code stringlengths 82 53.2k | code_codestyle int64 0 721 | style_context stringlengths 91 41.9k | style_context_codestyle int64 0 699 | label int64 0 1 |
|---|---|---|---|---|
from statistics import mean
import numpy as np
def A ( lowercase__ : list , lowercase__ : list , lowercase__ : list , lowercase__ : int ) -> list:
UpperCamelCase__ :Optional[Any] = 0
# Number of processes finished
UpperCamelCase__ :List[str] = 0
# Displays the finished process.
# If it is 0, the performance is completed if it is 1, before the performance.
UpperCamelCase__ :Optional[Any] = [0] * no_of_process
# List to include calculation results
UpperCamelCase__ :Tuple = [0] * no_of_process
# Sort by arrival time.
UpperCamelCase__ :Dict = [burst_time[i] for i in np.argsort(lowercase__ )]
UpperCamelCase__ :Tuple = [process_name[i] for i in np.argsort(lowercase__ )]
arrival_time.sort()
while no_of_process > finished_process_count:
UpperCamelCase__ :Union[str, Any] = 0
while finished_process[i] == 1:
i += 1
if current_time < arrival_time[i]:
UpperCamelCase__ :List[Any] = arrival_time[i]
UpperCamelCase__ :int = 0
# Index showing the location of the process being performed
UpperCamelCase__ :List[str] = 0
# Saves the current response ratio.
UpperCamelCase__ :Union[str, Any] = 0
for i in range(0 , lowercase__ ):
if finished_process[i] == 0 and arrival_time[i] <= current_time:
UpperCamelCase__ :List[str] = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[
i
]
if response_ratio < temp:
UpperCamelCase__ :Union[str, Any] = temp
UpperCamelCase__ :Optional[Any] = i
# Calculate the turn around time
UpperCamelCase__ :Optional[Any] = current_time + burst_time[loc] - arrival_time[loc]
current_time += burst_time[loc]
# Indicates that the process has been performed.
UpperCamelCase__ :Union[str, Any] = 1
# Increase finished_process_count by 1
finished_process_count += 1
return turn_around_time
def A ( lowercase__ : list , lowercase__ : list , lowercase__ : list , lowercase__ : int ) -> list:
UpperCamelCase__ :List[str] = [0] * no_of_process
for i in range(0 , lowercase__ ):
UpperCamelCase__ :List[str] = turn_around_time[i] - burst_time[i]
return waiting_time
if __name__ == "__main__":
UpperCamelCase = 5
UpperCamelCase = ["A", "B", "C", "D", "E"]
UpperCamelCase = [1, 2, 3, 4, 5]
UpperCamelCase = [1, 2, 3, 4, 5]
UpperCamelCase = calculate_turn_around_time(
process_name, arrival_time, burst_time, no_of_process
)
UpperCamelCase = calculate_waiting_time(
process_name, turn_around_time, burst_time, no_of_process
)
print("Process name \tArrival time \tBurst time \tTurn around time \tWaiting time")
for i in range(0, no_of_process):
print(
f'''{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t'''
f'''{turn_around_time[i]}\t\t\t{waiting_time[i]}'''
)
print(f'''average waiting time : {mean(waiting_time):.5f}''')
print(f'''average turn around time : {mean(turn_around_time):.5f}''') | 45 |
import numpy as np
from cva import destroyAllWindows, imread, imshow, waitKey
class lowercase :
'''simple docstring'''
def __init__(self , __a , __a , __a ) -> Union[str, Any]:
"""simple docstring"""
if dst_width < 0 or dst_height < 0:
raise ValueError('Destination width/height should be > 0' )
UpperCAmelCase__ = img
UpperCAmelCase__ = img.shape[1]
UpperCAmelCase__ = img.shape[0]
UpperCAmelCase__ = dst_width
UpperCAmelCase__ = dst_height
UpperCAmelCase__ = self.src_w / self.dst_w
UpperCAmelCase__ = self.src_h / self.dst_h
UpperCAmelCase__ = UpperCAmelCase__ = (
np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 255
)
def UpperCamelCase__ (self ) -> Tuple:
"""simple docstring"""
for i in range(self.dst_h ):
for j in range(self.dst_w ):
UpperCAmelCase__ = self.img[self.get_y(__a )][self.get_x(__a )]
def UpperCamelCase__ (self , __a ) -> int:
"""simple docstring"""
return int(self.ratio_x * x )
def UpperCamelCase__ (self , __a ) -> int:
"""simple docstring"""
return int(self.ratio_y * y )
if __name__ == "__main__":
_UpperCamelCase , _UpperCamelCase = 800, 600
_UpperCamelCase = imread('''image_data/lena.jpg''', 1)
_UpperCamelCase = NearestNeighbour(im, dst_w, dst_h)
n.process()
imshow(
F"""Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}""", n.output
)
waitKey(0)
destroyAllWindows()
| 146 | 0 |
import argparse
import json
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
from accelerate.utils.deepspeed import DummyOptim, DummyScheduler
SCREAMING_SNAKE_CASE : Optional[int] = 16
SCREAMING_SNAKE_CASE : int = 32
def UpperCamelCase ( _a , _a = 1_6 , _a = "bert-base-cased" ) -> Optional[Any]:
'''simple docstring'''
lowercase_ :Optional[int] = AutoTokenizer.from_pretrained(_a )
lowercase_ :Any = load_dataset('''glue''' , '''mrpc''' )
def tokenize_function(_a ):
# max_length=None => use the model max length (it's actually the default)
lowercase_ :Optional[int] = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=_a , max_length=_a )
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
lowercase_ :str = datasets.map(
_a , batched=_a , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , load_from_cache_file=_a )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
lowercase_ :Union[str, Any] = tokenized_datasets.rename_column('''label''' , '''labels''' )
def collate_fn(_a ):
# 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(_a , padding='''max_length''' , max_length=1_2_8 , return_tensors='''pt''' )
return tokenizer.pad(_a , padding='''longest''' , return_tensors='''pt''' )
# Instantiate dataloaders.
lowercase_ :int = DataLoader(
tokenized_datasets['''train'''] , shuffle=_a , collate_fn=_a , batch_size=_a )
lowercase_ :Optional[Any] = DataLoader(
tokenized_datasets['''validation'''] , shuffle=_a , collate_fn=_a , batch_size=_a )
return train_dataloader, eval_dataloader
def UpperCamelCase ( _a , _a , _a , _a ) -> Optional[Any]:
'''simple docstring'''
model.eval()
lowercase_ :List[str] = 0
for step, batch in enumerate(_a ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
lowercase_ :Optional[int] = model(**_a )
lowercase_ :Optional[int] = outputs.logits.argmax(dim=-1 )
# It is slightly faster to call this once, than multiple times
lowercase_ , lowercase_ :Optional[Any] = accelerator.gather(
(predictions, batch['''labels''']) ) # If we are in a multiprocess environment, the last batch has duplicates
if accelerator.use_distributed:
if step == len(_a ) - 1:
lowercase_ :Union[str, Any] = predictions[: len(eval_dataloader.dataset ) - samples_seen]
lowercase_ :str = references[: len(eval_dataloader.dataset ) - samples_seen]
else:
samples_seen += references.shape[0]
metric.add_batch(
predictions=_a , references=_a , )
lowercase_ :str = metric.compute()
return eval_metric["accuracy"]
def UpperCamelCase ( _a , _a ) -> Tuple:
'''simple docstring'''
lowercase_ :str = Accelerator()
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
lowercase_ :str = config['''lr''']
lowercase_ :int = int(config['''num_epochs'''] )
lowercase_ :Optional[int] = int(config['''seed'''] )
lowercase_ :int = int(config['''batch_size'''] )
lowercase_ :Tuple = args.model_name_or_path
set_seed(_a )
lowercase_ , lowercase_ :Any = get_dataloaders(_a , _a , _a )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
lowercase_ :Tuple = AutoModelForSequenceClassification.from_pretrained(_a , return_dict=_a )
# Instantiate optimizer
lowercase_ :List[Any] = (
AdamW
if accelerator.state.deepspeed_plugin is None
or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config
else DummyOptim
)
lowercase_ :Union[str, Any] = optimizer_cls(params=model.parameters() , lr=_a )
if accelerator.state.deepspeed_plugin is not None:
lowercase_ :Optional[int] = accelerator.state.deepspeed_plugin.deepspeed_config[
'''gradient_accumulation_steps'''
]
else:
lowercase_ :Any = 1
lowercase_ :Union[str, Any] = (len(_a ) * num_epochs) // gradient_accumulation_steps
# Instantiate scheduler
if (
accelerator.state.deepspeed_plugin is None
or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
):
lowercase_ :Tuple = get_linear_schedule_with_warmup(
optimizer=_a , num_warmup_steps=0 , num_training_steps=_a , )
else:
lowercase_ :List[Any] = DummyScheduler(_a , total_num_steps=_a , 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.
lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ :Tuple = accelerator.prepare(
_a , _a , _a , _a , _a )
# We need to keep track of how many total steps we have iterated over
lowercase_ :Optional[int] = 0
# We also need to keep track of the stating epoch so files are named properly
lowercase_ :List[Any] = 0
lowercase_ :List[str] = evaluate.load('''glue''' , '''mrpc''' )
lowercase_ :List[Any] = num_epochs
if args.partial_train_epoch is not None:
lowercase_ :str = args.partial_train_epoch
if args.resume_from_checkpoint:
accelerator.load_state(args.resume_from_checkpoint )
lowercase_ :List[Any] = args.resume_from_checkpoint.split('''epoch_''' )[1]
lowercase_ :Optional[Any] = ''''''
for char in epoch_string:
if char.isdigit():
state_epoch_num += char
else:
break
lowercase_ :Optional[int] = int(_a ) + 1
lowercase_ :Any = evaluation_loop(_a , _a , _a , _a )
accelerator.print('''resumed checkpoint performance:''' , _a )
accelerator.print('''resumed checkpoint\'s scheduler\'s lr:''' , lr_scheduler.get_lr()[0] )
accelerator.print('''resumed optimizers\'s lr:''' , optimizer.param_groups[0]['''lr'''] )
with open(os.path.join(args.output_dir , f"state_{starting_epoch-1}.json" ) , '''r''' ) as f:
lowercase_ :str = json.load(_a )
assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed"
assert (
resumed_state["lr"] == lr_scheduler.get_lr()[0]
), "Scheduler learning rate mismatch, loading from checkpoint failed"
assert (
resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"]
), "Optimizer learning rate mismatch, loading from checkpoint failed"
assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed"
return
# Now we train the model
lowercase_ :int = {}
for epoch in range(_a , _a ):
model.train()
for step, batch in enumerate(_a ):
lowercase_ :List[Any] = model(**_a )
lowercase_ :Dict = outputs.loss
lowercase_ :Optional[Any] = loss / gradient_accumulation_steps
accelerator.backward(_a )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
overall_step += 1
lowercase_ :List[str] = f"epoch_{epoch}"
lowercase_ :str = os.path.join(args.output_dir , _a )
accelerator.save_state(_a )
lowercase_ :List[str] = evaluation_loop(_a , _a , _a , _a )
lowercase_ :Any = accuracy
lowercase_ :List[str] = lr_scheduler.get_lr()[0]
lowercase_ :int = optimizer.param_groups[0]['''lr''']
lowercase_ :int = epoch
lowercase_ :Dict = overall_step
accelerator.print(f"epoch {epoch}:" , _a )
accelerator.wait_for_everyone()
if accelerator.is_main_process:
with open(os.path.join(args.output_dir , f"state_{epoch}.json" ) , '''w''' ) as f:
json.dump(_a , _a )
def UpperCamelCase ( ) -> int:
'''simple docstring'''
lowercase_ :str = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' )
parser.add_argument(
'''--model_name_or_path''' , type=_a , default='''bert-base-cased''' , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , required=_a , )
parser.add_argument(
'''--output_dir''' , type=_a , 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=_a , default=_a , help='''If the training should continue from a checkpoint folder.''' , )
parser.add_argument(
'''--partial_train_epoch''' , type=_a , default=_a , help='''If passed, the training will stop after this number of epochs.''' , )
parser.add_argument(
'''--num_epochs''' , type=_a , default=2 , help='''Number of train epochs.''' , )
lowercase_ :Dict = parser.parse_args()
lowercase_ :Optional[int] = {'''lr''': 2E-5, '''num_epochs''': args.num_epochs, '''seed''': 4_2, '''batch_size''': 1_6}
training_function(_a , _a )
if __name__ == "__main__":
main()
| 441 |
import argparse
import pickle
import numpy as np
import torch
from torch import nn
from transformers import ReformerConfig, ReformerModelWithLMHead
from transformers.utils import logging
logging.set_verbosity_info()
def UpperCamelCase ( _a , _a , _a=None ) -> Dict:
'''simple docstring'''
assert torch_layer.weight.shape == weight.shape, f"{torch_layer} layer.weight does not match"
lowercase_ :str = nn.Parameter(_a )
if bias is not None:
assert torch_layer.bias.shape == bias.shape, f"{torch_layer} layer.bias does not match"
lowercase_ :List[str] = nn.Parameter(_a )
def UpperCamelCase ( _a , _a , _a ) -> List[str]:
'''simple docstring'''
lowercase_ :Optional[int] = np.asarray(weights[0] )
lowercase_ :str = np.asarray(weights[1] )
lowercase_ :Union[str, Any] = np.asarray(weights[2] )
set_param(
torch_layer.self_attention.query_key , torch.tensor(_a ).transpose(1 , 2 ).contiguous().view(-1 , _a ) , )
set_param(
torch_layer.self_attention.value , torch.tensor(_a ).transpose(1 , 2 ).contiguous().view(-1 , _a ) , )
set_param(
torch_layer.output.dense , torch.tensor(_a ).view(-1 , _a ).contiguous().transpose(0 , 1 ) , )
def UpperCamelCase ( _a , _a , _a ) -> Optional[int]:
'''simple docstring'''
lowercase_ :Union[str, Any] = np.asarray(weights[0] )
lowercase_ :Tuple = np.asarray(weights[1] )
lowercase_ :List[Any] = np.asarray(weights[2] )
lowercase_ :Optional[int] = np.asarray(weights[3] )
set_param(
torch_layer.self_attention.query , torch.tensor(_a ).transpose(1 , 2 ).contiguous().view(-1 , _a ) , )
set_param(
torch_layer.self_attention.key , torch.tensor(_a ).transpose(1 , 2 ).contiguous().view(-1 , _a ) , )
set_param(
torch_layer.self_attention.value , torch.tensor(_a ).transpose(1 , 2 ).contiguous().view(-1 , _a ) , )
set_param(
torch_layer.output.dense , torch.tensor(_a ).view(-1 , _a ).contiguous().transpose(0 , 1 ) , )
def UpperCamelCase ( _a , _a , _a ) -> Optional[Any]:
'''simple docstring'''
lowercase_ :List[str] = weights[0][0][0]
lowercase_ :Optional[Any] = np.asarray(layer_norm_a[0] )
lowercase_ :Any = np.asarray(layer_norm_a[1] )
set_param(
torch_block.attention.layer_norm , torch.tensor(_a ) , torch.tensor(_a ) , )
# lsh weights + output
lowercase_ :int = weights[0][1]
if len(_a ) < 4:
set_layer_weights_in_torch_lsh(_a , torch_block.attention , _a )
else:
set_layer_weights_in_torch_local(_a , torch_block.attention , _a )
# intermediate weighs
lowercase_ :Optional[int] = weights[2][0][1][2]
# Chunked Feed Forward
if len(_a ) == 4:
lowercase_ :Tuple = intermediate_weights[2]
# layernorm 2
lowercase_ :int = np.asarray(intermediate_weights[0][0] )
lowercase_ :Any = np.asarray(intermediate_weights[0][1] )
set_param(
torch_block.feed_forward.layer_norm , torch.tensor(_a ) , torch.tensor(_a ) , )
# intermediate dense
lowercase_ :Any = np.asarray(intermediate_weights[1][0] )
lowercase_ :int = np.asarray(intermediate_weights[1][1] )
set_param(
torch_block.feed_forward.dense.dense , torch.tensor(_a ).transpose(0 , 1 ).contiguous() , torch.tensor(_a ) , )
# intermediate out
lowercase_ :Optional[int] = np.asarray(intermediate_weights[4][0] )
lowercase_ :Any = np.asarray(intermediate_weights[4][1] )
set_param(
torch_block.feed_forward.output.dense , torch.tensor(_a ).transpose(0 , 1 ).contiguous() , torch.tensor(_a ) , )
def UpperCamelCase ( _a , _a , _a ) -> Optional[Any]:
'''simple docstring'''
lowercase_ :Any = torch_model.reformer
# word embeds
lowercase_ :int = np.asarray(weights[1] )
set_param(
torch_model_reformer.embeddings.word_embeddings , torch.tensor(_a ) , )
if isinstance(weights[3] , _a ):
lowercase_ :Union[str, Any] = torch_model_reformer.embeddings.position_embeddings
for emb_idx in range(len(position_embeddings.weights ) ):
lowercase_ :Tuple = np.asarray(weights[3][emb_idx][0] )
assert (
position_embeddings.weights[emb_idx].shape == emb_weights.shape
), f"{position_embeddings[emb_idx]} emb does not match"
lowercase_ :Optional[int] = nn.Parameter(torch.tensor(_a ) )
lowercase_ :Any = weights[5]
assert len(torch_model_reformer.encoder.layers ) * 4 == len(
_a ), "HF and trax model do not have the same number of layers"
for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ):
lowercase_ :int = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)]
set_block_weights_in_torch(_a , _a , _a )
# output layer norm
lowercase_ :Optional[Any] = np.asarray(weights[7][0] )
lowercase_ :int = np.asarray(weights[7][1] )
set_param(
torch_model_reformer.encoder.layer_norm , torch.tensor(_a ) , torch.tensor(_a ) , )
# output embeddings
lowercase_ :Optional[int] = np.asarray(weights[9][0] )
lowercase_ :Union[str, Any] = np.asarray(weights[9][1] )
set_param(
torch_model.lm_head.decoder , torch.tensor(_a ).transpose(0 , 1 ).contiguous() , torch.tensor(_a ) , )
def UpperCamelCase ( _a , _a , _a ) -> str:
'''simple docstring'''
lowercase_ :List[str] = ReformerConfig.from_json_file(_a )
print(f"Building PyTorch model from configuration: {config}" )
lowercase_ :List[str] = ReformerModelWithLMHead(_a )
with open(_a , '''rb''' ) as f:
lowercase_ :Dict = pickle.load(_a )['''weights''']
set_model_weights_in_torch(_a , _a , config.hidden_size )
# Save pytorch-model
print(f"Save PyTorch model to {pytorch_dump_path}" )
torch.save(model.state_dict() , _a )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE : Optional[int] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--trax_model_pkl_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
)
parser.add_argument(
"--config_file",
default=None,
type=str,
required=True,
help=(
"The config json file corresponding to the pre-trained Reformer 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."
)
SCREAMING_SNAKE_CASE : Dict = parser.parse_args()
convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
| 441 | 1 |
"""simple docstring"""
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel
from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device
enable_full_determinism()
class lowerCAmelCase__ ( unittest.TestCase ):
@property
def lowercase ( self : Union[str, Any] ):
torch.manual_seed(0 )
_snake_case = UNetaDModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , )
return model
@property
def lowercase ( self : str ):
torch.manual_seed(0 )
_snake_case = VQModel(
block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=3 , )
return model
@property
def lowercase ( self : Tuple ):
torch.manual_seed(0 )
_snake_case = 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 , )
return CLIPTextModel(_lowerCamelCase )
def lowercase ( self : Tuple ):
_snake_case = self.dummy_uncond_unet
_snake_case = DDIMScheduler()
_snake_case = self.dummy_vq_model
_snake_case = LDMPipeline(unet=_lowerCamelCase , vqvae=_lowerCamelCase , scheduler=_lowerCamelCase )
ldm.to(_lowerCamelCase )
ldm.set_progress_bar_config(disable=_lowerCamelCase )
_snake_case = torch.manual_seed(0 )
_snake_case = ldm(generator=_lowerCamelCase , num_inference_steps=2 , output_type='''numpy''' ).images
_snake_case = torch.manual_seed(0 )
_snake_case = ldm(generator=_lowerCamelCase , num_inference_steps=2 , output_type='''numpy''' , return_dict=_lowerCamelCase )[0]
_snake_case = image[0, -3:, -3:, -1]
_snake_case = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
_snake_case = np.array([0.8_5_1_2, 0.8_1_8, 0.6_4_1_1, 0.6_8_0_8, 0.4_4_6_5, 0.5_6_1_8, 0.4_6, 0.6_2_3_1, 0.5_1_7_2] )
_snake_case = 1e-2 if torch_device != '''mps''' else 3e-2
assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance
@slow
@require_torch
class lowerCAmelCase__ ( unittest.TestCase ):
def lowercase ( self : Optional[int] ):
_snake_case = LDMPipeline.from_pretrained('''CompVis/ldm-celebahq-256''' )
ldm.to(_lowerCamelCase )
ldm.set_progress_bar_config(disable=_lowerCamelCase )
_snake_case = torch.manual_seed(0 )
_snake_case = ldm(generator=_lowerCamelCase , num_inference_steps=5 , output_type='''numpy''' ).images
_snake_case = image[0, -3:, -3:, -1]
assert image.shape == (1, 256, 256, 3)
_snake_case = np.array([0.4_3_9_9, 0.4_4_9_7_5, 0.4_6_8_2_5, 0.4_7_4, 0.4_3_5_9, 0.4_5_8_1, 0.4_5_0_9_5, 0.4_3_4_1, 0.4_4_4_7] )
_snake_case = 1e-2 if torch_device != '''mps''' else 3e-2
assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
| 224 |
"""simple docstring"""
from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError
import requests
def _UpperCAmelCase ( __lowerCamelCase : str = "isbn/0140328726" ) -> dict:
_snake_case = olid.strip().strip('''/''' ) # Remove leading/trailing whitespace & slashes
if new_olid.count('''/''' ) != 1:
_snake_case = f'''{olid} is not a valid Open Library olid'''
raise ValueError(__lowerCamelCase )
return requests.get(f'''https://openlibrary.org/{new_olid}.json''' ).json()
def _UpperCAmelCase ( __lowerCamelCase : dict ) -> dict:
_snake_case = {
'''title''': '''Title''',
'''publish_date''': '''Publish date''',
'''authors''': '''Authors''',
'''number_of_pages''': '''Number of pages:''',
'''first_sentence''': '''First sentence''',
'''isbn_10''': '''ISBN (10)''',
'''isbn_13''': '''ISBN (13)''',
}
_snake_case = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()}
_snake_case = [
get_openlibrary_data(author['''key'''] )['''name'''] for author in data['''Authors''']
]
_snake_case = data['''First sentence''']['''value''']
for key, value in data.items():
if isinstance(__lowerCamelCase , __lowerCamelCase ):
_snake_case = ''', '''.join(__lowerCamelCase )
return data
if __name__ == "__main__":
import doctest
doctest.testmod()
while True:
UpperCAmelCase__ = input('\nEnter the ISBN code to search (or \'quit\' to stop): ').strip()
if isbn.lower() in ("", "q", "quit", "exit", "stop"):
break
if len(isbn) not in (10, 13) or not isbn.isdigit():
print(F"Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.")
continue
print(F"\nSearching Open Library for ISBN: {isbn}...\n")
try:
UpperCAmelCase__ = summarize_book(get_openlibrary_data(F"isbn/{isbn}"))
print('\n'.join(F"{key}: {value}" for key, value in book_summary.items()))
except JSONDecodeError: # Workaround for requests.exceptions.RequestException:
print(F"Sorry, there are no results for ISBN: {isbn}.")
| 224 | 1 |
"""simple docstring"""
from cva import destroyAllWindows, imread, imshow, waitKey
def lowercase ( a__ : Dict ) -> str:
_UpperCamelCase , _UpperCamelCase = img.shape[0], img.shape[1]
# converting each pixel's color to its negative
for i in range(a__ ):
for j in range(a__ ):
_UpperCamelCase = [255, 255, 255] - img[i][j]
return img
if __name__ == "__main__":
# read original image
UpperCAmelCase = imread("""image_data/lena.jpg""", 1)
# convert to its negative
UpperCAmelCase = convert_to_negative(img)
# show result image
imshow("""negative of original image""", img)
waitKey(0)
destroyAllWindows()
| 703 | """simple docstring"""
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import PaddingStrategy, logging
from .tokenization_realm import RealmTokenizer
UpperCAmelCase = logging.get_logger(__name__)
UpperCAmelCase = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""}
UpperCAmelCase = {
"""vocab_file""": {
"""google/realm-cc-news-pretrained-embedder""": (
"""https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt"""
),
"""google/realm-cc-news-pretrained-encoder""": (
"""https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt"""
),
"""google/realm-cc-news-pretrained-scorer""": (
"""https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt"""
),
"""google/realm-cc-news-pretrained-openqa""": (
"""https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt"""
),
"""google/realm-orqa-nq-openqa""": """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt""",
"""google/realm-orqa-nq-reader""": """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt""",
"""google/realm-orqa-wq-openqa""": """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt""",
"""google/realm-orqa-wq-reader""": """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt""",
},
"""tokenizer_file""": {
"""google/realm-cc-news-pretrained-embedder""": (
"""https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont"""
),
"""google/realm-cc-news-pretrained-encoder""": (
"""https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json"""
),
"""google/realm-cc-news-pretrained-scorer""": (
"""https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json"""
),
"""google/realm-cc-news-pretrained-openqa""": (
"""https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json"""
),
"""google/realm-orqa-nq-openqa""": (
"""https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json"""
),
"""google/realm-orqa-nq-reader""": (
"""https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json"""
),
"""google/realm-orqa-wq-openqa""": (
"""https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json"""
),
"""google/realm-orqa-wq-reader""": (
"""https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json"""
),
},
}
UpperCAmelCase = {
"""google/realm-cc-news-pretrained-embedder""": 512,
"""google/realm-cc-news-pretrained-encoder""": 512,
"""google/realm-cc-news-pretrained-scorer""": 512,
"""google/realm-cc-news-pretrained-openqa""": 512,
"""google/realm-orqa-nq-openqa""": 512,
"""google/realm-orqa-nq-reader""": 512,
"""google/realm-orqa-wq-openqa""": 512,
"""google/realm-orqa-wq-reader""": 512,
}
UpperCAmelCase = {
"""google/realm-cc-news-pretrained-embedder""": {"""do_lower_case""": True},
"""google/realm-cc-news-pretrained-encoder""": {"""do_lower_case""": True},
"""google/realm-cc-news-pretrained-scorer""": {"""do_lower_case""": True},
"""google/realm-cc-news-pretrained-openqa""": {"""do_lower_case""": True},
"""google/realm-orqa-nq-openqa""": {"""do_lower_case""": True},
"""google/realm-orqa-nq-reader""": {"""do_lower_case""": True},
"""google/realm-orqa-wq-openqa""": {"""do_lower_case""": True},
"""google/realm-orqa-wq-reader""": {"""do_lower_case""": True},
}
class UpperCAmelCase_ ( _lowercase):
snake_case__ = VOCAB_FILES_NAMES
snake_case__ = PRETRAINED_VOCAB_FILES_MAP
snake_case__ = PRETRAINED_INIT_CONFIGURATION
snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
snake_case__ = RealmTokenizer
def __init__( self : Dict , __UpperCamelCase : Any=None , __UpperCamelCase : Optional[Any]=None , __UpperCamelCase : str=True , __UpperCamelCase : Tuple="[UNK]" , __UpperCamelCase : List[str]="[SEP]" , __UpperCamelCase : Tuple="[PAD]" , __UpperCamelCase : Union[str, Any]="[CLS]" , __UpperCamelCase : Optional[int]="[MASK]" , __UpperCamelCase : Optional[int]=True , __UpperCamelCase : Union[str, Any]=None , **__UpperCamelCase : List[Any] , ) -> Any:
super().__init__(
__UpperCamelCase , tokenizer_file=__UpperCamelCase , do_lower_case=__UpperCamelCase , unk_token=__UpperCamelCase , sep_token=__UpperCamelCase , pad_token=__UpperCamelCase , cls_token=__UpperCamelCase , mask_token=__UpperCamelCase , tokenize_chinese_chars=__UpperCamelCase , strip_accents=__UpperCamelCase , **__UpperCamelCase , )
_UpperCamelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() )
if (
normalizer_state.get('''lowercase''' , __UpperCamelCase ) != do_lower_case
or normalizer_state.get('''strip_accents''' , __UpperCamelCase ) != strip_accents
or normalizer_state.get('''handle_chinese_chars''' , __UpperCamelCase ) != tokenize_chinese_chars
):
_UpperCamelCase = getattr(__UpperCamelCase , normalizer_state.pop('''type''' ) )
_UpperCamelCase = do_lower_case
_UpperCamelCase = strip_accents
_UpperCamelCase = tokenize_chinese_chars
_UpperCamelCase = normalizer_class(**__UpperCamelCase )
_UpperCamelCase = do_lower_case
def _UpperCamelCase ( self : int , __UpperCamelCase : Any , **__UpperCamelCase : Optional[Any] ) -> str:
_UpperCamelCase = PaddingStrategy.MAX_LENGTH
_UpperCamelCase = text
_UpperCamelCase = kwargs.pop('''text_pair''' , __UpperCamelCase )
_UpperCamelCase = kwargs.pop('''return_tensors''' , __UpperCamelCase )
_UpperCamelCase = {
'''input_ids''': [],
'''attention_mask''': [],
'''token_type_ids''': [],
}
for idx, candidate_text in enumerate(__UpperCamelCase ):
if batch_text_pair is not None:
_UpperCamelCase = batch_text_pair[idx]
else:
_UpperCamelCase = None
_UpperCamelCase = super().__call__(__UpperCamelCase , __UpperCamelCase , return_tensors=__UpperCamelCase , **__UpperCamelCase )
_UpperCamelCase = encoded_candidates.get('''input_ids''' )
_UpperCamelCase = encoded_candidates.get('''attention_mask''' )
_UpperCamelCase = encoded_candidates.get('''token_type_ids''' )
if encoded_input_ids is not None:
output_data["input_ids"].append(__UpperCamelCase )
if encoded_attention_mask is not None:
output_data["attention_mask"].append(__UpperCamelCase )
if encoded_token_type_ids is not None:
output_data["token_type_ids"].append(__UpperCamelCase )
_UpperCamelCase = {key: item for key, item in output_data.items() if len(__UpperCamelCase ) != 0}
return BatchEncoding(__UpperCamelCase , tensor_type=__UpperCamelCase )
def _UpperCamelCase ( self : List[Any] , __UpperCamelCase : Dict , __UpperCamelCase : Union[str, Any]=None ) -> int:
_UpperCamelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id]
if token_ids_a:
output += token_ids_a + [self.sep_token_id]
return output
def _UpperCamelCase ( self : Union[str, Any] , __UpperCamelCase : List[int] , __UpperCamelCase : Optional[List[int]] = None ) -> List[int]:
_UpperCamelCase = [self.sep_token_id]
_UpperCamelCase = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def _UpperCamelCase ( self : List[str] , __UpperCamelCase : str , __UpperCamelCase : Optional[str] = None ) -> Tuple[str]:
_UpperCamelCase = self._tokenizer.model.save(__UpperCamelCase , name=__UpperCamelCase )
return tuple(__UpperCamelCase )
| 342 | 0 |
def lowerCamelCase_ ( UpperCAmelCase__ ):
"""simple docstring"""
assert column_title.isupper()
a_ = 0
a_ = len(_lowerCamelCase ) - 1
a_ = 0
while index >= 0:
a_ = (ord(column_title[index] ) - 64) * pow(26 , _lowerCamelCase )
answer += value
power += 1
index -= 1
return answer
if __name__ == "__main__":
from doctest import testmod
testmod() | 483 |
"""simple docstring"""
import unittest
from datasets import load_dataset
from transformers.pipelines import pipeline
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow
@is_pipeline_test
@require_torch
class a ( unittest.TestCase ):
@require_torch
def UpperCamelCase ( self : str ) -> str:
lowerCamelCase_ = pipeline(
task='zero-shot-audio-classification' , model='hf-internal-testing/tiny-clap-htsat-unfused' )
lowerCamelCase_ = load_dataset('ashraq/esc50' )
lowerCamelCase_ = dataset['train']['audio'][-1]['array']
lowerCamelCase_ = audio_classifier(__SCREAMING_SNAKE_CASE , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] )
self.assertEqual(
nested_simplify(__SCREAMING_SNAKE_CASE ) , [{'score': 0.501, 'label': 'Sound of a dog'}, {'score': 0.499, 'label': 'Sound of vaccum cleaner'}] , )
@unittest.skip('No models are available in TF' )
def UpperCamelCase ( self : Tuple ) -> Optional[Any]:
pass
@slow
@require_torch
def UpperCamelCase ( self : Optional[Any] ) -> Optional[Any]:
lowerCamelCase_ = pipeline(
task='zero-shot-audio-classification' , model='laion/clap-htsat-unfused' , )
# This is an audio of a dog
lowerCamelCase_ = load_dataset('ashraq/esc50' )
lowerCamelCase_ = dataset['train']['audio'][-1]['array']
lowerCamelCase_ = audio_classifier(__SCREAMING_SNAKE_CASE , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] )
self.assertEqual(
nested_simplify(__SCREAMING_SNAKE_CASE ) , [
{'score': 0.999, 'label': 'Sound of a dog'},
{'score': 0.001, 'label': 'Sound of vaccum cleaner'},
] , )
lowerCamelCase_ = audio_classifier([audio] * 5 , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] )
self.assertEqual(
nested_simplify(__SCREAMING_SNAKE_CASE ) , [
[
{'score': 0.999, 'label': 'Sound of a dog'},
{'score': 0.001, 'label': 'Sound of vaccum cleaner'},
],
]
* 5 , )
lowerCamelCase_ = audio_classifier(
[audio] * 5 , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] , batch_size=5 )
self.assertEqual(
nested_simplify(__SCREAMING_SNAKE_CASE ) , [
[
{'score': 0.999, 'label': 'Sound of a dog'},
{'score': 0.001, 'label': 'Sound of vaccum cleaner'},
],
]
* 5 , )
@unittest.skip('No models are available in TF' )
def UpperCamelCase ( self : Optional[int] ) -> int:
pass
| 549 | 0 |
"""simple docstring"""
import argparse
import json
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from torchvision import transforms
from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification
from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling
def _lowerCAmelCase ( lowerCamelCase__ : List[str] ) -> Optional[int]:
_SCREAMING_SNAKE_CASE : Tuple = [2, 2, 6, 2] if "tiny" in model_name else [2, 2, 1_8, 2]
_SCREAMING_SNAKE_CASE : Tuple = True if "large" in model_name or "huge" in model_name else False
_SCREAMING_SNAKE_CASE : Optional[int] = True if "large" in model_name or "huge" in model_name else False
_SCREAMING_SNAKE_CASE : Tuple = True if "large" in model_name or "huge" in model_name else False
if "large" in model_name or "xlarge" in model_name or "huge" in model_name:
if "fl3" in model_name:
_SCREAMING_SNAKE_CASE : str = [3, 3, 3, 3]
_SCREAMING_SNAKE_CASE : int = [5, 5, 5, 5]
elif "fl4" in model_name:
_SCREAMING_SNAKE_CASE : int = [4, 4, 4, 4]
_SCREAMING_SNAKE_CASE : Optional[int] = [3, 3, 3, 3]
if "tiny" in model_name or "small" in model_name or "base" in model_name:
_SCREAMING_SNAKE_CASE : Union[str, Any] = [3, 3, 3, 3]
if "lrf" in model_name:
_SCREAMING_SNAKE_CASE : Any = [3, 3, 3, 3]
else:
_SCREAMING_SNAKE_CASE : str = [2, 2, 2, 2]
if "tiny" in model_name:
_SCREAMING_SNAKE_CASE : Any = 9_6
elif "small" in model_name:
_SCREAMING_SNAKE_CASE : Optional[int] = 9_6
elif "base" in model_name:
_SCREAMING_SNAKE_CASE : List[str] = 1_2_8
elif "large" in model_name:
_SCREAMING_SNAKE_CASE : Dict = 1_9_2
elif "xlarge" in model_name:
_SCREAMING_SNAKE_CASE : Union[str, Any] = 2_5_6
elif "huge" in model_name:
_SCREAMING_SNAKE_CASE : Optional[Any] = 3_5_2
# set label information
_SCREAMING_SNAKE_CASE : Tuple = "huggingface/label-files"
if "large" in model_name or "huge" in model_name:
_SCREAMING_SNAKE_CASE : Dict = "imagenet-22k-id2label.json"
else:
_SCREAMING_SNAKE_CASE : Optional[Any] = "imagenet-1k-id2label.json"
_SCREAMING_SNAKE_CASE : int = json.load(open(hf_hub_download(lowerCamelCase__, lowerCamelCase__, repo_type="dataset" ), "r" ) )
_SCREAMING_SNAKE_CASE : Tuple = {int(lowerCamelCase__ ): v for k, v in idalabel.items()}
_SCREAMING_SNAKE_CASE : int = {v: k for k, v in idalabel.items()}
_SCREAMING_SNAKE_CASE : Union[str, Any] = FocalNetConfig(
embed_dim=lowerCamelCase__, depths=lowerCamelCase__, focal_levels=lowerCamelCase__, focal_windows=lowerCamelCase__, use_conv_embed=lowerCamelCase__, idalabel=lowerCamelCase__, labelaid=lowerCamelCase__, use_post_layernorm=lowerCamelCase__, use_layerscale=lowerCamelCase__, )
return config
def _lowerCAmelCase ( lowerCamelCase__ : int ) -> int:
if "patch_embed.proj" in name:
_SCREAMING_SNAKE_CASE : Any = name.replace("patch_embed.proj", "embeddings.patch_embeddings.projection" )
if "patch_embed.norm" in name:
_SCREAMING_SNAKE_CASE : Tuple = name.replace("patch_embed.norm", "embeddings.norm" )
if "layers" in name:
_SCREAMING_SNAKE_CASE : Optional[int] = "encoder." + name
if "encoder.layers" in name:
_SCREAMING_SNAKE_CASE : int = name.replace("encoder.layers", "encoder.stages" )
if "downsample.proj" in name:
_SCREAMING_SNAKE_CASE : int = name.replace("downsample.proj", "downsample.projection" )
if "blocks" in name:
_SCREAMING_SNAKE_CASE : List[Any] = name.replace("blocks", "layers" )
if "modulation.f.weight" in name or "modulation.f.bias" in name:
_SCREAMING_SNAKE_CASE : Tuple = name.replace("modulation.f", "modulation.projection_in" )
if "modulation.h.weight" in name or "modulation.h.bias" in name:
_SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("modulation.h", "modulation.projection_context" )
if "modulation.proj.weight" in name or "modulation.proj.bias" in name:
_SCREAMING_SNAKE_CASE : str = name.replace("modulation.proj", "modulation.projection_out" )
if name == "norm.weight":
_SCREAMING_SNAKE_CASE : int = "layernorm.weight"
if name == "norm.bias":
_SCREAMING_SNAKE_CASE : List[Any] = "layernorm.bias"
if "head" in name:
_SCREAMING_SNAKE_CASE : Optional[int] = name.replace("head", "classifier" )
else:
_SCREAMING_SNAKE_CASE : Union[str, Any] = "focalnet." + name
return name
def _lowerCAmelCase ( lowerCamelCase__ : List[Any], lowerCamelCase__ : Union[str, Any], lowerCamelCase__ : Optional[Any]=False ) -> Tuple:
# fmt: off
_SCREAMING_SNAKE_CASE : Optional[int] = {
"focalnet-tiny": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth",
"focalnet-tiny-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth",
"focalnet-small": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth",
"focalnet-small-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth",
"focalnet-base": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth",
"focalnet-base-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth",
"focalnet-large-lrf-fl3": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth",
"focalnet-large-lrf-fl4": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth",
"focalnet-xlarge-lrf-fl3": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth",
"focalnet-xlarge-lrf-fl4": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth",
}
# fmt: on
_SCREAMING_SNAKE_CASE : Union[str, Any] = model_name_to_url[model_name]
print("Checkpoint URL: ", lowerCamelCase__ )
_SCREAMING_SNAKE_CASE : str = torch.hub.load_state_dict_from_url(lowerCamelCase__, map_location="cpu" )["model"]
# rename keys
for key in state_dict.copy().keys():
_SCREAMING_SNAKE_CASE : Union[str, Any] = state_dict.pop(lowerCamelCase__ )
_SCREAMING_SNAKE_CASE : Optional[Any] = val
_SCREAMING_SNAKE_CASE : Optional[Any] = get_focalnet_config(lowerCamelCase__ )
_SCREAMING_SNAKE_CASE : Tuple = FocalNetForImageClassification(lowerCamelCase__ )
model.eval()
# load state dict
model.load_state_dict(lowerCamelCase__ )
# verify conversion
_SCREAMING_SNAKE_CASE : Tuple = "http://images.cocodataset.org/val2017/000000039769.jpg"
_SCREAMING_SNAKE_CASE : List[Any] = BitImageProcessor(
do_resize=lowerCamelCase__, size={"shortest_edge": 2_5_6}, resample=PILImageResampling.BILINEAR, do_center_crop=lowerCamelCase__, crop_size=2_2_4, do_normalize=lowerCamelCase__, image_mean=lowerCamelCase__, image_std=lowerCamelCase__, )
_SCREAMING_SNAKE_CASE : Tuple = Image.open(requests.get(lowerCamelCase__, stream=lowerCamelCase__ ).raw )
_SCREAMING_SNAKE_CASE : int = processor(images=lowerCamelCase__, return_tensors="pt" )
_SCREAMING_SNAKE_CASE : Optional[int] = transforms.Compose(
[
transforms.Resize(2_5_6 ),
transforms.CenterCrop(2_2_4 ),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ),
] )
_SCREAMING_SNAKE_CASE : Any = image_transforms(lowerCamelCase__ ).unsqueeze(0 )
# verify pixel_values
assert torch.allclose(inputs.pixel_values, lowerCamelCase__, atol=1E-4 )
_SCREAMING_SNAKE_CASE : Union[str, Any] = model(**lowerCamelCase__ )
_SCREAMING_SNAKE_CASE : Optional[int] = outputs.logits.argmax(-1 ).item()
print("Predicted class:", model.config.idalabel[predicted_class_idx] )
print("First values of logits:", outputs.logits[0, :3] )
if model_name == "focalnet-tiny":
_SCREAMING_SNAKE_CASE : Tuple = torch.tensor([0.2166, -0.4368, 0.2191] )
elif model_name == "focalnet-tiny-lrf":
_SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1.1669, 0.0125, -0.1695] )
elif model_name == "focalnet-small":
_SCREAMING_SNAKE_CASE : str = torch.tensor([0.4917, -0.0430, 0.1341] )
elif model_name == "focalnet-small-lrf":
_SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([-0.2588, -0.5342, -0.2331] )
elif model_name == "focalnet-base":
_SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([-0.1655, -0.4090, -0.1730] )
elif model_name == "focalnet-base-lrf":
_SCREAMING_SNAKE_CASE : int = torch.tensor([0.5306, -0.0483, -0.3928] )
assert torch.allclose(outputs.logits[0, :3], lowerCamelCase__, atol=1E-4 )
print("Looks ok!" )
if pytorch_dump_folder_path is not None:
print(f'''Saving model and processor of {model_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(lowerCamelCase__ )
processor.save_pretrained(lowerCamelCase__ )
if push_to_hub:
print(f'''Pushing model and processor of {model_name} to the hub...''' )
model.push_to_hub(f'''{model_name}''' )
processor.push_to_hub(f'''{model_name}''' )
if __name__ == "__main__":
lowercase_ : Dict = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--model_name''',
default='''focalnet-tiny''',
type=str,
help='''Name of the FocalNet model you\'d like to convert.''',
)
parser.add_argument(
'''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.'''
)
parser.add_argument(
'''--push_to_hub''',
action='''store_true''',
help='''Whether to push the model and processor to the hub.''',
)
lowercase_ : List[Any] = parser.parse_args()
convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 295 |
"""simple docstring"""
from __future__ import annotations
import time
from collections.abc import Sequence
from random import randint
from matplotlib import pyplot as plt
def _lowerCAmelCase ( lowerCamelCase__ : Sequence[float], lowerCamelCase__ : int, lowerCamelCase__ : int ) -> tuple[int | None, int | None, float]:
if not arr:
return None, None, 0
if low == high:
return low, high, arr[low]
_SCREAMING_SNAKE_CASE : Any = (low + high) // 2
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = max_subarray(lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ )
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = max_subarray(lowerCamelCase__, mid + 1, lowerCamelCase__ )
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = max_cross_sum(lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ )
if left_sum >= right_sum and left_sum >= cross_sum:
return left_low, left_high, left_sum
elif right_sum >= left_sum and right_sum >= cross_sum:
return right_low, right_high, right_sum
return cross_left, cross_right, cross_sum
def _lowerCAmelCase ( lowerCamelCase__ : Sequence[float], lowerCamelCase__ : int, lowerCamelCase__ : int, lowerCamelCase__ : int ) -> tuple[int, int, float]:
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = float("-inf" ), -1
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = float("-inf" ), -1
_SCREAMING_SNAKE_CASE : int | float = 0
for i in range(lowerCamelCase__, low - 1, -1 ):
summ += arr[i]
if summ > left_sum:
_SCREAMING_SNAKE_CASE : int = summ
_SCREAMING_SNAKE_CASE : Tuple = i
_SCREAMING_SNAKE_CASE : Union[str, Any] = 0
for i in range(mid + 1, high + 1 ):
summ += arr[i]
if summ > right_sum:
_SCREAMING_SNAKE_CASE : int = summ
_SCREAMING_SNAKE_CASE : Any = i
return max_left, max_right, (left_sum + right_sum)
def _lowerCAmelCase ( lowerCamelCase__ : int ) -> float:
_SCREAMING_SNAKE_CASE : Any = [randint(1, lowerCamelCase__ ) for _ in range(lowerCamelCase__ )]
_SCREAMING_SNAKE_CASE : int = time.time()
max_subarray(lowerCamelCase__, 0, input_size - 1 )
_SCREAMING_SNAKE_CASE : List[str] = time.time()
return end - start
def _lowerCAmelCase ( ) -> None:
_SCREAMING_SNAKE_CASE : Union[str, Any] = [1_0, 1_0_0, 1_0_0_0, 1_0_0_0_0, 5_0_0_0_0, 1_0_0_0_0_0, 2_0_0_0_0_0, 3_0_0_0_0_0, 4_0_0_0_0_0, 5_0_0_0_0_0]
_SCREAMING_SNAKE_CASE : int = [time_max_subarray(lowerCamelCase__ ) for input_size in input_sizes]
print("No of Inputs\t\tTime Taken" )
for input_size, runtime in zip(lowerCamelCase__, lowerCamelCase__ ):
print(lowerCamelCase__, "\t\t", lowerCamelCase__ )
plt.plot(lowerCamelCase__, lowerCamelCase__ )
plt.xlabel("Number of Inputs" )
plt.ylabel("Time taken in seconds" )
plt.show()
if __name__ == "__main__":
from doctest import testmod
testmod()
| 295 | 1 |
import os
import unittest
from huggingface_hub.utils import are_progress_bars_disabled
import transformers.models.bart.tokenization_bart
from transformers import logging
from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context
from transformers.utils.logging import disable_progress_bar, enable_progress_bar
class lowerCamelCase ( unittest.TestCase ):
def A( self):
__UpperCAmelCase : List[str] = logging.get_logger()
# the current default level is logging.WARNING
__UpperCAmelCase : List[Any] = logging.get_verbosity()
logging.set_verbosity_error()
self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity())
logging.set_verbosity_warning()
self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity())
logging.set_verbosity_info()
self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity())
logging.set_verbosity_debug()
self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity())
# restore to the original level
logging.set_verbosity(lowercase__)
def A( self):
__UpperCAmelCase : Optional[int] = logging.get_verbosity()
__UpperCAmelCase : Dict = logging.get_logger('''transformers.models.bart.tokenization_bart''')
__UpperCAmelCase : Optional[Any] = '''Testing 1, 2, 3'''
# should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`)
if level_origin <= logging.WARNING:
with CaptureLogger(lowercase__) as cl:
logger.warning(lowercase__)
self.assertEqual(cl.out , msg + '''\n''')
# this is setting the level for all of `transformers.*` loggers
logging.set_verbosity_error()
# should not be able to log warnings
with CaptureLogger(lowercase__) as cl:
logger.warning(lowercase__)
self.assertEqual(cl.out , '''''')
# should be able to log warnings again
logging.set_verbosity_warning()
with CaptureLogger(lowercase__) as cl:
logger.warning(lowercase__)
self.assertEqual(cl.out , msg + '''\n''')
# restore to the original level
logging.set_verbosity(lowercase__)
@mockenv(TRANSFORMERS_VERBOSITY='''error''')
def A( self):
# reset for the env var to take effect, next time some logger call is made
transformers.utils.logging._reset_library_root_logger()
# this action activates the env var
__UpperCAmelCase : List[str] = logging.get_logger('''transformers.models.bart.tokenization_bart''')
__UpperCAmelCase : List[str] = os.getenv('''TRANSFORMERS_VERBOSITY''' , lowercase__)
__UpperCAmelCase : Dict = logging.log_levels[env_level_str]
__UpperCAmelCase : Optional[Any] = logging.get_verbosity()
self.assertEqual(
lowercase__ , lowercase__ , F"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}" , )
# restore to the original level
__UpperCAmelCase : Any = ''''''
transformers.utils.logging._reset_library_root_logger()
@mockenv(TRANSFORMERS_VERBOSITY='''super-error''')
def A( self):
# reset for the env var to take effect, next time some logger call is made
transformers.utils.logging._reset_library_root_logger()
__UpperCAmelCase : Tuple = logging.logging.getLogger()
with CaptureLogger(lowercase__) as cl:
# this action activates the env var
logging.get_logger('''transformers.models.bart.tokenization_bart''')
self.assertIn('''Unknown option TRANSFORMERS_VERBOSITY=super-error''' , cl.out)
# no need to restore as nothing was changed
def A( self):
# testing `logger.warning_advice()`
transformers.utils.logging._reset_library_root_logger()
__UpperCAmelCase : Optional[Any] = logging.get_logger('''transformers.models.bart.tokenization_bart''')
__UpperCAmelCase : Optional[Any] = '''Testing 1, 2, 3'''
with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS='''1'''):
# nothing should be logged as env var disables this method
with CaptureLogger(lowercase__) as cl:
logger.warning_advice(lowercase__)
self.assertEqual(cl.out , '''''')
with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS=''''''):
# should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset
with CaptureLogger(lowercase__) as cl:
logger.warning_advice(lowercase__)
self.assertEqual(cl.out , msg + '''\n''')
def __SCREAMING_SNAKE_CASE ( ) -> Dict:
'''simple docstring'''
disable_progress_bar()
assert are_progress_bars_disabled()
enable_progress_bar()
assert not are_progress_bars_disabled()
| 462 |
import itertools
import os
import random
import tempfile
import unittest
import numpy as np
from transformers import TvltFeatureExtractor, is_datasets_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available
from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin
if is_torch_available():
import torch
if is_datasets_available():
from datasets import load_dataset
lowerCAmelCase = random.Random()
def __SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=1.0 , lowercase_=None , lowercase_=None ) -> Union[str, Any]:
'''simple docstring'''
if rng is None:
__UpperCAmelCase : str = global_rng
__UpperCAmelCase : List[Any] = []
for batch_idx in range(shape[0] ):
values.append([] )
for _ in range(shape[1] ):
values[-1].append(rng.random() * scale )
return values
class lowerCamelCase ( unittest.TestCase ):
def __init__( self , lowercase__ , lowercase__=7 , lowercase__=4_0_0 , lowercase__=2_0_0_0 , lowercase__=2_0_4_8 , lowercase__=1_2_8 , lowercase__=1 , lowercase__=5_1_2 , lowercase__=3_0 , lowercase__=4_4_1_0_0 , ):
__UpperCAmelCase : Optional[Any] = parent
__UpperCAmelCase : Any = batch_size
__UpperCAmelCase : int = min_seq_length
__UpperCAmelCase : List[str] = max_seq_length
__UpperCAmelCase : Dict = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
__UpperCAmelCase : Any = spectrogram_length
__UpperCAmelCase : List[Any] = feature_size
__UpperCAmelCase : Union[str, Any] = num_audio_channels
__UpperCAmelCase : Optional[int] = hop_length
__UpperCAmelCase : Tuple = chunk_length
__UpperCAmelCase : Any = sampling_rate
def A( self):
return {
"spectrogram_length": self.spectrogram_length,
"feature_size": self.feature_size,
"num_audio_channels": self.num_audio_channels,
"hop_length": self.hop_length,
"chunk_length": self.chunk_length,
"sampling_rate": self.sampling_rate,
}
def A( self , lowercase__=False , lowercase__=False):
def _flatten(lowercase__):
return list(itertools.chain(*lowercase__))
if equal_length:
__UpperCAmelCase : str = [floats_list((self.max_seq_length, self.feature_size)) for _ in range(self.batch_size)]
else:
# make sure that inputs increase in size
__UpperCAmelCase : List[str] = [
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 : List[str] = [np.asarray(lowercase__) for x in speech_inputs]
return speech_inputs
@require_torch
@require_torchaudio
class lowerCamelCase ( _UpperCamelCase , unittest.TestCase ):
_lowerCAmelCase : Optional[int] = TvltFeatureExtractor
def A( self):
__UpperCAmelCase : Dict = TvltFeatureExtractionTester(self)
def A( self):
__UpperCAmelCase : Optional[int] = self.feature_extraction_class(**self.feat_extract_dict)
self.assertTrue(hasattr(lowercase__ , '''spectrogram_length'''))
self.assertTrue(hasattr(lowercase__ , '''feature_size'''))
self.assertTrue(hasattr(lowercase__ , '''num_audio_channels'''))
self.assertTrue(hasattr(lowercase__ , '''hop_length'''))
self.assertTrue(hasattr(lowercase__ , '''chunk_length'''))
self.assertTrue(hasattr(lowercase__ , '''sampling_rate'''))
def A( self):
__UpperCAmelCase : str = self.feature_extraction_class(**self.feat_extract_dict)
with tempfile.TemporaryDirectory() as tmpdirname:
__UpperCAmelCase : str = feat_extract_first.save_pretrained(lowercase__)[0]
check_json_file_has_correct_format(lowercase__)
__UpperCAmelCase : Optional[int] = self.feature_extraction_class.from_pretrained(lowercase__)
__UpperCAmelCase : List[Any] = feat_extract_first.to_dict()
__UpperCAmelCase : Union[str, Any] = feat_extract_second.to_dict()
__UpperCAmelCase : Union[str, Any] = dict_first.pop('''mel_filters''')
__UpperCAmelCase : Union[str, Any] = dict_second.pop('''mel_filters''')
self.assertTrue(np.allclose(lowercase__ , lowercase__))
self.assertEqual(lowercase__ , lowercase__)
def A( self):
__UpperCAmelCase : Optional[int] = self.feature_extraction_class(**self.feat_extract_dict)
with tempfile.TemporaryDirectory() as tmpdirname:
__UpperCAmelCase : Union[str, Any] = os.path.join(lowercase__ , '''feat_extract.json''')
feat_extract_first.to_json_file(lowercase__)
__UpperCAmelCase : str = self.feature_extraction_class.from_json_file(lowercase__)
__UpperCAmelCase : Any = feat_extract_first.to_dict()
__UpperCAmelCase : Union[str, Any] = feat_extract_second.to_dict()
__UpperCAmelCase : Tuple = dict_first.pop('''mel_filters''')
__UpperCAmelCase : List[str] = dict_second.pop('''mel_filters''')
self.assertTrue(np.allclose(lowercase__ , lowercase__))
self.assertEqual(lowercase__ , lowercase__)
def A( self):
# Initialize feature_extractor
__UpperCAmelCase : Optional[int] = self.feature_extraction_class(**self.feat_extract_dict)
# create three inputs of length 800, 1000, and 1200
__UpperCAmelCase : Optional[int] = [floats_list((1, x))[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0)]
__UpperCAmelCase : int = [np.asarray(lowercase__) for speech_input in speech_inputs]
# Test not batched input
__UpperCAmelCase : Dict = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' , sampling_rate=4_4_1_0_0).audio_values
self.assertTrue(encoded_audios.ndim == 4)
self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size)
self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length)
self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels)
# Test batched
__UpperCAmelCase : List[str] = feature_extractor(lowercase__ , return_tensors='''np''' , sampling_rate=4_4_1_0_0).audio_values
self.assertTrue(encoded_audios.ndim == 4)
self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size)
self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length)
self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels)
# Test audio masking
__UpperCAmelCase : Tuple = feature_extractor(
lowercase__ , return_tensors='''np''' , sampling_rate=4_4_1_0_0 , mask_audio=lowercase__).audio_values
self.assertTrue(encoded_audios.ndim == 4)
self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size)
self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length)
self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels)
# Test 2-D numpy arrays are batched.
__UpperCAmelCase : Any = [floats_list((1, x))[0] for x in (8_0_0, 8_0_0, 8_0_0)]
__UpperCAmelCase : Optional[Any] = np.asarray(lowercase__)
__UpperCAmelCase : Tuple = feature_extractor(lowercase__ , return_tensors='''np''' , sampling_rate=4_4_1_0_0).audio_values
self.assertTrue(encoded_audios.ndim == 4)
self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size)
self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length)
self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels)
def A( self , lowercase__):
__UpperCAmelCase : Optional[int] = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''')
# automatic decoding with librispeech
__UpperCAmelCase : int = ds.sort('''id''').select(range(lowercase__))[:num_samples]['''audio''']
return [x["array"] for x in speech_samples]
def A( self):
__UpperCAmelCase : Optional[Any] = self._load_datasamples(1)
__UpperCAmelCase : Tuple = TvltFeatureExtractor()
__UpperCAmelCase : Tuple = feature_extractor(lowercase__ , return_tensors='''pt''').audio_values
self.assertEquals(audio_values.shape , (1, 1, 1_9_2, 1_2_8))
__UpperCAmelCase : int = torch.tensor([[-0.3_0_3_2, -0.2_7_0_8], [-0.4_4_3_4, -0.4_0_0_7]])
self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] , lowercase__ , atol=1e-4))
| 462 | 1 |
import os
import unittest
from transformers import LxmertTokenizer, LxmertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class __UpperCAmelCase ( snake_case__ , unittest.TestCase ):
"""simple docstring"""
lowercase = LxmertTokenizer
lowercase = LxmertTokenizerFast
lowercase = True
lowercase = True
def __lowerCAmelCase ( self ) -> Union[str, Any]:
"""simple docstring"""
super().setUp()
UpperCamelCase = [
"[UNK]",
"[CLS]",
"[SEP]",
"want",
"##want",
"##ed",
"wa",
"un",
"runn",
"##ing",
",",
"low",
"lowest",
]
UpperCamelCase = 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 __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Union[str, Any]:
"""simple docstring"""
UpperCamelCase = "UNwant\u00E9d,running"
UpperCamelCase = "unwanted, running"
return input_text, output_text
def __lowerCAmelCase ( self ) -> Tuple:
"""simple docstring"""
UpperCamelCase = self.tokenizer_class(self.vocab_file )
UpperCamelCase = tokenizer.tokenize("UNwant\u00E9d,running" )
self.assertListEqual(SCREAMING_SNAKE_CASE , ["un", "##want", "##ed", ",", "runn", "##ing"] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) , [7, 4, 5, 10, 8, 9] )
def __lowerCAmelCase ( self ) -> Optional[Any]:
"""simple docstring"""
if not self.test_rust_tokenizer:
return
UpperCamelCase = self.get_tokenizer()
UpperCamelCase = self.get_rust_tokenizer()
UpperCamelCase = "I was born in 92000, and this is falsé."
UpperCamelCase = tokenizer.tokenize(SCREAMING_SNAKE_CASE )
UpperCamelCase = rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE )
self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
UpperCamelCase = tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE )
UpperCamelCase = rust_tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE )
self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
UpperCamelCase = self.get_rust_tokenizer()
UpperCamelCase = tokenizer.encode(SCREAMING_SNAKE_CASE )
UpperCamelCase = rust_tokenizer.encode(SCREAMING_SNAKE_CASE )
self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
| 714 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
__a : List[Any] = {
"""configuration_altclip""": [
"""ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""",
"""AltCLIPConfig""",
"""AltCLIPTextConfig""",
"""AltCLIPVisionConfig""",
],
"""processing_altclip""": ["""AltCLIPProcessor"""],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__a : Optional[Any] = [
"""ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""AltCLIPPreTrainedModel""",
"""AltCLIPModel""",
"""AltCLIPTextModel""",
"""AltCLIPVisionModel""",
]
if TYPE_CHECKING:
from .configuration_altclip import (
ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
AltCLIPConfig,
AltCLIPTextConfig,
AltCLIPVisionConfig,
)
from .processing_altclip import AltCLIPProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_altclip import (
ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
AltCLIPModel,
AltCLIPPreTrainedModel,
AltCLIPTextModel,
AltCLIPVisionModel,
)
else:
import sys
__a : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 414 | 0 |
'''simple docstring'''
import math
from typing import Optional
import numpy as np
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowerCamelCase_ = logging.get_logger(__name__)
lowerCamelCase_ = {
'''facebook/encodec_24khz''': '''https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json''',
'''facebook/encodec_48khz''': '''https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json''',
}
class _UpperCAmelCase ( snake_case_ ):
"""simple docstring"""
snake_case = '''encodec'''
def __init__( self : List[str] , __UpperCAmelCase : Dict=[1.5, 3.0, 6.0, 12.0, 24.0] , __UpperCAmelCase : List[Any]=24000 , __UpperCAmelCase : List[Any]=1 , __UpperCAmelCase : int=False , __UpperCAmelCase : Dict=None , __UpperCAmelCase : List[Any]=None , __UpperCAmelCase : Dict=128 , __UpperCAmelCase : int=32 , __UpperCAmelCase : List[str]=1 , __UpperCAmelCase : int=[8, 5, 4, 2] , __UpperCAmelCase : List[str]="weight_norm" , __UpperCAmelCase : Union[str, Any]=7 , __UpperCAmelCase : str=7 , __UpperCAmelCase : List[Any]=3 , __UpperCAmelCase : int=2 , __UpperCAmelCase : Union[str, Any]=True , __UpperCAmelCase : Any="reflect" , __UpperCAmelCase : Dict=2 , __UpperCAmelCase : List[str]=2 , __UpperCAmelCase : Optional[int]=1.0 , __UpperCAmelCase : Union[str, Any]=1024 , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Tuple=True , **__UpperCAmelCase : List[str] , ):
'''simple docstring'''
_A = target_bandwidths
_A = sampling_rate
_A = audio_channels
_A = normalize
_A = chunk_length_s
_A = overlap
_A = hidden_size
_A = num_filters
_A = num_residual_layers
_A = upsampling_ratios
_A = norm_type
_A = kernel_size
_A = last_kernel_size
_A = residual_kernel_size
_A = dilation_growth_rate
_A = use_causal_conv
_A = pad_mode
_A = compress
_A = num_lstm_layers
_A = trim_right_ratio
_A = codebook_size
_A = codebook_dim if codebook_dim is not None else hidden_size
_A = use_conv_shortcut
if self.norm_type not in ["weight_norm", "time_group_norm"]:
raise ValueError(
f'''self.norm_type must be one of `"weight_norm"`, `"time_group_norm"`), got {self.norm_type}''' )
super().__init__(**__UpperCAmelCase )
@property
def lowerCAmelCase ( self : str ):
'''simple docstring'''
if self.chunk_length_s is None:
return None
else:
return int(self.chunk_length_s * self.sampling_rate )
@property
def lowerCAmelCase ( self : List[Any] ):
'''simple docstring'''
if self.chunk_length_s is None or self.overlap is None:
return None
else:
return max(1 , int((1.0 - self.overlap) * self.chunk_length ) )
@property
def lowerCAmelCase ( self : List[str] ):
'''simple docstring'''
_A = np.prod(self.upsampling_ratios )
return math.ceil(self.sampling_rate / hop_length )
@property
def lowerCAmelCase ( self : Dict ):
'''simple docstring'''
return int(1000 * self.target_bandwidths[-1] // (self.frame_rate * 10) )
| 330 |
'''simple docstring'''
from collections import OrderedDict
from typing import Any, Mapping, Optional
from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging
lowerCamelCase_ = logging.get_logger(__name__)
lowerCamelCase_ = {
'''Helsinki-NLP/opus-mt-en-de''': '''https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/config.json''',
# See all Marian models at https://huggingface.co/models?filter=marian
}
class _UpperCAmelCase ( snake_case_ ):
"""simple docstring"""
snake_case = '''marian'''
snake_case = ['''past_key_values''']
snake_case = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''}
def __init__( self : List[Any] , __UpperCAmelCase : Union[str, Any]=58101 , __UpperCAmelCase : List[str]=None , __UpperCAmelCase : Optional[int]=1024 , __UpperCAmelCase : Union[str, Any]=12 , __UpperCAmelCase : Tuple=4096 , __UpperCAmelCase : Any=16 , __UpperCAmelCase : Optional[int]=12 , __UpperCAmelCase : Optional[Any]=4096 , __UpperCAmelCase : str=16 , __UpperCAmelCase : Tuple=0.0 , __UpperCAmelCase : Optional[Any]=0.0 , __UpperCAmelCase : int=True , __UpperCAmelCase : Tuple=True , __UpperCAmelCase : Dict="gelu" , __UpperCAmelCase : Union[str, Any]=1024 , __UpperCAmelCase : int=0.1 , __UpperCAmelCase : Dict=0.0 , __UpperCAmelCase : List[Any]=0.0 , __UpperCAmelCase : Union[str, Any]=0.02 , __UpperCAmelCase : Union[str, Any]=58100 , __UpperCAmelCase : int=False , __UpperCAmelCase : List[str]=58100 , __UpperCAmelCase : List[Any]=0 , __UpperCAmelCase : Union[str, Any]=0 , __UpperCAmelCase : Optional[int]=True , **__UpperCAmelCase : Union[str, Any] , ):
'''simple docstring'''
_A = vocab_size
_A = decoder_vocab_size or vocab_size
_A = max_position_embeddings
_A = d_model
_A = encoder_ffn_dim
_A = encoder_layers
_A = encoder_attention_heads
_A = decoder_ffn_dim
_A = decoder_layers
_A = decoder_attention_heads
_A = dropout
_A = attention_dropout
_A = activation_dropout
_A = activation_function
_A = init_std
_A = encoder_layerdrop
_A = decoder_layerdrop
_A = use_cache
_A = encoder_layers
_A = scale_embedding # scale factor will be sqrt(d_model) if True
_A = share_encoder_decoder_embeddings
super().__init__(
pad_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , is_encoder_decoder=__UpperCAmelCase , decoder_start_token_id=__UpperCAmelCase , forced_eos_token_id=__UpperCAmelCase , **__UpperCAmelCase , )
class _UpperCAmelCase ( snake_case_ ):
"""simple docstring"""
@property
# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.inputs
def lowerCAmelCase ( self : List[str] ):
'''simple docstring'''
if self.task in ["default", "seq2seq-lm"]:
_A = OrderedDict(
[
("input_ids", {0: "batch", 1: "encoder_sequence"}),
("attention_mask", {0: "batch", 1: "encoder_sequence"}),
] )
if self.use_past:
_A = {0: "batch"}
_A = {0: "batch", 1: "past_decoder_sequence + sequence"}
else:
_A = {0: "batch", 1: "decoder_sequence"}
_A = {0: "batch", 1: "decoder_sequence"}
if self.use_past:
self.fill_with_past_key_values_(__UpperCAmelCase , direction="inputs" )
elif self.task == "causal-lm":
# TODO: figure this case out.
_A = OrderedDict(
[
("input_ids", {0: "batch", 1: "encoder_sequence"}),
("attention_mask", {0: "batch", 1: "encoder_sequence"}),
] )
if self.use_past:
_A , _A = self.num_layers
for i in range(__UpperCAmelCase ):
_A = {0: "batch", 2: "past_sequence + sequence"}
_A = {0: "batch", 2: "past_sequence + sequence"}
else:
_A = OrderedDict(
[
("input_ids", {0: "batch", 1: "encoder_sequence"}),
("attention_mask", {0: "batch", 1: "encoder_sequence"}),
("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}),
("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}),
] )
return common_inputs
@property
# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
def lowerCAmelCase ( self : Union[str, Any] ):
'''simple docstring'''
if self.task in ["default", "seq2seq-lm"]:
_A = super().outputs
else:
_A = super(__UpperCAmelCase , self ).outputs
if self.use_past:
_A , _A = self.num_layers
for i in range(__UpperCAmelCase ):
_A = {0: "batch", 2: "past_sequence + sequence"}
_A = {0: "batch", 2: "past_sequence + sequence"}
return common_outputs
def lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : PreTrainedTokenizer , __UpperCAmelCase : int = -1 , __UpperCAmelCase : int = -1 , __UpperCAmelCase : bool = False , __UpperCAmelCase : Optional[TensorType] = None , ):
'''simple docstring'''
_A = self._generate_dummy_inputs_for_encoder_and_decoder(
__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
# Generate decoder inputs
_A = seq_length if not self.use_past else 1
_A = self._generate_dummy_inputs_for_encoder_and_decoder(
__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
_A = {f'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()}
_A = dict(**__UpperCAmelCase , **__UpperCAmelCase )
if self.use_past:
if not is_torch_available():
raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." )
else:
import torch
_A , _A = common_inputs["input_ids"].shape
_A = common_inputs["decoder_input_ids"].shape[1]
_A , _A = self.num_attention_heads
_A = (
batch,
num_encoder_attention_heads,
encoder_seq_length,
self._config.hidden_size // num_encoder_attention_heads,
)
_A = decoder_seq_length + 3
_A = (
batch,
num_decoder_attention_heads,
decoder_past_length,
self._config.hidden_size // num_decoder_attention_heads,
)
_A = torch.cat(
[common_inputs["decoder_attention_mask"], torch.ones(__UpperCAmelCase , __UpperCAmelCase )] , dim=1 )
_A = []
# If the number of encoder and decoder layers are present in the model configuration, both are considered
_A , _A = self.num_layers
_A = min(__UpperCAmelCase , __UpperCAmelCase )
_A = max(__UpperCAmelCase , __UpperCAmelCase ) - min_num_layers
_A = "encoder" if num_encoder_layers > num_decoder_layers else "decoder"
for _ in range(__UpperCAmelCase ):
common_inputs["past_key_values"].append(
(
torch.zeros(__UpperCAmelCase ),
torch.zeros(__UpperCAmelCase ),
torch.zeros(__UpperCAmelCase ),
torch.zeros(__UpperCAmelCase ),
) )
# TODO: test this.
_A = encoder_shape if remaining_side_name == "encoder" else decoder_shape
for _ in range(__UpperCAmelCase , __UpperCAmelCase ):
common_inputs["past_key_values"].append((torch.zeros(__UpperCAmelCase ), torch.zeros(__UpperCAmelCase )) )
return common_inputs
def lowerCAmelCase ( self : Dict , __UpperCAmelCase : PreTrainedTokenizer , __UpperCAmelCase : int = -1 , __UpperCAmelCase : int = -1 , __UpperCAmelCase : bool = False , __UpperCAmelCase : Optional[TensorType] = None , ):
'''simple docstring'''
_A = self._generate_dummy_inputs_for_encoder_and_decoder(
__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
if self.use_past:
if not is_torch_available():
raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." )
else:
import torch
_A , _A = common_inputs["input_ids"].shape
# Not using the same length for past_key_values
_A = seqlen + 2
_A , _A = self.num_layers
_A , _A = self.num_attention_heads
_A = (
batch,
num_encoder_attention_heads,
past_key_values_length,
self._config.hidden_size // num_encoder_attention_heads,
)
_A = common_inputs["attention_mask"].dtype
_A = torch.cat(
[common_inputs["attention_mask"], torch.ones(__UpperCAmelCase , __UpperCAmelCase , dtype=__UpperCAmelCase )] , dim=1 )
_A = [
(torch.zeros(__UpperCAmelCase ), torch.zeros(__UpperCAmelCase )) for _ in range(__UpperCAmelCase )
]
return common_inputs
def lowerCAmelCase ( self : str , __UpperCAmelCase : PreTrainedTokenizer , __UpperCAmelCase : int = -1 , __UpperCAmelCase : int = -1 , __UpperCAmelCase : bool = False , __UpperCAmelCase : Optional[TensorType] = None , ):
'''simple docstring'''
_A = compute_effective_axis_dimension(
__UpperCAmelCase , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 )
# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
_A = tokenizer.num_special_tokens_to_add(__UpperCAmelCase )
_A = compute_effective_axis_dimension(
__UpperCAmelCase , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__UpperCAmelCase )
# Generate dummy inputs according to compute batch and sequence
_A = [" ".join([tokenizer.unk_token] ) * seq_length] * batch_size
_A = dict(tokenizer(__UpperCAmelCase , return_tensors=__UpperCAmelCase ) )
return common_inputs
def lowerCAmelCase ( self : Dict , __UpperCAmelCase : PreTrainedTokenizer , __UpperCAmelCase : int = -1 , __UpperCAmelCase : int = -1 , __UpperCAmelCase : bool = False , __UpperCAmelCase : Optional[TensorType] = None , ):
'''simple docstring'''
if self.task in ["default", "seq2seq-lm"]:
_A = self._generate_dummy_inputs_for_default_and_seqaseq_lm(
__UpperCAmelCase , batch_size=__UpperCAmelCase , seq_length=__UpperCAmelCase , is_pair=__UpperCAmelCase , framework=__UpperCAmelCase )
else:
_A = self._generate_dummy_inputs_for_causal_lm(
__UpperCAmelCase , batch_size=__UpperCAmelCase , seq_length=__UpperCAmelCase , is_pair=__UpperCAmelCase , framework=__UpperCAmelCase )
return common_inputs
def lowerCAmelCase ( self : str , __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : str ):
'''simple docstring'''
if self.task in ["default", "seq2seq-lm"]:
_A = super()._flatten_past_key_values_(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
else:
_A = super(__UpperCAmelCase , self )._flatten_past_key_values_(
__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
@property
def lowerCAmelCase ( self : int ):
'''simple docstring'''
return 1E-4
| 330 | 1 |
import warnings
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_snake_case : Optional[Any] = logging.get_logger(__name__)
_snake_case : str = {
"xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/config.json",
"xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/config.json",
}
class a (_lowerCAmelCase ):
"""simple docstring"""
__UpperCAmelCase : List[Any] = "xlnet"
__UpperCAmelCase : Dict = ["mems"]
__UpperCAmelCase : Tuple = {
"n_token": "vocab_size", # Backward compatibility
"hidden_size": "d_model",
"num_attention_heads": "n_head",
"num_hidden_layers": "n_layer",
}
def __init__( self : List[Any] , lowerCamelCase : Optional[int]=32000 , lowerCamelCase : str=1024 , lowerCamelCase : int=24 , lowerCamelCase : List[Any]=16 , lowerCamelCase : Any=4096 , lowerCamelCase : Optional[Any]="gelu" , lowerCamelCase : Optional[Any]=True , lowerCamelCase : Optional[int]="bi" , lowerCamelCase : Union[str, Any]=0.02 , lowerCamelCase : Union[str, Any]=1E-12 , lowerCamelCase : Dict=0.1 , lowerCamelCase : int=512 , lowerCamelCase : str=None , lowerCamelCase : Dict=True , lowerCamelCase : str=False , lowerCamelCase : Any=False , lowerCamelCase : Optional[Any]=-1 , lowerCamelCase : List[Any]=False , lowerCamelCase : Optional[int]="last" , lowerCamelCase : Dict=True , lowerCamelCase : Union[str, Any]="tanh" , lowerCamelCase : int=0.1 , lowerCamelCase : Any=5 , lowerCamelCase : List[str]=5 , lowerCamelCase : List[Any]=5 , lowerCamelCase : Tuple=1 , lowerCamelCase : Dict=2 , **lowerCamelCase : List[str] , ) -> List[Any]:
__snake_case : Optional[Any] = vocab_size
__snake_case : Any = d_model
__snake_case : int = n_layer
__snake_case : Optional[int] = n_head
if d_model % n_head != 0:
raise ValueError(F'\'d_model % n_head\' ({d_model % n_head}) should be equal to 0' )
if "d_head" in kwargs:
if kwargs["d_head"] != d_model // n_head:
raise ValueError(
F'`d_head` ({kwargs["d_head"]}) should be equal to `d_model // n_head` ({d_model // n_head})' )
__snake_case : Any = d_model // n_head
__snake_case : Tuple = ff_activation
__snake_case : int = d_inner
__snake_case : Optional[Any] = untie_r
__snake_case : Optional[Any] = attn_type
__snake_case : List[str] = initializer_range
__snake_case : Tuple = layer_norm_eps
__snake_case : str = dropout
__snake_case : Any = mem_len
__snake_case : Tuple = reuse_len
__snake_case : Union[str, Any] = bi_data
__snake_case : List[Any] = clamp_len
__snake_case : Optional[int] = same_length
__snake_case : List[str] = summary_type
__snake_case : Any = summary_use_proj
__snake_case : Any = summary_activation
__snake_case : Optional[int] = summary_last_dropout
__snake_case : Dict = start_n_top
__snake_case : Optional[Any] = end_n_top
__snake_case : List[str] = bos_token_id
__snake_case : Any = pad_token_id
__snake_case : Optional[Any] = eos_token_id
if "use_cache" in kwargs:
warnings.warn(
"The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`"
" instead." , lowerCamelCase , )
__snake_case : Any = kwargs["use_cache"]
__snake_case : int = use_mems_eval
__snake_case : Optional[int] = use_mems_train
super().__init__(pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , **lowerCamelCase )
@property
def __snake_case ( self : Any ) -> Optional[int]:
logger.info(F'The model {self.model_type} is one of the few models that has no sequence length limit.' )
return -1
@max_position_embeddings.setter
def __snake_case ( self : Union[str, Any] , lowerCamelCase : Any ) -> Optional[Any]:
# Message copied from Transformer-XL documentation
raise NotImplementedError(
F'The model {self.model_type} is one of the few models that has no sequence length limit.' )
| 203 |
from __future__ import annotations
_snake_case : Union[str, Any] = {
"A": ["B", "C", "E"],
"B": ["A", "D", "E"],
"C": ["A", "F", "G"],
"D": ["B"],
"E": ["A", "B", "D"],
"F": ["C"],
"G": ["C"],
}
class a :
"""simple docstring"""
def __init__( self : Tuple , lowerCamelCase : dict[str, list[str]] , lowerCamelCase : str ) -> None:
__snake_case : Tuple = graph
# mapping node to its parent in resulting breadth first tree
__snake_case : dict[str, str | None] = {}
__snake_case : Dict = source_vertex
def __snake_case ( self : Optional[int] ) -> None:
__snake_case : Dict = {self.source_vertex}
__snake_case : List[str] = None
__snake_case : Optional[Any] = [self.source_vertex] # first in first out queue
while queue:
__snake_case : List[Any] = queue.pop(0 )
for adjacent_vertex in self.graph[vertex]:
if adjacent_vertex not in visited:
visited.add(lowerCamelCase )
__snake_case : Any = vertex
queue.append(lowerCamelCase )
def __snake_case ( self : Optional[Any] , lowerCamelCase : str ) -> str:
if target_vertex == self.source_vertex:
return self.source_vertex
__snake_case : Optional[Any] = self.parent.get(lowerCamelCase )
if target_vertex_parent is None:
__snake_case : Optional[Any] = (
F'No path from vertex: {self.source_vertex} to vertex: {target_vertex}'
)
raise ValueError(lowerCamelCase )
return self.shortest_path(lowerCamelCase ) + F'->{target_vertex}'
if __name__ == "__main__":
_snake_case : Optional[Any] = Graph(graph, "G")
g.breath_first_search()
print(g.shortest_path("D"))
print(g.shortest_path("G"))
print(g.shortest_path("Foo"))
| 203 | 1 |
'''simple docstring'''
def _lowerCAmelCase ( __snake_case : int = 50 ) -> int:
__A : Optional[Any] = [1] * (length + 1)
for row_length in range(length + 1 ):
for tile_length in range(2 , 5 ):
for tile_start in range(row_length - tile_length + 1 ):
ways_number[row_length] += ways_number[
row_length - tile_start - tile_length
]
return ways_number[length]
if __name__ == "__main__":
print(f"""{solution() = }""") | 8 |
import inspect
import unittest
from transformers import DPTConfig
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel
from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import DPTImageProcessor
class _snake_case :
def __init__( self : Any, __lowercase : Any, __lowercase : int=2, __lowercase : Tuple=32, __lowercase : List[Any]=16, __lowercase : Any=3, __lowercase : Dict=True, __lowercase : str=True, __lowercase : Any=32, __lowercase : Union[str, Any]=4, __lowercase : Optional[int]=[0, 1, 2, 3], __lowercase : Dict=4, __lowercase : Union[str, Any]=37, __lowercase : Any="gelu", __lowercase : List[Any]=0.1, __lowercase : int=0.1, __lowercase : str=0.02, __lowercase : List[str]=3, __lowercase : int=[1, 384, 24, 24], __lowercase : List[Any]=True, __lowercase : Any=None, ):
lowercase__ = parent
lowercase__ = batch_size
lowercase__ = image_size
lowercase__ = patch_size
lowercase__ = num_channels
lowercase__ = is_training
lowercase__ = use_labels
lowercase__ = hidden_size
lowercase__ = num_hidden_layers
lowercase__ = backbone_out_indices
lowercase__ = num_attention_heads
lowercase__ = intermediate_size
lowercase__ = hidden_act
lowercase__ = hidden_dropout_prob
lowercase__ = attention_probs_dropout_prob
lowercase__ = initializer_range
lowercase__ = num_labels
lowercase__ = backbone_featmap_shape
lowercase__ = scope
lowercase__ = is_hybrid
# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
lowercase__ = (image_size // patch_size) ** 2
lowercase__ = num_patches + 1
def A__ ( self : Optional[Any] ):
lowercase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
lowercase__ = None
if self.use_labels:
lowercase__ = ids_tensor([self.batch_size, self.image_size, self.image_size], self.num_labels )
lowercase__ = self.get_config()
return config, pixel_values, labels
def A__ ( self : List[Any] ):
lowercase__ = {
"global_padding": "same",
"layer_type": "bottleneck",
"depths": [3, 4, 9],
"out_features": ["stage1", "stage2", "stage3"],
"embedding_dynamic_padding": True,
"hidden_sizes": [96, 192, 384, 768],
"num_groups": 2,
}
return DPTConfig(
image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, backbone_out_indices=self.backbone_out_indices, 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, is_decoder=__lowercase, initializer_range=self.initializer_range, is_hybrid=self.is_hybrid, backbone_config=__lowercase, backbone_featmap_shape=self.backbone_featmap_shape, )
def A__ ( self : Optional[int], __lowercase : Optional[Any], __lowercase : str, __lowercase : Any ):
lowercase__ = DPTModel(config=__lowercase )
model.to(__lowercase )
model.eval()
lowercase__ = model(__lowercase )
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) )
def A__ ( self : Optional[int], __lowercase : Dict, __lowercase : Optional[Any], __lowercase : int ):
lowercase__ = self.num_labels
lowercase__ = DPTForDepthEstimation(__lowercase )
model.to(__lowercase )
model.eval()
lowercase__ = model(__lowercase )
self.parent.assertEqual(result.predicted_depth.shape, (self.batch_size, self.image_size, self.image_size) )
def A__ ( self : Dict, __lowercase : Optional[int], __lowercase : List[str], __lowercase : Any ):
lowercase__ = self.num_labels
lowercase__ = DPTForSemanticSegmentation(__lowercase )
model.to(__lowercase )
model.eval()
lowercase__ = model(__lowercase, labels=__lowercase )
self.parent.assertEqual(
result.logits.shape, (self.batch_size, self.num_labels, self.image_size, self.image_size) )
def A__ ( self : Optional[int] ):
lowercase__ = self.prepare_config_and_inputs()
lowercase__ , lowercase__ , lowercase__ = config_and_inputs
lowercase__ = {"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
class _snake_case ( lowercase__ , lowercase__ , unittest.TestCase):
UpperCamelCase__ : Union[str, Any] =(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
UpperCamelCase__ : int =(
{
"""depth-estimation""": DPTForDepthEstimation,
"""feature-extraction""": DPTModel,
"""image-segmentation""": DPTForSemanticSegmentation,
}
if is_torch_available()
else {}
)
UpperCamelCase__ : Union[str, Any] =False
UpperCamelCase__ : Optional[int] =False
UpperCamelCase__ : Dict =False
def A__ ( self : Union[str, Any] ):
lowercase__ = DPTModelTester(self )
lowercase__ = ConfigTester(self, config_class=__lowercase, has_text_modality=__lowercase, hidden_size=37 )
def A__ ( self : int ):
self.config_tester.run_common_tests()
@unittest.skip(reason="DPT does not use inputs_embeds" )
def A__ ( self : Optional[int] ):
pass
def A__ ( self : str ):
lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowercase__ = model_class(__lowercase )
self.assertIsInstance(model.get_input_embeddings(), (nn.Module) )
lowercase__ = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(__lowercase, nn.Linear ) )
def A__ ( self : Dict ):
lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowercase__ = model_class(__lowercase )
lowercase__ = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
lowercase__ = [*signature.parameters.keys()]
lowercase__ = ["pixel_values"]
self.assertListEqual(arg_names[:1], __lowercase )
def A__ ( self : Any ):
lowercase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__lowercase )
def A__ ( self : Tuple ):
lowercase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_depth_estimation(*__lowercase )
def A__ ( self : Union[str, Any] ):
lowercase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_semantic_segmentation(*__lowercase )
def A__ ( self : Tuple ):
for model_class in self.all_model_classes:
if model_class.__name__ == "DPTForDepthEstimation":
continue
lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common()
lowercase__ = True
if model_class in get_values(__lowercase ):
continue
lowercase__ = model_class(__lowercase )
model.to(__lowercase )
model.train()
lowercase__ = self._prepare_for_class(__lowercase, __lowercase, return_labels=__lowercase )
lowercase__ = model(**__lowercase ).loss
loss.backward()
def A__ ( self : Optional[Any] ):
for model_class in self.all_model_classes:
if model_class.__name__ == "DPTForDepthEstimation":
continue
lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common()
lowercase__ = False
lowercase__ = True
if model_class in get_values(__lowercase ) or not model_class.supports_gradient_checkpointing:
continue
lowercase__ = model_class(__lowercase )
model.to(__lowercase )
model.gradient_checkpointing_enable()
model.train()
lowercase__ = self._prepare_for_class(__lowercase, __lowercase, return_labels=__lowercase )
lowercase__ = model(**__lowercase ).loss
loss.backward()
def A__ ( self : Tuple ):
lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common()
lowercase__ = _config_zero_init(__lowercase )
for model_class in self.all_model_classes:
lowercase__ = model_class(config=__lowercase )
# Skip the check for the backbone
lowercase__ = []
for name, module in model.named_modules():
if module.__class__.__name__ == "DPTViTHybridEmbeddings":
lowercase__ = [F'''{name}.{key}''' for key in module.state_dict().keys()]
break
for name, param in model.named_parameters():
if param.requires_grad:
if name in backbone_params:
continue
self.assertIn(
((param.data.mean() * 1e9).round() / 1e9).item(), [0.0, 1.0], msg=F'''Parameter {name} of model {model_class} seems not properly initialized''', )
@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." )
def A__ ( self : Optional[int] ):
pass
@slow
def A__ ( self : str ):
for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
lowercase__ = DPTModel.from_pretrained(__lowercase )
self.assertIsNotNone(__lowercase )
def A__ ( self : Optional[int] ):
# We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type
lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common()
lowercase__ = "add"
with self.assertRaises(__lowercase ):
lowercase__ = DPTForDepthEstimation(__lowercase )
def __lowerCAmelCase ( ):
lowercase__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_torch
@require_vision
@slow
class _snake_case ( unittest.TestCase):
def A__ ( self : str ):
lowercase__ = DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas" )
lowercase__ = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas" ).to(__lowercase )
lowercase__ = prepare_img()
lowercase__ = image_processor(images=__lowercase, return_tensors="pt" ).to(__lowercase )
# forward pass
with torch.no_grad():
lowercase__ = model(**__lowercase )
lowercase__ = outputs.predicted_depth
# verify the predicted depth
lowercase__ = torch.Size((1, 384, 384) )
self.assertEqual(predicted_depth.shape, __lowercase )
lowercase__ = torch.tensor(
[[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]] ).to(__lowercase )
self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100, __lowercase, atol=1e-4 ) )
| 413 | 0 |
'''simple docstring'''
from typing import List
import datasets
from datasets.tasks import AudioClassification
from ..folder_based_builder import folder_based_builder
__lowerCamelCase : int = datasets.utils.logging.get_logger(__name__)
class UpperCAmelCase ( folder_based_builder.FolderBasedBuilderConfig ):
UpperCAmelCase : bool = None
UpperCAmelCase : bool = None
class UpperCAmelCase ( folder_based_builder.FolderBasedBuilder ):
UpperCAmelCase : Tuple = datasets.Audio()
UpperCAmelCase : List[str] = '''audio'''
UpperCAmelCase : Optional[Any] = AudioFolderConfig
UpperCAmelCase : List[str] # definition at the bottom of the script
UpperCAmelCase : Dict = AudioClassification(audio_column='''audio''' , label_column='''label''' )
__lowerCamelCase : Any = [
".aiff",
".au",
".avr",
".caf",
".flac",
".htk",
".svx",
".mat4",
".mat5",
".mpc2k",
".ogg",
".paf",
".pvf",
".raw",
".rf64",
".sd2",
".sds",
".ircam",
".voc",
".w64",
".wav",
".nist",
".wavex",
".wve",
".xi",
".mp3",
".opus",
]
__lowerCamelCase : int = AUDIO_EXTENSIONS
| 459 |
'''simple docstring'''
import functools
def UpperCAmelCase_ ( lowerCAmelCase_ , lowerCAmelCase_ ):
"""simple docstring"""
if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) or not all(isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) for day in days ):
raise ValueError("The parameter days should be a list of integers" )
if len(lowerCAmelCase_ ) != 3 or not all(isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) for cost in costs ):
raise ValueError("The parameter costs should be a list of three integers" )
if len(lowerCAmelCase_ ) == 0:
return 0
if min(lowerCAmelCase_ ) <= 0:
raise ValueError("All days elements should be greater than 0" )
if max(lowerCAmelCase_ ) >= 366:
raise ValueError("All days elements should be less than 366" )
lowercase = set(lowerCAmelCase_ )
@functools.cache
def dynamic_programming(lowerCAmelCase_ ) -> int:
if index > 365:
return 0
if index not in days_set:
return dynamic_programming(index + 1 )
return min(
costs[0] + dynamic_programming(index + 1 ) , costs[1] + dynamic_programming(index + 7 ) , costs[2] + dynamic_programming(index + 30 ) , )
return dynamic_programming(1 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 459 | 1 |
'''simple docstring'''
import os
import platform
import sys
lowerCamelCase = '''3'''
print("""Python version:""", sys.version)
print("""OS platform:""", platform.platform())
print("""OS architecture:""", platform.machine())
try:
import torch
print("""Torch version:""", torch.__version__)
print("""Cuda available:""", torch.cuda.is_available())
print("""Cuda version:""", torch.version.cuda)
print("""CuDNN version:""", torch.backends.cudnn.version())
print("""Number of GPUs available:""", torch.cuda.device_count())
except ImportError:
print("""Torch version:""", None)
try:
import transformers
print("""transformers version:""", transformers.__version__)
except ImportError:
print("""transformers version:""", None)
| 474 |
'''simple docstring'''
import logging
import os
from dataclasses import dataclass, field
from typing import Dict, Optional
import datasets
import numpy as np
import tensorflow as tf
from transformers import (
AutoConfig,
AutoTokenizer,
EvalPrediction,
HfArgumentParser,
PreTrainedTokenizer,
TFAutoModelForSequenceClassification,
TFTrainer,
TFTrainingArguments,
)
from transformers.utils import logging as hf_logging
hf_logging.set_verbosity_info()
hf_logging.enable_default_handler()
hf_logging.enable_explicit_format()
def lowerCAmelCase_ ( _lowerCamelCase: str , _lowerCamelCase: str , _lowerCamelCase: str , _lowerCamelCase: PreTrainedTokenizer , _lowerCamelCase: int , _lowerCamelCase: Optional[int] = None , ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = {}
if train_file is not None:
__SCREAMING_SNAKE_CASE : Any = [train_file]
if eval_file is not None:
__SCREAMING_SNAKE_CASE : Any = [eval_file]
if test_file is not None:
__SCREAMING_SNAKE_CASE : Optional[Any] = [test_file]
__SCREAMING_SNAKE_CASE : Optional[Any] = datasets.load_dataset("""csv""" , data_files=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = list(ds[list(files.keys() )[0]].features.keys() )
__SCREAMING_SNAKE_CASE : Dict = features_name.pop(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = list(set(ds[list(files.keys() )[0]][label_name] ) )
__SCREAMING_SNAKE_CASE : str = {label: i for i, label in enumerate(_lowerCamelCase )}
__SCREAMING_SNAKE_CASE : Any = tokenizer.model_input_names
__SCREAMING_SNAKE_CASE : Any = {}
if len(_lowerCamelCase ) == 1:
for k in files.keys():
__SCREAMING_SNAKE_CASE : Optional[int] = ds[k].map(
lambda _lowerCamelCase : tokenizer.batch_encode_plus(
example[features_name[0]] , truncation=_lowerCamelCase , max_length=_lowerCamelCase , padding="""max_length""" ) , batched=_lowerCamelCase , )
elif len(_lowerCamelCase ) == 2:
for k in files.keys():
__SCREAMING_SNAKE_CASE : int = ds[k].map(
lambda _lowerCamelCase : tokenizer.batch_encode_plus(
(example[features_name[0]], example[features_name[1]]) , truncation=_lowerCamelCase , max_length=_lowerCamelCase , padding="""max_length""" , ) , batched=_lowerCamelCase , )
def gen_train():
for ex in transformed_ds[datasets.Split.TRAIN]:
__SCREAMING_SNAKE_CASE : int = {k: v for k, v in ex.items() if k in input_names}
__SCREAMING_SNAKE_CASE : str = labelaid[ex[label_name]]
yield (d, label)
def gen_val():
for ex in transformed_ds[datasets.Split.VALIDATION]:
__SCREAMING_SNAKE_CASE : str = {k: v for k, v in ex.items() if k in input_names}
__SCREAMING_SNAKE_CASE : int = labelaid[ex[label_name]]
yield (d, label)
def gen_test():
for ex in transformed_ds[datasets.Split.TEST]:
__SCREAMING_SNAKE_CASE : Optional[int] = {k: v for k, v in ex.items() if k in input_names}
__SCREAMING_SNAKE_CASE : str = labelaid[ex[label_name]]
yield (d, label)
__SCREAMING_SNAKE_CASE : Tuple = (
tf.data.Dataset.from_generator(
_lowerCamelCase , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , )
if datasets.Split.TRAIN in transformed_ds
else None
)
if train_ds is not None:
__SCREAMING_SNAKE_CASE : Dict = train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN] ) ) )
__SCREAMING_SNAKE_CASE : Optional[Any] = (
tf.data.Dataset.from_generator(
_lowerCamelCase , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , )
if datasets.Split.VALIDATION in transformed_ds
else None
)
if val_ds is not None:
__SCREAMING_SNAKE_CASE : Any = val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION] ) ) )
__SCREAMING_SNAKE_CASE : Union[str, Any] = (
tf.data.Dataset.from_generator(
_lowerCamelCase , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , )
if datasets.Split.TEST in transformed_ds
else None
)
if test_ds is not None:
__SCREAMING_SNAKE_CASE : Optional[int] = test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST] ) ) )
return train_ds, val_ds, test_ds, labelaid
UpperCamelCase__ : List[str] = logging.getLogger(__name__)
@dataclass
class _UpperCamelCase :
'''simple docstring'''
_A : int = field(metadata={'''help''': '''Which column contains the label'''} )
_A : str = field(default=lowerCamelCase__ , metadata={'''help''': '''The path of the training file'''} )
_A : Optional[str] = field(default=lowerCamelCase__ , metadata={'''help''': '''The path of the development file'''} )
_A : Optional[str] = field(default=lowerCamelCase__ , metadata={'''help''': '''The path of the test file'''} )
_A : int = field(
default=128 , metadata={
'''help''': (
'''The maximum total input sequence length after tokenization. Sequences longer '''
'''than this will be truncated, sequences shorter will be padded.'''
)
} , )
_A : bool = field(
default=lowerCamelCase__ , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} )
@dataclass
class _UpperCamelCase :
'''simple docstring'''
_A : str = field(
metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} )
_A : Optional[str] = field(
default=lowerCamelCase__ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} )
_A : Optional[str] = field(
default=lowerCamelCase__ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} )
_A : bool = field(default=lowerCamelCase__ , metadata={'''help''': '''Set this flag to use fast tokenization.'''} )
# If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
# or just modify its tokenizer_config.json.
_A : Optional[str] = field(
default=lowerCamelCase__ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , )
def lowerCAmelCase_ ( ):
# 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.
__SCREAMING_SNAKE_CASE : List[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments) )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = parser.parse_args_into_dataclasses()
if (
os.path.exists(training_args.output_dir )
and os.listdir(training_args.output_dir )
and training_args.do_train
and not training_args.overwrite_output_dir
):
raise ValueError(
F"Output directory ({training_args.output_dir}) already exists and is not empty. Use"
""" --overwrite_output_dir to overcome.""" )
# Setup logging
logging.basicConfig(
format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO , )
logger.info(
F"n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1 )}, "
F"16-bits training: {training_args.fpaa}" )
logger.info(F"Training/evaluation parameters {training_args}" )
# Load pretrained model and tokenizer
#
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
__SCREAMING_SNAKE_CASE : Any = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = get_tfds(
train_file=data_args.train_file , eval_file=data_args.dev_file , test_file=data_args.test_file , tokenizer=_lowerCamelCase , label_column_id=data_args.label_column_id , max_seq_length=data_args.max_seq_length , )
__SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=len(_lowerCamelCase ) , labelaid=_lowerCamelCase , idalabel={id: label for label, id in labelaid.items()} , finetuning_task="""text-classification""" , cache_dir=model_args.cache_dir , )
with training_args.strategy.scope():
__SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForSequenceClassification.from_pretrained(
model_args.model_name_or_path , from_pt=bool(""".bin""" in model_args.model_name_or_path ) , config=_lowerCamelCase , cache_dir=model_args.cache_dir , )
def compute_metrics(_lowerCamelCase: EvalPrediction ) -> Dict:
__SCREAMING_SNAKE_CASE : List[Any] = np.argmax(p.predictions , axis=1 )
return {"acc": (preds == p.label_ids).mean()}
# Initialize our Trainer
__SCREAMING_SNAKE_CASE : List[Any] = TFTrainer(
model=_lowerCamelCase , args=_lowerCamelCase , train_dataset=_lowerCamelCase , eval_dataset=_lowerCamelCase , compute_metrics=_lowerCamelCase , )
# Training
if training_args.do_train:
trainer.train()
trainer.save_model()
tokenizer.save_pretrained(training_args.output_dir )
# Evaluation
__SCREAMING_SNAKE_CASE : Dict = {}
if training_args.do_eval:
logger.info("""*** Evaluate ***""" )
__SCREAMING_SNAKE_CASE : Union[str, Any] = trainer.evaluate()
__SCREAMING_SNAKE_CASE : List[str] = os.path.join(training_args.output_dir , """eval_results.txt""" )
with open(_lowerCamelCase , """w""" ) as writer:
logger.info("""***** Eval results *****""" )
for key, value in result.items():
logger.info(F" {key} = {value}" )
writer.write(F"{key} = {value}\n" )
results.update(_lowerCamelCase )
return results
if __name__ == "__main__":
main() | 578 | 0 |
'''simple docstring'''
import qiskit
def UpperCamelCase ( __lowercase : int ,__lowercase : int ):
'''simple docstring'''
A_ : List[Any] = qiskit.Aer.get_backend('aer_simulator' )
# Create a Quantum Circuit acting on the q register
A_ : Union[str, Any] = qiskit.QuantumCircuit(__lowercase ,__lowercase )
# Map the quantum measurement to the classical bits
circuit.measure([0] ,[0] )
# Execute the circuit on the simulator
A_ : List[str] = qiskit.execute(__lowercase ,__lowercase ,shots=10_00 )
# Return the histogram data of the results of the experiment.
return job.result().get_counts(__lowercase )
if __name__ == "__main__":
print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
| 700 | from math import sqrt
def UpperCamelCase ( __lowercase : int = 1_00_00_00 ):
'''simple docstring'''
A_ : int = 0
A_ : int = 0
A_ : int
while num_cuboids <= limit:
max_cuboid_size += 1
for sum_shortest_sides in range(2 ,2 * max_cuboid_size + 1 ):
if sqrt(sum_shortest_sides**2 + max_cuboid_size**2 ).is_integer():
num_cuboids += (
min(__lowercase ,sum_shortest_sides // 2 )
- max(1 ,sum_shortest_sides - max_cuboid_size )
+ 1
)
return max_cuboid_size
if __name__ == "__main__":
print(F"""{solution() = }""")
| 70 | 0 |
import argparse
import re
from pathlib import Path
import requests
import torch
from PIL import Image
from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor
from transformers import (
EfficientFormerConfig,
EfficientFormerForImageClassificationWithTeacher,
EfficientFormerImageProcessor,
)
from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling
def lowerCamelCase__ ( _A , _A ):
'''simple docstring'''
snake_case_ = old_name
if "patch_embed" in old_name:
snake_case_ , snake_case_ , snake_case_ = old_name.split("." )
if layer == "0":
snake_case_ = old_name.replace("0" , "convolution1" )
elif layer == "1":
snake_case_ = old_name.replace("1" , "batchnorm_before" )
elif layer == "3":
snake_case_ = old_name.replace("3" , "convolution2" )
else:
snake_case_ = old_name.replace("4" , "batchnorm_after" )
if "network" in old_name and re.search(R"\d\.\d" , _A ):
snake_case_ = R"\b\d{2}\b"
if bool(re.search(_A , _A ) ):
snake_case_ = re.search(R"\d\.\d\d." , _A ).group()
else:
snake_case_ = re.search(R"\d\.\d." , _A ).group()
if int(match[0] ) < 6:
snake_case_ = old_name.replace(_A , "" )
snake_case_ = trimmed_name.replace("network" , match[0] + ".meta4D_layers.blocks." + match[2:-1] )
snake_case_ = "intermediate_stages." + trimmed_name
else:
snake_case_ = old_name.replace(_A , "" )
if int(match[2] ) < num_meta4D_last_stage:
snake_case_ = trimmed_name.replace("network" , "meta4D_layers.blocks." + match[2] )
else:
snake_case_ = str(int(match[2] ) - num_meta4D_last_stage )
snake_case_ = trimmed_name.replace("network" , "meta3D_layers.blocks." + layer_index )
if "norm1" in old_name:
snake_case_ = trimmed_name.replace("norm1" , "layernorm1" )
elif "norm2" in old_name:
snake_case_ = trimmed_name.replace("norm2" , "layernorm2" )
elif "fc1" in old_name:
snake_case_ = trimmed_name.replace("fc1" , "linear_in" )
elif "fc2" in old_name:
snake_case_ = trimmed_name.replace("fc2" , "linear_out" )
snake_case_ = "last_stage." + trimmed_name
elif "network" in old_name and re.search(R".\d." , _A ):
snake_case_ = old_name.replace("network" , "intermediate_stages" )
if "fc" in new_name:
snake_case_ = new_name.replace("fc" , "convolution" )
elif ("norm1" in new_name) and ("layernorm1" not in new_name):
snake_case_ = new_name.replace("norm1" , "batchnorm_before" )
elif ("norm2" in new_name) and ("layernorm2" not in new_name):
snake_case_ = new_name.replace("norm2" , "batchnorm_after" )
if "proj" in new_name:
snake_case_ = new_name.replace("proj" , "projection" )
if "dist_head" in new_name:
snake_case_ = new_name.replace("dist_head" , "distillation_classifier" )
elif "head" in new_name:
snake_case_ = new_name.replace("head" , "classifier" )
elif "patch_embed" in new_name:
snake_case_ = "efficientformer." + new_name
elif new_name == "norm.weight" or new_name == "norm.bias":
snake_case_ = new_name.replace("norm" , "layernorm" )
snake_case_ = "efficientformer." + new_name
else:
snake_case_ = "efficientformer.encoder." + new_name
return new_name
def lowerCamelCase__ ( _A , _A ):
'''simple docstring'''
for key in checkpoint.copy().keys():
snake_case_ = checkpoint.pop(_A )
snake_case_ = val
return checkpoint
def lowerCamelCase__ ( ):
'''simple docstring'''
snake_case_ = "http://images.cocodataset.org/val2017/000000039769.jpg"
snake_case_ = Image.open(requests.get(_A , stream=_A ).raw )
return image
def lowerCamelCase__ ( _A , _A , _A , _A ):
'''simple docstring'''
snake_case_ = torch.load(_A , map_location="cpu" )["model"]
snake_case_ = EfficientFormerConfig.from_json_file(_A )
snake_case_ = EfficientFormerForImageClassificationWithTeacher(_A )
snake_case_ = "_".join(checkpoint_path.split("/" )[-1].split("." )[0].split("_" )[:-1] )
snake_case_ = config.depths[-1] - config.num_metaad_blocks + 1
snake_case_ = convert_torch_checkpoint(_A , _A )
model.load_state_dict(_A )
model.eval()
snake_case_ = {
"bilinear": PILImageResampling.BILINEAR,
"bicubic": PILImageResampling.BICUBIC,
"nearest": PILImageResampling.NEAREST,
}
# prepare image
snake_case_ = prepare_img()
snake_case_ = 256
snake_case_ = 224
snake_case_ = EfficientFormerImageProcessor(
size={"shortest_edge": image_size} , crop_size={"height": crop_size, "width": crop_size} , resample=pillow_resamplings["bicubic"] , )
snake_case_ = processor(images=_A , return_tensors="pt" ).pixel_values
# original processing pipeline
snake_case_ = Compose(
[
Resize(_A , interpolation=pillow_resamplings["bicubic"] ),
CenterCrop(_A ),
ToTensor(),
Normalize(_A , _A ),
] )
snake_case_ = image_transforms(_A ).unsqueeze(0 )
assert torch.allclose(_A , _A )
snake_case_ = model(_A )
snake_case_ = outputs.logits
snake_case_ = (1, 1000)
if "l1" in model_name:
snake_case_ = torch.Tensor(
[-0.13_12, 0.43_53, -1.04_99, -0.51_24, 0.41_83, -0.67_93, -1.37_77, -0.08_93, -0.73_58, -2.43_28] )
assert torch.allclose(logits[0, :10] , _A , atol=1E-3 )
assert logits.shape == expected_shape
elif "l3" in model_name:
snake_case_ = torch.Tensor(
[-1.31_50, -1.54_56, -1.25_56, -0.84_96, -0.71_27, -0.78_97, -0.97_28, -0.30_52, 0.37_51, -0.31_27] )
assert torch.allclose(logits[0, :10] , _A , atol=1E-3 )
assert logits.shape == expected_shape
elif "l7" in model_name:
snake_case_ = torch.Tensor(
[-1.02_83, -1.41_31, -0.56_44, -1.31_15, -0.57_85, -1.20_49, -0.75_28, 0.19_92, -0.38_22, -0.08_78] )
assert logits.shape == expected_shape
else:
raise ValueError(
f"Unknown model checkpoint: {checkpoint_path}. Supported version of efficientformer are l1, l3 and l7" )
# Save Checkpoints
Path(_A ).mkdir(exist_ok=_A )
model.save_pretrained(_A )
print(f"Checkpoint successfuly converted. Model saved at {pytorch_dump_path}" )
processor.save_pretrained(_A )
print(f"Processor successfuly saved at {pytorch_dump_path}" )
if push_to_hub:
print("Pushing model to the hub..." )
model.push_to_hub(
repo_id=f"Bearnardd/{pytorch_dump_path}" , commit_message="Add model" , use_temp_dir=_A , )
processor.push_to_hub(
repo_id=f"Bearnardd/{pytorch_dump_path}" , commit_message="Add image processor" , use_temp_dir=_A , )
if __name__ == "__main__":
lowercase__ : Tuple = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--pytorch_model_path",
default=None,
type=str,
required=True,
help="Path to EfficientFormer pytorch checkpoint.",
)
parser.add_argument(
"--config_file",
default=None,
type=str,
required=True,
help="The json file for EfficientFormer model config.",
)
parser.add_argument(
"--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
)
parser.add_argument("--push_to_hub", action="store_true", help="Push model and image processor to the hub")
parser.add_argument(
"--no-push_to_hub",
dest="push_to_hub",
action="store_false",
help="Do not push model and image processor to the hub",
)
parser.set_defaults(push_to_hub=True)
lowercase__ : Optional[Any] = parser.parse_args()
convert_efficientformer_checkpoint(
checkpoint_path=args.pytorch_model_path,
efficientformer_config_file=args.config_file,
pytorch_dump_path=args.pytorch_dump_path,
push_to_hub=args.push_to_hub,
)
| 376 |
def lowerCamelCase__ ( _A , _A ):
'''simple docstring'''
_validate_point(_A )
_validate_point(_A )
if len(_A ) != len(_A ):
raise ValueError("Both points must be in the same n-dimensional space" )
return float(sum(abs(a - b ) for a, b in zip(_A , _A ) ) )
def lowerCamelCase__ ( _A ):
'''simple docstring'''
if point:
if isinstance(_A , _A ):
for item in point:
if not isinstance(_A , (int, float) ):
snake_case_ = (
"Expected a list of numbers as input, found "
f"{type(_A ).__name__}"
)
raise TypeError(_A )
else:
snake_case_ = f"Expected a list of numbers as input, found {type(_A ).__name__}"
raise TypeError(_A )
else:
raise ValueError("Missing an input" )
def lowerCamelCase__ ( _A , _A ):
'''simple docstring'''
_validate_point(_A )
_validate_point(_A )
if len(_A ) != len(_A ):
raise ValueError("Both points must be in the same n-dimensional space" )
return float(sum(abs(x - y ) for x, y in zip(_A , _A ) ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 376 | 1 |
lowercase__ : List[Any] = "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n"
lowercase__ : Union[str, Any] = [{"type": "code", "content": INSTALL_CONTENT}]
lowercase__ : Optional[int] = {
"{processor_class}": "FakeProcessorClass",
"{model_class}": "FakeModelClass",
"{object_class}": "FakeObjectClass",
}
| 720 |
import unittest
from diffusers import FlaxAutoencoderKL
from diffusers.utils import is_flax_available
from diffusers.utils.testing_utils import require_flax
from .test_modeling_common_flax import FlaxModelTesterMixin
if is_flax_available():
import jax
@require_flax
class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ):
"""simple docstring"""
_snake_case = FlaxAutoencoderKL
@property
def A__ ( self )-> int:
'''simple docstring'''
__UpperCamelCase = 4
__UpperCamelCase = 3
__UpperCamelCase = (32, 32)
__UpperCamelCase = jax.random.PRNGKey(0 )
__UpperCamelCase = jax.random.uniform(SCREAMING_SNAKE_CASE_ , ((batch_size, num_channels) + sizes) )
return {"sample": image, "prng_key": prng_key}
def A__ ( self )-> List[Any]:
'''simple docstring'''
__UpperCamelCase = {
'''block_out_channels''': [32, 64],
'''in_channels''': 3,
'''out_channels''': 3,
'''down_block_types''': ['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''],
'''up_block_types''': ['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''],
'''latent_channels''': 4,
}
__UpperCamelCase = self.dummy_input
return init_dict, inputs_dict
| 451 | 0 |
'''simple docstring'''
import json
import pathlib
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import DetrImageProcessor
class a ( unittest.TestCase ):
'''simple docstring'''
def __init__( self , lowerCamelCase_ , lowerCamelCase_=7 , lowerCamelCase_=3 , lowerCamelCase_=3_0 , lowerCamelCase_=4_0_0 , lowerCamelCase_=True , lowerCamelCase_=None , lowerCamelCase_=True , lowerCamelCase_=1 / 2_5_5 , lowerCamelCase_=True , lowerCamelCase_=[0.5, 0.5, 0.5] , lowerCamelCase_=[0.5, 0.5, 0.5] , lowerCamelCase_=True , ) -> List[Any]:
# by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
_a : List[str] = size if size is not None else {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3}
_a : Tuple = parent
_a : List[Any] = batch_size
_a : Dict = num_channels
_a : str = min_resolution
_a : List[str] = max_resolution
_a : Dict = do_resize
_a : Optional[int] = size
_a : List[str] = do_rescale
_a : str = rescale_factor
_a : str = do_normalize
_a : Union[str, Any] = image_mean
_a : int = image_std
_a : str = do_pad
def __UpperCamelCase ( self ) -> List[str]:
return {
"do_resize": self.do_resize,
"size": self.size,
"do_rescale": self.do_rescale,
"rescale_factor": self.rescale_factor,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_pad": self.do_pad,
}
def __UpperCamelCase ( self , lowerCamelCase_ , lowerCamelCase_=False ) -> Any:
if not batched:
_a : Dict = image_inputs[0]
if isinstance(__A , Image.Image ):
_a , _a : int = image.size
else:
_a , _a : Dict = image.shape[1], image.shape[2]
if w < h:
_a : Any = int(self.size['shortest_edge'] * h / w )
_a : Union[str, Any] = self.size['shortest_edge']
elif w > h:
_a : str = self.size['shortest_edge']
_a : List[str] = int(self.size['shortest_edge'] * w / h )
else:
_a : Union[str, Any] = self.size['shortest_edge']
_a : Tuple = self.size['shortest_edge']
else:
_a : Optional[Any] = []
for image in image_inputs:
_a , _a : str = self.get_expected_values([image] )
expected_values.append((expected_height, expected_width) )
_a : Optional[int] = max(__A , key=lambda lowerCamelCase_ : item[0] )[0]
_a : Any = max(__A , key=lambda lowerCamelCase_ : item[1] )[1]
return expected_height, expected_width
@require_torch
@require_vision
class a ( UpperCAmelCase_ , unittest.TestCase ):
'''simple docstring'''
__lowerCAmelCase : Any = DetrImageProcessor if is_vision_available() else None
def __UpperCamelCase ( self ) -> int:
_a : Any = DetrImageProcessingTester(self )
@property
def __UpperCamelCase ( self ) -> Optional[int]:
return self.image_processor_tester.prepare_image_processor_dict()
def __UpperCamelCase ( self ) -> Any:
_a : Optional[int] = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(__A , 'image_mean' ) )
self.assertTrue(hasattr(__A , 'image_std' ) )
self.assertTrue(hasattr(__A , 'do_normalize' ) )
self.assertTrue(hasattr(__A , 'do_rescale' ) )
self.assertTrue(hasattr(__A , 'rescale_factor' ) )
self.assertTrue(hasattr(__A , 'do_resize' ) )
self.assertTrue(hasattr(__A , 'size' ) )
self.assertTrue(hasattr(__A , 'do_pad' ) )
def __UpperCamelCase ( self ) -> Optional[int]:
_a : Dict = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3} )
self.assertEqual(image_processor.do_pad , __A )
_a : Any = self.image_processing_class.from_dict(
self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=__A )
self.assertEqual(image_processor.size , {'shortest_edge': 4_2, 'longest_edge': 8_4} )
self.assertEqual(image_processor.do_pad , __A )
def __UpperCamelCase ( self ) -> int:
pass
def __UpperCamelCase ( self ) -> Tuple:
# Initialize image_processing
_a : Optional[Any] = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
_a : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A )
for image in image_inputs:
self.assertIsInstance(__A , Image.Image )
# Test not batched input
_a : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
_a , _a : str = self.image_processor_tester.get_expected_values(__A )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
_a , _a : Dict = self.image_processor_tester.get_expected_values(__A , batched=__A )
_a : List[str] = image_processing(__A , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def __UpperCamelCase ( self ) -> Dict:
# Initialize image_processing
_a : Optional[int] = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
_a : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A , numpify=__A )
for image in image_inputs:
self.assertIsInstance(__A , np.ndarray )
# Test not batched input
_a : str = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
_a , _a : Any = self.image_processor_tester.get_expected_values(__A )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
_a : List[Any] = image_processing(__A , return_tensors='pt' ).pixel_values
_a , _a : Union[str, Any] = self.image_processor_tester.get_expected_values(__A , batched=__A )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def __UpperCamelCase ( self ) -> Optional[Any]:
# Initialize image_processing
_a : Tuple = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
_a : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A , torchify=__A )
for image in image_inputs:
self.assertIsInstance(__A , torch.Tensor )
# Test not batched input
_a : List[str] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
_a , _a : Tuple = self.image_processor_tester.get_expected_values(__A )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
_a : str = image_processing(__A , return_tensors='pt' ).pixel_values
_a , _a : str = self.image_processor_tester.get_expected_values(__A , batched=__A )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
@slow
def __UpperCamelCase ( self ) -> List[str]:
# prepare image and target
_a : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f:
_a : int = json.loads(f.read() )
_a : List[Any] = {'image_id': 3_9_7_6_9, 'annotations': target}
# encode them
_a : Any = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50' )
_a : Dict = image_processing(images=__A , annotations=__A , return_tensors='pt' )
# verify pixel values
_a : int = torch.Size([1, 3, 8_0_0, 1_0_6_6] )
self.assertEqual(encoding['pixel_values'].shape , __A )
_a : Any = torch.tensor([0.2796, 0.3138, 0.3481] )
self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , __A , atol=1e-4 ) )
# verify area
_a : Tuple = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] )
self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , __A ) )
# verify boxes
_a : str = torch.Size([6, 4] )
self.assertEqual(encoding['labels'][0]['boxes'].shape , __A )
_a : int = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] )
self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , __A , atol=1e-3 ) )
# verify image_id
_a : Optional[Any] = torch.tensor([3_9_7_6_9] )
self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , __A ) )
# verify is_crowd
_a : List[str] = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , __A ) )
# verify class_labels
_a : int = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] )
self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , __A ) )
# verify orig_size
_a : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] )
self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , __A ) )
# verify size
_a : Union[str, Any] = torch.tensor([8_0_0, 1_0_6_6] )
self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , __A ) )
@slow
def __UpperCamelCase ( self ) -> Union[str, Any]:
# prepare image, target and masks_path
_a : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f:
_a : Union[str, Any] = json.loads(f.read() )
_a : Optional[Any] = {'file_name': '000000039769.png', 'image_id': 3_9_7_6_9, 'segments_info': target}
_a : Any = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' )
# encode them
_a : Optional[int] = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50-panoptic' )
_a : Any = image_processing(images=__A , annotations=__A , masks_path=__A , return_tensors='pt' )
# verify pixel values
_a : int = torch.Size([1, 3, 8_0_0, 1_0_6_6] )
self.assertEqual(encoding['pixel_values'].shape , __A )
_a : Tuple = torch.tensor([0.2796, 0.3138, 0.3481] )
self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , __A , atol=1e-4 ) )
# verify area
_a : List[str] = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] )
self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , __A ) )
# verify boxes
_a : List[Any] = torch.Size([6, 4] )
self.assertEqual(encoding['labels'][0]['boxes'].shape , __A )
_a : Optional[int] = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] )
self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , __A , atol=1e-3 ) )
# verify image_id
_a : Optional[int] = torch.tensor([3_9_7_6_9] )
self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , __A ) )
# verify is_crowd
_a : Optional[int] = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , __A ) )
# verify class_labels
_a : Any = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] )
self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , __A ) )
# verify masks
_a : Optional[Any] = 8_2_2_8_7_3
self.assertEqual(encoding['labels'][0]['masks'].sum().item() , __A )
# verify orig_size
_a : List[str] = torch.tensor([4_8_0, 6_4_0] )
self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , __A ) )
# verify size
_a : int = torch.tensor([8_0_0, 1_0_6_6] )
self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , __A ) )
| 120 |
'''simple docstring'''
from collections import Counter
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
_A: List[Any] = datasets.load_iris()
_A: Union[str, Any] = np.array(data["""data"""])
_A: Union[str, Any] = np.array(data["""target"""])
_A: Dict = data["""target_names"""]
_A , _A , _A , _A: List[str] = train_test_split(X, y)
def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase )-> Optional[int]:
return np.linalg.norm(np.array(_lowerCAmelCase ) - np.array(_lowerCAmelCase ) )
def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=5 )-> int:
__UpperCAmelCase = zip(_lowerCAmelCase , _lowerCAmelCase )
# List of distances of all points from the point to be classified
__UpperCAmelCase = []
for data_point in data:
__UpperCAmelCase = euclidean_distance(data_point[0] , _lowerCAmelCase )
distances.append((distance, data_point[1]) )
# Choosing 'k' points with the least distances.
__UpperCAmelCase = [i[1] for i in sorted(_lowerCAmelCase )[:k]]
# Most commonly occurring class among them
# is the class into which the point is classified
__UpperCAmelCase = Counter(_lowerCAmelCase ).most_common(1 )[0][0]
return classes[result]
if __name__ == "__main__":
print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
| 126 | 0 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_torch_available,
)
UpperCAmelCase_ : str = {
"""configuration_resnet""": ["""RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ResNetConfig""", """ResNetOnnxConfig"""]
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ : Union[str, Any] = [
"""RESNET_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""ResNetForImageClassification""",
"""ResNetModel""",
"""ResNetPreTrainedModel""",
"""ResNetBackbone""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ : Optional[int] = [
"""TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""TFResNetForImageClassification""",
"""TFResNetModel""",
"""TFResNetPreTrainedModel""",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ : Any = [
"""FlaxResNetForImageClassification""",
"""FlaxResNetModel""",
"""FlaxResNetPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_resnet import (
RESNET_PRETRAINED_MODEL_ARCHIVE_LIST,
ResNetBackbone,
ResNetForImageClassification,
ResNetModel,
ResNetPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_resnet import (
TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST,
TFResNetForImageClassification,
TFResNetModel,
TFResNetPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel
else:
import sys
UpperCAmelCase_ : List[str] = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
| 720 |
"""simple docstring"""
import unittest
import numpy as np
from transformers.testing_utils import require_flax, require_tf, require_torch
from transformers.utils import (
expand_dims,
flatten_dict,
is_flax_available,
is_tf_available,
is_torch_available,
reshape,
squeeze,
transpose,
)
if is_flax_available():
import jax.numpy as jnp
if is_tf_available():
import tensorflow as tf
if is_torch_available():
import torch
class lowerCAmelCase__ ( unittest.TestCase ):
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( self : str):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ : str = {
'''task_specific_params''': {
'''summarization''': {'''length_penalty''': 1.0, '''max_length''': 128, '''min_length''': 12, '''num_beams''': 4},
'''summarization_cnn''': {'''length_penalty''': 2.0, '''max_length''': 142, '''min_length''': 56, '''num_beams''': 4},
'''summarization_xsum''': {'''length_penalty''': 1.0, '''max_length''': 62, '''min_length''': 11, '''num_beams''': 6},
}
}
SCREAMING_SNAKE_CASE_ : List[str] = {
'''task_specific_params.summarization.length_penalty''': 1.0,
'''task_specific_params.summarization.max_length''': 128,
'''task_specific_params.summarization.min_length''': 12,
'''task_specific_params.summarization.num_beams''': 4,
'''task_specific_params.summarization_cnn.length_penalty''': 2.0,
'''task_specific_params.summarization_cnn.max_length''': 142,
'''task_specific_params.summarization_cnn.min_length''': 56,
'''task_specific_params.summarization_cnn.num_beams''': 4,
'''task_specific_params.summarization_xsum.length_penalty''': 1.0,
'''task_specific_params.summarization_xsum.max_length''': 62,
'''task_specific_params.summarization_xsum.min_length''': 11,
'''task_specific_params.summarization_xsum.num_beams''': 6,
}
self.assertEqual(flatten_dict(lowercase_) , lowercase_)
def _SCREAMING_SNAKE_CASE ( self : List[Any]):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ : Optional[int] = np.random.randn(3 , 4)
self.assertTrue(np.allclose(transpose(lowercase_) , x.transpose()))
SCREAMING_SNAKE_CASE_ : Optional[Any] = np.random.randn(3 , 4 , 5)
self.assertTrue(np.allclose(transpose(lowercase_ , axes=(1, 2, 0)) , x.transpose((1, 2, 0))))
@require_torch
def _SCREAMING_SNAKE_CASE ( self : Dict):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ : str = np.random.randn(3 , 4)
SCREAMING_SNAKE_CASE_ : str = torch.tensor(lowercase_)
self.assertTrue(np.allclose(transpose(lowercase_) , transpose(lowercase_).numpy()))
SCREAMING_SNAKE_CASE_ : List[Any] = np.random.randn(3 , 4 , 5)
SCREAMING_SNAKE_CASE_ : Dict = torch.tensor(lowercase_)
self.assertTrue(np.allclose(transpose(lowercase_ , axes=(1, 2, 0)) , transpose(lowercase_ , axes=(1, 2, 0)).numpy()))
@require_tf
def _SCREAMING_SNAKE_CASE ( self : Tuple):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.random.randn(3 , 4)
SCREAMING_SNAKE_CASE_ : str = tf.constant(lowercase_)
self.assertTrue(np.allclose(transpose(lowercase_) , transpose(lowercase_).numpy()))
SCREAMING_SNAKE_CASE_ : Optional[int] = np.random.randn(3 , 4 , 5)
SCREAMING_SNAKE_CASE_ : int = tf.constant(lowercase_)
self.assertTrue(np.allclose(transpose(lowercase_ , axes=(1, 2, 0)) , transpose(lowercase_ , axes=(1, 2, 0)).numpy()))
@require_flax
def _SCREAMING_SNAKE_CASE ( self : Optional[Any]):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ : Tuple = np.random.randn(3 , 4)
SCREAMING_SNAKE_CASE_ : Any = jnp.array(lowercase_)
self.assertTrue(np.allclose(transpose(lowercase_) , np.asarray(transpose(lowercase_))))
SCREAMING_SNAKE_CASE_ : Dict = np.random.randn(3 , 4 , 5)
SCREAMING_SNAKE_CASE_ : Any = jnp.array(lowercase_)
self.assertTrue(np.allclose(transpose(lowercase_ , axes=(1, 2, 0)) , np.asarray(transpose(lowercase_ , axes=(1, 2, 0)))))
def _SCREAMING_SNAKE_CASE ( self : Optional[int]):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ : Dict = np.random.randn(3 , 4)
self.assertTrue(np.allclose(reshape(lowercase_ , (4, 3)) , np.reshape(lowercase_ , (4, 3))))
SCREAMING_SNAKE_CASE_ : Dict = np.random.randn(3 , 4 , 5)
self.assertTrue(np.allclose(reshape(lowercase_ , (12, 5)) , np.reshape(lowercase_ , (12, 5))))
@require_torch
def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.random.randn(3 , 4)
SCREAMING_SNAKE_CASE_ : List[str] = torch.tensor(lowercase_)
self.assertTrue(np.allclose(reshape(lowercase_ , (4, 3)) , reshape(lowercase_ , (4, 3)).numpy()))
SCREAMING_SNAKE_CASE_ : int = np.random.randn(3 , 4 , 5)
SCREAMING_SNAKE_CASE_ : int = torch.tensor(lowercase_)
self.assertTrue(np.allclose(reshape(lowercase_ , (12, 5)) , reshape(lowercase_ , (12, 5)).numpy()))
@require_tf
def _SCREAMING_SNAKE_CASE ( self : Dict):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ : Optional[Any] = np.random.randn(3 , 4)
SCREAMING_SNAKE_CASE_ : int = tf.constant(lowercase_)
self.assertTrue(np.allclose(reshape(lowercase_ , (4, 3)) , reshape(lowercase_ , (4, 3)).numpy()))
SCREAMING_SNAKE_CASE_ : List[Any] = np.random.randn(3 , 4 , 5)
SCREAMING_SNAKE_CASE_ : Union[str, Any] = tf.constant(lowercase_)
self.assertTrue(np.allclose(reshape(lowercase_ , (12, 5)) , reshape(lowercase_ , (12, 5)).numpy()))
@require_flax
def _SCREAMING_SNAKE_CASE ( self : Any):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ : Any = np.random.randn(3 , 4)
SCREAMING_SNAKE_CASE_ : List[Any] = jnp.array(lowercase_)
self.assertTrue(np.allclose(reshape(lowercase_ , (4, 3)) , np.asarray(reshape(lowercase_ , (4, 3)))))
SCREAMING_SNAKE_CASE_ : Optional[Any] = np.random.randn(3 , 4 , 5)
SCREAMING_SNAKE_CASE_ : List[Any] = jnp.array(lowercase_)
self.assertTrue(np.allclose(reshape(lowercase_ , (12, 5)) , np.asarray(reshape(lowercase_ , (12, 5)))))
def _SCREAMING_SNAKE_CASE ( self : List[Any]):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ : List[Any] = np.random.randn(1 , 3 , 4)
self.assertTrue(np.allclose(squeeze(lowercase_) , np.squeeze(lowercase_)))
SCREAMING_SNAKE_CASE_ : str = np.random.randn(1 , 4 , 1 , 5)
self.assertTrue(np.allclose(squeeze(lowercase_ , axis=2) , np.squeeze(lowercase_ , axis=2)))
@require_torch
def _SCREAMING_SNAKE_CASE ( self : Any):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.random.randn(1 , 3 , 4)
SCREAMING_SNAKE_CASE_ : int = torch.tensor(lowercase_)
self.assertTrue(np.allclose(squeeze(lowercase_) , squeeze(lowercase_).numpy()))
SCREAMING_SNAKE_CASE_ : Optional[Any] = np.random.randn(1 , 4 , 1 , 5)
SCREAMING_SNAKE_CASE_ : str = torch.tensor(lowercase_)
self.assertTrue(np.allclose(squeeze(lowercase_ , axis=2) , squeeze(lowercase_ , axis=2).numpy()))
@require_tf
def _SCREAMING_SNAKE_CASE ( self : List[str]):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ : int = np.random.randn(1 , 3 , 4)
SCREAMING_SNAKE_CASE_ : Dict = tf.constant(lowercase_)
self.assertTrue(np.allclose(squeeze(lowercase_) , squeeze(lowercase_).numpy()))
SCREAMING_SNAKE_CASE_ : List[Any] = np.random.randn(1 , 4 , 1 , 5)
SCREAMING_SNAKE_CASE_ : Any = tf.constant(lowercase_)
self.assertTrue(np.allclose(squeeze(lowercase_ , axis=2) , squeeze(lowercase_ , axis=2).numpy()))
@require_flax
def _SCREAMING_SNAKE_CASE ( self : int):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.random.randn(1 , 3 , 4)
SCREAMING_SNAKE_CASE_ : Optional[Any] = jnp.array(lowercase_)
self.assertTrue(np.allclose(squeeze(lowercase_) , np.asarray(squeeze(lowercase_))))
SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.random.randn(1 , 4 , 1 , 5)
SCREAMING_SNAKE_CASE_ : str = jnp.array(lowercase_)
self.assertTrue(np.allclose(squeeze(lowercase_ , axis=2) , np.asarray(squeeze(lowercase_ , axis=2))))
def _SCREAMING_SNAKE_CASE ( self : Tuple):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ : int = np.random.randn(3 , 4)
self.assertTrue(np.allclose(expand_dims(lowercase_ , axis=1) , np.expand_dims(lowercase_ , axis=1)))
@require_torch
def _SCREAMING_SNAKE_CASE ( self : Dict):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ : int = np.random.randn(3 , 4)
SCREAMING_SNAKE_CASE_ : int = torch.tensor(lowercase_)
self.assertTrue(np.allclose(expand_dims(lowercase_ , axis=1) , expand_dims(lowercase_ , axis=1).numpy()))
@require_tf
def _SCREAMING_SNAKE_CASE ( self : str):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ : List[str] = np.random.randn(3 , 4)
SCREAMING_SNAKE_CASE_ : Any = tf.constant(lowercase_)
self.assertTrue(np.allclose(expand_dims(lowercase_ , axis=1) , expand_dims(lowercase_ , axis=1).numpy()))
@require_flax
def _SCREAMING_SNAKE_CASE ( self : Optional[Any]):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ : Tuple = np.random.randn(3 , 4)
SCREAMING_SNAKE_CASE_ : int = jnp.array(lowercase_)
self.assertTrue(np.allclose(expand_dims(lowercase_ , axis=1) , np.asarray(expand_dims(lowercase_ , axis=1))))
| 176 | 0 |
'''simple docstring'''
from collections import deque
def lowercase__ ( __lowercase : int ) -> Union[str, Any]:
"""simple docstring"""
__UpperCamelCase = len(__lowercase )
__UpperCamelCase = deque()
__UpperCamelCase = [False for _ in range(__lowercase )]
__UpperCamelCase = [-1 for _ in range(__lowercase )]
__UpperCamelCase = index_of[:]
def strong_connect(__lowercase : str , __lowercase : int , __lowercase : Any ):
__UpperCamelCase = index # the number when this node is seen
__UpperCamelCase = index # lowest rank node reachable from here
index += 1
stack.append(__lowercase )
__UpperCamelCase = True
for w in g[v]:
if index_of[w] == -1:
__UpperCamelCase = strong_connect(__lowercase , __lowercase , __lowercase )
__UpperCamelCase = (
lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v]
)
elif on_stack[w]:
__UpperCamelCase = (
lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v]
)
if lowlink_of[v] == index_of[v]:
__UpperCamelCase = []
__UpperCamelCase = stack.pop()
__UpperCamelCase = False
component.append(__lowercase )
while w != v:
__UpperCamelCase = stack.pop()
__UpperCamelCase = False
component.append(__lowercase )
components.append(__lowercase )
return index
__UpperCamelCase = []
for v in range(__lowercase ):
if index_of[v] == -1:
strong_connect(__lowercase , 0 , __lowercase )
return components
def lowercase__ ( __lowercase : Union[str, Any] , __lowercase : Dict ) -> int:
"""simple docstring"""
__UpperCamelCase = [[] for _ in range(__lowercase )]
for u, v in edges:
g[u].append(__lowercase )
return g
if __name__ == "__main__":
# Test
a__ : List[Any] =7
a__ : Any =[0, 0, 1, 2, 3, 3, 4, 4, 6]
a__ : List[Any] =[1, 3, 2, 0, 1, 4, 5, 6, 5]
a__ : Optional[int] =[(u, v) for u, v in zip(source, target)]
a__ : Dict =create_graph(n_vertices, edges)
assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
| 399 |
'''simple docstring'''
import random
import timeit
from functools import wraps
from typing import Callable, Optional
from ..configuration_utils import PretrainedConfig
from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING
from ..utils import is_pyanvml_available, is_tf_available, logging
from .benchmark_utils import (
Benchmark,
Memory,
MemorySummary,
measure_peak_memory_cpu,
start_memory_tracing,
stop_memory_tracing,
)
if is_tf_available():
import tensorflow as tf
from tensorflow.python.framework.errors_impl import ResourceExhaustedError
from .benchmark_args_tf import TensorFlowBenchmarkArguments
if is_pyanvml_available():
import pyanvml.pyanvml as nvml
a__ : Union[str, Any] =logging.get_logger(__name__)
def lowercase__ ( __lowercase : bool , __lowercase : bool ) -> Any:
"""simple docstring"""
def run_func(__lowercase : Tuple ):
@wraps(__lowercase )
def run_in_eager_mode(*__lowercase : Any , **__lowercase : Any ):
return func(*__lowercase , **__lowercase )
@wraps(__lowercase )
@tf.function(experimental_compile=__lowercase )
def run_in_graph_mode(*__lowercase : List[str] , **__lowercase : Optional[int] ):
return func(*__lowercase , **__lowercase )
if do_eager_mode is True:
if use_xla is not False:
raise ValueError(
'Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`.' )
return run_in_eager_mode
else:
return run_in_graph_mode
return run_func
def lowercase__ ( __lowercase : int , __lowercase : int , __lowercase : int ) -> ["tf.Tensor"]:
"""simple docstring"""
__UpperCamelCase = random.Random()
__UpperCamelCase = [rng.randint(0 , vocab_size - 1 ) for i in range(batch_size * sequence_length )]
return tf.constant(__lowercase , shape=(batch_size, sequence_length) , dtype=tf.intaa )
class snake_case ( __lowerCamelCase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : TensorFlowBenchmarkArguments
SCREAMING_SNAKE_CASE_ : PretrainedConfig
SCREAMING_SNAKE_CASE_ : str ="TensorFlow"
@property
def _lowerCamelCase ( self : List[str] ):
return tf.__version__
def _lowerCamelCase ( self : Union[str, Any] , __A : str , __A : int , __A : int ):
# initialize GPU on separate process
__UpperCamelCase = self.args.strategy
if strategy is None:
raise ValueError('A device strategy has to be initialized before using TensorFlow.' )
__UpperCamelCase = self._prepare_inference_func(__A , __A , __A )
return self._measure_speed(_inference )
def _lowerCamelCase ( self : Dict , __A : str , __A : int , __A : int ):
__UpperCamelCase = self.args.strategy
if strategy is None:
raise ValueError('A device strategy has to be initialized before using TensorFlow.' )
__UpperCamelCase = self._prepare_train_func(__A , __A , __A )
return self._measure_speed(_train )
def _lowerCamelCase ( self : str , __A : str , __A : int , __A : int ):
# initialize GPU on separate process
if self.args.is_gpu:
tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , __A )
__UpperCamelCase = self.args.strategy
if strategy is None:
raise ValueError('A device strategy has to be initialized before using TensorFlow.' )
__UpperCamelCase = self._prepare_inference_func(__A , __A , __A )
return self._measure_memory(_inference )
def _lowerCamelCase ( self : Dict , __A : str , __A : int , __A : int ):
if self.args.is_gpu:
tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , __A )
__UpperCamelCase = self.args.strategy
if strategy is None:
raise ValueError('A device strategy has to be initialized before using TensorFlow.' )
__UpperCamelCase = self._prepare_train_func(__A , __A , __A )
return self._measure_memory(_train )
def _lowerCamelCase ( self : Union[str, Any] , __A : str , __A : int , __A : int ):
__UpperCamelCase = self.config_dict[model_name]
if self.args.fpaa:
raise NotImplementedError('Mixed precision is currently not supported.' )
__UpperCamelCase = (
hasattr(__A , 'architectures' )
and isinstance(config.architectures , __A )
and len(config.architectures ) > 0
)
if not self.args.only_pretrain_model and has_model_class_in_config:
try:
__UpperCamelCase = 'TF' + config.architectures[0] # prepend 'TF' for tensorflow model
__UpperCamelCase = __import__('transformers' , fromlist=[model_class] )
__UpperCamelCase = getattr(__A , __A )
__UpperCamelCase = model_cls(__A )
except ImportError:
raise ImportError(
f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to'''
' set `--only_pretrain_model` or `args.only_pretrain_model=True`.' )
else:
__UpperCamelCase = TF_MODEL_MAPPING[config.__class__](__A )
# encoder-decoder has vocab size saved differently
__UpperCamelCase = config.vocab_size if hasattr(__A , 'vocab_size' ) else config.encoder.vocab_size
__UpperCamelCase = random_input_ids(__A , __A , __A )
@run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla )
def encoder_decoder_forward():
return model(__A , decoder_input_ids=__A , training=__A )
@run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla )
def encoder_forward():
return model(__A , training=__A )
__UpperCamelCase = encoder_decoder_forward if config.is_encoder_decoder else encoder_forward
return _inference
def _lowerCamelCase ( self : Any , __A : str , __A : int , __A : int ):
__UpperCamelCase = self.config_dict[model_name]
if self.args.eager_mode is not False:
raise ValueError('Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.' )
if self.args.fpaa:
raise NotImplementedError('Mixed precision is currently not supported.' )
__UpperCamelCase = (
hasattr(__A , 'architectures' )
and isinstance(config.architectures , __A )
and len(config.architectures ) > 0
)
if not self.args.only_pretrain_model and has_model_class_in_config:
try:
__UpperCamelCase = 'TF' + config.architectures[0] # prepend 'TF' for tensorflow model
__UpperCamelCase = __import__('transformers' , fromlist=[model_class] )
__UpperCamelCase = getattr(__A , __A )
__UpperCamelCase = model_cls(__A )
except ImportError:
raise ImportError(
f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to'''
' set `--only_pretrain_model` or `args.only_pretrain_model=True`.' )
else:
__UpperCamelCase = TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](__A )
# encoder-decoder has vocab size saved differently
__UpperCamelCase = config.vocab_size if hasattr(__A , 'vocab_size' ) else config.encoder.vocab_size
__UpperCamelCase = random_input_ids(__A , __A , __A )
@run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla )
def encoder_decoder_train():
__UpperCamelCase = model(__A , decoder_input_ids=__A , labels=__A , training=__A )[0]
__UpperCamelCase = tf.gradients(__A , model.trainable_variables )
return gradients
@run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla )
def encoder_train():
__UpperCamelCase = model(__A , labels=__A , training=__A )[0]
__UpperCamelCase = tf.gradients(__A , model.trainable_variables )
return gradients
__UpperCamelCase = encoder_decoder_train if config.is_encoder_decoder else encoder_train
return _train
def _lowerCamelCase ( self : List[Any] , __A : List[Any] ):
with self.args.strategy.scope():
try:
if self.args.is_tpu or self.args.use_xla:
# run additional 10 times to stabilize compilation for tpu
logger.info('Do inference on TPU. Running model 5 times to stabilize compilation' )
timeit.repeat(__A , repeat=1 , number=5 )
# as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average
__UpperCamelCase = timeit.repeat(
__A , repeat=self.args.repeat , number=1_0 , )
return min(__A ) / 10.0
except ResourceExhaustedError as e:
self.print_fn(f'''Doesn\'t fit on GPU. {e}''' )
def _lowerCamelCase ( self : Optional[int] , __A : Callable[[], None] ):
logger.info(
'Note that TensorFlow allocates more memory than '
'it might need to speed up computation. '
'The memory reported here corresponds to the memory '
'reported by `nvidia-smi`, which can vary depending '
'on total available memory on the GPU that is used.' )
with self.args.strategy.scope():
try:
if self.args.trace_memory_line_by_line:
if not self.args.eager_mode:
raise ValueError(
'`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory'
' consumption line by line.' )
__UpperCamelCase = start_memory_tracing('transformers' )
if self.args.is_tpu:
# tpu
raise NotImplementedError(
'Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking'
' with `args.memory=False`' )
elif self.args.is_gpu:
# gpu
if not is_pyanvml_available():
logger.warning(
'py3nvml not installed, we won\'t log GPU memory usage. '
'Install py3nvml (pip install py3nvml) to log information about GPU.' )
__UpperCamelCase = 'N/A'
else:
logger.info(
'Measuring total GPU usage on GPU device. Make sure to not have additional processes'
' running on the same GPU.' )
# init nvml
nvml.nvmlInit()
func()
__UpperCamelCase = nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx )
__UpperCamelCase = nvml.nvmlDeviceGetMemoryInfo(__A )
__UpperCamelCase = meminfo.used
__UpperCamelCase = Memory(__A )
# shutdown nvml
nvml.nvmlShutdown()
else:
# cpu
if self.args.trace_memory_line_by_line:
logger.info(
'When enabling line by line tracing, the max peak memory for CPU is inaccurate in'
' TensorFlow.' )
__UpperCamelCase = None
else:
__UpperCamelCase = measure_peak_memory_cpu(__A )
__UpperCamelCase = Memory(__A ) if isinstance(__A , __A ) else memory_bytes
if self.args.trace_memory_line_by_line:
__UpperCamelCase = stop_memory_tracing(__A )
if memory is None:
__UpperCamelCase = summary.total
else:
__UpperCamelCase = None
return memory, summary
except ResourceExhaustedError as e:
self.print_fn(f'''Doesn\'t fit on GPU. {e}''' )
return "N/A", None
| 399 | 1 |
"""simple docstring"""
from collections import deque
def UpperCAmelCase ( A : Optional[int] ):
'''simple docstring'''
_UpperCAmelCase = len(A )
_UpperCAmelCase = deque()
_UpperCAmelCase = [False for _ in range(A )]
_UpperCAmelCase = [-1 for _ in range(A )]
_UpperCAmelCase = index_of[:]
def strong_connect(A : List[Any] , A : List[str] , A : Optional[int] ):
_UpperCAmelCase = index # the number when this node is seen
_UpperCAmelCase = index # lowest rank node reachable from here
index += 1
stack.append(A )
_UpperCAmelCase = True
for w in g[v]:
if index_of[w] == -1:
_UpperCAmelCase = strong_connect(A , A , A )
_UpperCAmelCase = (
lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v]
)
elif on_stack[w]:
_UpperCAmelCase = (
lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v]
)
if lowlink_of[v] == index_of[v]:
_UpperCAmelCase = []
_UpperCAmelCase = stack.pop()
_UpperCAmelCase = False
component.append(A )
while w != v:
_UpperCAmelCase = stack.pop()
_UpperCAmelCase = False
component.append(A )
components.append(A )
return index
_UpperCAmelCase = []
for v in range(A ):
if index_of[v] == -1:
strong_connect(A , 0 , A )
return components
def UpperCAmelCase ( A : List[Any] , A : Optional[Any] ):
'''simple docstring'''
_UpperCAmelCase = [[] for _ in range(A )]
for u, v in edges:
g[u].append(A )
return g
if __name__ == "__main__":
# Test
lowercase = 7
lowercase = [0, 0, 1, 2, 3, 3, 4, 4, 6]
lowercase = [1, 3, 2, 0, 1, 4, 5, 6, 5]
lowercase = [(u, v) for u, v in zip(source, target)]
lowercase = create_graph(n_vertices, edges)
assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
| 701 |
"""simple docstring"""
import argparse
import logging
import pickle
from collections import Counter
logging.basicConfig(
format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO
)
lowercase = logging.getLogger(__name__)
if __name__ == "__main__":
lowercase = argparse.ArgumentParser(
description='''Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)'''
)
parser.add_argument(
'''--data_file''', type=str, default='''data/dump.bert-base-uncased.pickle''', help='''The binarized dataset.'''
)
parser.add_argument(
'''--token_counts_dump''', type=str, default='''data/token_counts.bert-base-uncased.pickle''', help='''The dump file.'''
)
parser.add_argument('''--vocab_size''', default=3_05_22, type=int)
lowercase = parser.parse_args()
logger.info(F'''Loading data from {args.data_file}''')
with open(args.data_file, '''rb''') as fp:
lowercase = pickle.load(fp)
logger.info('''Counting occurrences for MLM.''')
lowercase = Counter()
for tk_ids in data:
counter.update(tk_ids)
lowercase = [0] * args.vocab_size
for k, v in counter.items():
lowercase = v
logger.info(F'''Dump to {args.token_counts_dump}''')
with open(args.token_counts_dump, '''wb''') as handle:
pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
| 24 | 0 |
import json
import os
import unittest
from transformers import MgpstrTokenizer
from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class lowercase ( _UpperCAmelCase , unittest.TestCase ):
lowerCamelCase : Union[str, Any] = MgpstrTokenizer
lowerCamelCase : Tuple = False
lowerCamelCase : str = {}
lowerCamelCase : Dict = False
def lowercase__ ( self : Dict ):
super().setUp()
# fmt: off
SCREAMING_SNAKE_CASE__ : Optional[int] = ['''[GO]''', '''[s]''', '''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''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''']
# fmt: on
SCREAMING_SNAKE_CASE__ : str = dict(zip(_lowercase , range(len(_lowercase ) ) ) )
SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp:
fp.write(json.dumps(_lowercase ) + '''\n''' )
def lowercase__ ( self : Any , **_lowercase : List[Any] ):
return MgpstrTokenizer.from_pretrained(self.tmpdirname , **_lowercase )
def lowercase__ ( self : int , _lowercase : List[str] ):
SCREAMING_SNAKE_CASE__ : Tuple = '''tester'''
SCREAMING_SNAKE_CASE__ : Union[str, Any] = '''tester'''
return input_text, output_text
@unittest.skip('''MGP-STR always lower cases letters.''' )
def lowercase__ ( self : Dict ):
pass
def lowercase__ ( self : str ):
SCREAMING_SNAKE_CASE__ : Dict = self.get_tokenizers(do_lower_case=_lowercase )
for tokenizer in tokenizers:
with self.subTest(f"""{tokenizer.__class__.__name__}""" ):
SCREAMING_SNAKE_CASE__ : List[str] = '''[SPECIAL_TOKEN]'''
tokenizer.add_special_tokens({'''cls_token''': special_token} )
SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.encode([special_token] , add_special_tokens=_lowercase )
self.assertEqual(len(_lowercase ) , 1 )
SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.decode(_lowercase , skip_special_tokens=_lowercase )
self.assertTrue(special_token not in decoded )
def lowercase__ ( self : Dict ):
SCREAMING_SNAKE_CASE__ : List[Any] = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(f"""{tokenizer.__class__.__name__}""" ):
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_input_output_texts(_lowercase )
SCREAMING_SNAKE_CASE__ : Any = tokenizer.tokenize(_lowercase )
SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.convert_tokens_to_ids(_lowercase )
SCREAMING_SNAKE_CASE__ : str = tokenizer.encode(_lowercase , add_special_tokens=_lowercase )
self.assertListEqual(_lowercase , _lowercase )
SCREAMING_SNAKE_CASE__ : int = tokenizer.convert_ids_to_tokens(_lowercase )
self.assertNotEqual(len(_lowercase ) , 0 )
SCREAMING_SNAKE_CASE__ : str = tokenizer.decode(_lowercase )
self.assertIsInstance(_lowercase , _lowercase )
self.assertEqual(text_a.replace(''' ''' , '''''' ) , _lowercase )
@unittest.skip('''MGP-STR tokenizer only handles one sequence.''' )
def lowercase__ ( self : Optional[int] ):
pass
@unittest.skip('''inputs cannot be pretokenized in MgpstrTokenizer''' )
def lowercase__ ( self : int ):
pass
| 35 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_torch_available,
is_vision_available,
)
A = {'configuration_vit': ['VIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTConfig', 'ViTOnnxConfig']}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A = ['ViTFeatureExtractor']
A = ['ViTImageProcessor']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A = [
'VIT_PRETRAINED_MODEL_ARCHIVE_LIST',
'ViTForImageClassification',
'ViTForMaskedImageModeling',
'ViTModel',
'ViTPreTrainedModel',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A = [
'TFViTForImageClassification',
'TFViTModel',
'TFViTPreTrainedModel',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A = [
'FlaxViTForImageClassification',
'FlaxViTModel',
'FlaxViTPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_vit import ViTFeatureExtractor
from .image_processing_vit import ViTImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_vit import (
VIT_PRETRAINED_MODEL_ARCHIVE_LIST,
ViTForImageClassification,
ViTForMaskedImageModeling,
ViTModel,
ViTPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel
else:
import sys
A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 449 | 0 |
import itertools
import os
import random
import tempfile
import unittest
import numpy as np
from transformers import TvltFeatureExtractor, is_datasets_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available
from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin
if is_torch_available():
import torch
if is_datasets_available():
from datasets import load_dataset
__lowerCamelCase = random.Random()
def _snake_case ( __snake_case , __snake_case=1.0 , __snake_case=None , __snake_case=None ) -> Optional[Any]:
'''simple docstring'''
if rng is None:
UpperCAmelCase_ : List[Any] = global_rng
UpperCAmelCase_ : str = []
for batch_idx in range(shape[0] ):
values.append([] )
for _ in range(shape[1] ):
values[-1].append(rng.random() * scale )
return values
class snake_case_ (unittest.TestCase ):
"""simple docstring"""
def __init__( self ,lowercase ,lowercase=7 ,lowercase=400 ,lowercase=2000 ,lowercase=2048 ,lowercase=128 ,lowercase=1 ,lowercase=512 ,lowercase=30 ,lowercase=44100 ,):
"""simple docstring"""
UpperCAmelCase_ : Optional[int] = parent
UpperCAmelCase_ : List[Any] = batch_size
UpperCAmelCase_ : Dict = min_seq_length
UpperCAmelCase_ : Optional[Any] = max_seq_length
UpperCAmelCase_ : Union[str, Any] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
UpperCAmelCase_ : str = spectrogram_length
UpperCAmelCase_ : Optional[int] = feature_size
UpperCAmelCase_ : Optional[int] = num_audio_channels
UpperCAmelCase_ : List[str] = hop_length
UpperCAmelCase_ : Tuple = chunk_length
UpperCAmelCase_ : Any = sampling_rate
def A_ ( self):
"""simple docstring"""
return {
"spectrogram_length": self.spectrogram_length,
"feature_size": self.feature_size,
"num_audio_channels": self.num_audio_channels,
"hop_length": self.hop_length,
"chunk_length": self.chunk_length,
"sampling_rate": self.sampling_rate,
}
def A_ ( self ,lowercase=False ,lowercase=False):
"""simple docstring"""
def _flatten(lowercase):
return list(itertools.chain(*lowercase))
if equal_length:
UpperCAmelCase_ : Tuple = [floats_list((self.max_seq_length, self.feature_size)) for _ in range(self.batch_size)]
else:
# make sure that inputs increase in size
UpperCAmelCase_ : List[str] = [
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_ : Optional[int] = [np.asarray(lowercase) for x in speech_inputs]
return speech_inputs
@require_torch
@require_torchaudio
class snake_case_ (lowercase__ , unittest.TestCase ):
"""simple docstring"""
_lowerCamelCase = TvltFeatureExtractor
def A_ ( self):
"""simple docstring"""
UpperCAmelCase_ : List[str] = TvltFeatureExtractionTester(self)
def A_ ( self):
"""simple docstring"""
UpperCAmelCase_ : Any = self.feature_extraction_class(**self.feat_extract_dict)
self.assertTrue(hasattr(lowercase ,"spectrogram_length"))
self.assertTrue(hasattr(lowercase ,"feature_size"))
self.assertTrue(hasattr(lowercase ,"num_audio_channels"))
self.assertTrue(hasattr(lowercase ,"hop_length"))
self.assertTrue(hasattr(lowercase ,"chunk_length"))
self.assertTrue(hasattr(lowercase ,"sampling_rate"))
def A_ ( self):
"""simple docstring"""
UpperCAmelCase_ : Dict = self.feature_extraction_class(**self.feat_extract_dict)
with tempfile.TemporaryDirectory() as tmpdirname:
UpperCAmelCase_ : List[str] = feat_extract_first.save_pretrained(lowercase)[0]
check_json_file_has_correct_format(lowercase)
UpperCAmelCase_ : int = self.feature_extraction_class.from_pretrained(lowercase)
UpperCAmelCase_ : Optional[Any] = feat_extract_first.to_dict()
UpperCAmelCase_ : Tuple = feat_extract_second.to_dict()
UpperCAmelCase_ : Union[str, Any] = dict_first.pop("mel_filters")
UpperCAmelCase_ : Optional[Any] = dict_second.pop("mel_filters")
self.assertTrue(np.allclose(lowercase ,lowercase))
self.assertEqual(lowercase ,lowercase)
def A_ ( self):
"""simple docstring"""
UpperCAmelCase_ : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict)
with tempfile.TemporaryDirectory() as tmpdirname:
UpperCAmelCase_ : Union[str, Any] = os.path.join(lowercase ,"feat_extract.json")
feat_extract_first.to_json_file(lowercase)
UpperCAmelCase_ : Any = self.feature_extraction_class.from_json_file(lowercase)
UpperCAmelCase_ : Optional[int] = feat_extract_first.to_dict()
UpperCAmelCase_ : Dict = feat_extract_second.to_dict()
UpperCAmelCase_ : Union[str, Any] = dict_first.pop("mel_filters")
UpperCAmelCase_ : Dict = dict_second.pop("mel_filters")
self.assertTrue(np.allclose(lowercase ,lowercase))
self.assertEqual(lowercase ,lowercase)
def A_ ( self):
"""simple docstring"""
UpperCAmelCase_ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict)
# create three inputs of length 800, 1000, and 1200
UpperCAmelCase_ : Optional[Any] = [floats_list((1, x))[0] for x in range(800 ,1400 ,200)]
UpperCAmelCase_ : str = [np.asarray(lowercase) for speech_input in speech_inputs]
# Test not batched input
UpperCAmelCase_ : List[str] = feature_extractor(np_speech_inputs[0] ,return_tensors="np" ,sampling_rate=44100).audio_values
self.assertTrue(encoded_audios.ndim == 4)
self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size)
self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length)
self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels)
# Test batched
UpperCAmelCase_ : List[Any] = feature_extractor(lowercase ,return_tensors="np" ,sampling_rate=44100).audio_values
self.assertTrue(encoded_audios.ndim == 4)
self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size)
self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length)
self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels)
# Test audio masking
UpperCAmelCase_ : List[Any] = feature_extractor(
lowercase ,return_tensors="np" ,sampling_rate=44100 ,mask_audio=lowercase).audio_values
self.assertTrue(encoded_audios.ndim == 4)
self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size)
self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length)
self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels)
# Test 2-D numpy arrays are batched.
UpperCAmelCase_ : Dict = [floats_list((1, x))[0] for x in (800, 800, 800)]
UpperCAmelCase_ : Dict = np.asarray(lowercase)
UpperCAmelCase_ : Any = feature_extractor(lowercase ,return_tensors="np" ,sampling_rate=44100).audio_values
self.assertTrue(encoded_audios.ndim == 4)
self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size)
self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length)
self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels)
def A_ ( self ,lowercase):
"""simple docstring"""
UpperCAmelCase_ : List[str] = load_dataset("hf-internal-testing/librispeech_asr_dummy" ,"clean" ,split="validation")
# automatic decoding with librispeech
UpperCAmelCase_ : Any = ds.sort("id").select(range(lowercase))[:num_samples]["audio"]
return [x["array"] for x in speech_samples]
def A_ ( self):
"""simple docstring"""
UpperCAmelCase_ : str = self._load_datasamples(1)
UpperCAmelCase_ : List[str] = TvltFeatureExtractor()
UpperCAmelCase_ : Optional[int] = feature_extractor(lowercase ,return_tensors="pt").audio_values
self.assertEquals(audio_values.shape ,(1, 1, 192, 128))
UpperCAmelCase_ : int = torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]])
self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] ,lowercase ,atol=1E-4))
| 455 |
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class snake_case_ (lowercase__ ):
"""simple docstring"""
_lowerCamelCase = """ClapFeatureExtractor"""
_lowerCamelCase = ("""RobertaTokenizer""", """RobertaTokenizerFast""")
def __init__( self ,lowercase ,lowercase):
"""simple docstring"""
super().__init__(lowercase ,lowercase)
def __call__( self ,lowercase=None ,lowercase=None ,lowercase=None ,**lowercase):
"""simple docstring"""
UpperCAmelCase_ : Dict = kwargs.pop("sampling_rate" ,lowercase)
if text is None and audios is None:
raise ValueError("You have to specify either text or audios. Both cannot be none.")
if text is not None:
UpperCAmelCase_ : List[str] = self.tokenizer(lowercase ,return_tensors=lowercase ,**lowercase)
if audios is not None:
UpperCAmelCase_ : str = self.feature_extractor(
lowercase ,sampling_rate=lowercase ,return_tensors=lowercase ,**lowercase)
if text is not None and audios is not None:
UpperCAmelCase_ : Optional[int] = audio_features.input_features
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**lowercase) ,tensor_type=lowercase)
def A_ ( self ,*lowercase ,**lowercase):
"""simple docstring"""
return self.tokenizer.batch_decode(*lowercase ,**lowercase)
def A_ ( self ,*lowercase ,**lowercase):
"""simple docstring"""
return self.tokenizer.decode(*lowercase ,**lowercase)
@property
def A_ ( self):
"""simple docstring"""
UpperCAmelCase_ : str = self.tokenizer.model_input_names
UpperCAmelCase_ : str = self.feature_extractor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names))
| 455 | 1 |
"""simple docstring"""
def _lowerCAmelCase ( UpperCamelCase_ ):
__SCREAMING_SNAKE_CASE = abs(__lowerCamelCase )
__SCREAMING_SNAKE_CASE = 0
while n > 0:
res += n % 10
n //= 10
return res
def _lowerCAmelCase ( UpperCamelCase_ ):
__SCREAMING_SNAKE_CASE = abs(__lowerCamelCase )
return n if n < 10 else n % 10 + sum_of_digits(n // 10 )
def _lowerCAmelCase ( UpperCamelCase_ ):
return sum(int(__lowerCamelCase ) for c in str(abs(__lowerCamelCase ) ) )
def _lowerCAmelCase ( ):
from collections.abc import Callable
from timeit import timeit
def benchmark_a_function(UpperCamelCase_ , UpperCamelCase_ ) -> None:
__SCREAMING_SNAKE_CASE = f"{func.__name__}({value})"
__SCREAMING_SNAKE_CASE = timeit(f"__main__.{call}" , setup="""import __main__""" )
print(f"{call:56} = {func(__lowerCamelCase )} -- {timing:.4f} seconds" )
for value in (26_2144, 1125_8999_0684_2624, 126_7650_6002_2822_9401_4967_0320_5376):
for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact):
benchmark_a_function(__lowerCamelCase , __lowerCamelCase )
print()
if __name__ == "__main__":
import doctest
doctest.testmod()
benchmark()
| 155 |
from typing import TYPE_CHECKING
# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
_snake_case : Any = {
"configuration_informer": [
"INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP",
"InformerConfig",
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_snake_case : int = [
"INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
"InformerForPrediction",
"InformerModel",
"InformerPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_informer import (
INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
InformerForPrediction,
InformerModel,
InformerPreTrainedModel,
)
else:
import sys
_snake_case : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 81 | 0 |
from __future__ import annotations
import copy
import tempfile
import unittest
from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available
from transformers.testing_utils import (
DUMMY_UNKNOWN_IDENTIFIER,
SMALL_MODEL_IDENTIFIER,
RequestCounter,
require_tensorflow_probability,
require_tf,
slow,
)
from ..bert.test_modeling_bert import BertModelTester
if is_tf_available():
from transformers import (
TFAutoModel,
TFAutoModelForCausalLM,
TFAutoModelForMaskedLM,
TFAutoModelForPreTraining,
TFAutoModelForQuestionAnswering,
TFAutoModelForSeqaSeqLM,
TFAutoModelForSequenceClassification,
TFAutoModelForTableQuestionAnswering,
TFAutoModelForTokenClassification,
TFAutoModelWithLMHead,
TFBertForMaskedLM,
TFBertForPreTraining,
TFBertForQuestionAnswering,
TFBertForSequenceClassification,
TFBertModel,
TFFunnelBaseModel,
TFFunnelModel,
TFGPTaLMHeadModel,
TFRobertaForMaskedLM,
TFTaForConditionalGeneration,
TFTapasForQuestionAnswering,
)
from transformers.models.auto.modeling_tf_auto import (
TF_MODEL_FOR_CAUSAL_LM_MAPPING,
TF_MODEL_FOR_MASKED_LM_MAPPING,
TF_MODEL_FOR_PRETRAINING_MAPPING,
TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
TF_MODEL_MAPPING,
)
from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST
from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST
from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST
from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST
class A_ ( __lowerCamelCase ):
'''simple docstring'''
_UpperCamelCase : Dict = """new-model"""
if is_tf_available():
class A_ ( __lowerCamelCase ):
'''simple docstring'''
_UpperCamelCase : Any = NewModelConfig
@require_tf
class A_ ( unittest.TestCase ):
'''simple docstring'''
@slow
def SCREAMING_SNAKE_CASE__ ( self ):
lowercase = 'bert-base-cased'
lowercase = AutoConfig.from_pretrained(snake_case )
self.assertIsNotNone(snake_case )
self.assertIsInstance(snake_case , snake_case )
lowercase = TFAutoModel.from_pretrained(snake_case )
self.assertIsNotNone(snake_case )
self.assertIsInstance(snake_case , snake_case )
@slow
def SCREAMING_SNAKE_CASE__ ( self ):
lowercase = 'bert-base-cased'
lowercase = AutoConfig.from_pretrained(snake_case )
self.assertIsNotNone(snake_case )
self.assertIsInstance(snake_case , snake_case )
lowercase = TFAutoModelForPreTraining.from_pretrained(snake_case )
self.assertIsNotNone(snake_case )
self.assertIsInstance(snake_case , snake_case )
@slow
def SCREAMING_SNAKE_CASE__ ( self ):
for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowercase = AutoConfig.from_pretrained(snake_case )
self.assertIsNotNone(snake_case )
self.assertIsInstance(snake_case , snake_case )
lowercase = TFAutoModelForCausalLM.from_pretrained(snake_case )
lowercase , lowercase = TFAutoModelForCausalLM.from_pretrained(snake_case , output_loading_info=snake_case )
self.assertIsNotNone(snake_case )
self.assertIsInstance(snake_case , snake_case )
@slow
def SCREAMING_SNAKE_CASE__ ( self ):
for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowercase = AutoConfig.from_pretrained(snake_case )
self.assertIsNotNone(snake_case )
self.assertIsInstance(snake_case , snake_case )
lowercase = TFAutoModelWithLMHead.from_pretrained(snake_case )
self.assertIsNotNone(snake_case )
self.assertIsInstance(snake_case , snake_case )
@slow
def SCREAMING_SNAKE_CASE__ ( self ):
for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowercase = AutoConfig.from_pretrained(snake_case )
self.assertIsNotNone(snake_case )
self.assertIsInstance(snake_case , snake_case )
lowercase = TFAutoModelForMaskedLM.from_pretrained(snake_case )
lowercase , lowercase = TFAutoModelForMaskedLM.from_pretrained(snake_case , output_loading_info=snake_case )
self.assertIsNotNone(snake_case )
self.assertIsInstance(snake_case , snake_case )
@slow
def SCREAMING_SNAKE_CASE__ ( self ):
for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowercase = AutoConfig.from_pretrained(snake_case )
self.assertIsNotNone(snake_case )
self.assertIsInstance(snake_case , snake_case )
lowercase = TFAutoModelForSeqaSeqLM.from_pretrained(snake_case )
lowercase , lowercase = TFAutoModelForSeqaSeqLM.from_pretrained(snake_case , output_loading_info=snake_case )
self.assertIsNotNone(snake_case )
self.assertIsInstance(snake_case , snake_case )
@slow
def SCREAMING_SNAKE_CASE__ ( self ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
lowercase = AutoConfig.from_pretrained(snake_case )
self.assertIsNotNone(snake_case )
self.assertIsInstance(snake_case , snake_case )
lowercase = TFAutoModelForSequenceClassification.from_pretrained(snake_case )
self.assertIsNotNone(snake_case )
self.assertIsInstance(snake_case , snake_case )
@slow
def SCREAMING_SNAKE_CASE__ ( self ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
lowercase = AutoConfig.from_pretrained(snake_case )
self.assertIsNotNone(snake_case )
self.assertIsInstance(snake_case , snake_case )
lowercase = TFAutoModelForQuestionAnswering.from_pretrained(snake_case )
self.assertIsNotNone(snake_case )
self.assertIsInstance(snake_case , snake_case )
@slow
@require_tensorflow_probability
def SCREAMING_SNAKE_CASE__ ( self ):
for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]:
lowercase = AutoConfig.from_pretrained(snake_case )
self.assertIsNotNone(snake_case )
self.assertIsInstance(snake_case , snake_case )
lowercase = TFAutoModelForTableQuestionAnswering.from_pretrained(snake_case )
lowercase , lowercase = TFAutoModelForTableQuestionAnswering.from_pretrained(
snake_case , output_loading_info=snake_case )
self.assertIsNotNone(snake_case )
self.assertIsInstance(snake_case , snake_case )
def SCREAMING_SNAKE_CASE__ ( self ):
lowercase = TFAutoModelWithLMHead.from_pretrained(snake_case )
self.assertIsInstance(snake_case , snake_case )
self.assertEqual(model.num_parameters() , 1_4410 )
self.assertEqual(model.num_parameters(only_trainable=snake_case ) , 1_4410 )
def SCREAMING_SNAKE_CASE__ ( self ):
lowercase = TFAutoModelWithLMHead.from_pretrained(snake_case )
self.assertIsInstance(snake_case , snake_case )
self.assertEqual(model.num_parameters() , 1_4410 )
self.assertEqual(model.num_parameters(only_trainable=snake_case ) , 1_4410 )
def SCREAMING_SNAKE_CASE__ ( self ):
# For the auto model mapping, FunnelConfig has two models: FunnelModel and FunnelBaseModel
lowercase = TFAutoModel.from_pretrained('sgugger/funnel-random-tiny' )
self.assertIsInstance(snake_case , snake_case )
lowercase = copy.deepcopy(model.config )
lowercase = ['FunnelBaseModel']
lowercase = TFAutoModel.from_config(snake_case )
self.assertIsInstance(snake_case , snake_case )
with tempfile.TemporaryDirectory() as tmp_dir:
model.save_pretrained(snake_case )
lowercase = TFAutoModel.from_pretrained(snake_case )
self.assertIsInstance(snake_case , snake_case )
def SCREAMING_SNAKE_CASE__ ( self ):
try:
AutoConfig.register('new-model' , snake_case )
lowercase = [
TFAutoModel,
TFAutoModelForCausalLM,
TFAutoModelForMaskedLM,
TFAutoModelForPreTraining,
TFAutoModelForQuestionAnswering,
TFAutoModelForSequenceClassification,
TFAutoModelForTokenClassification,
]
for auto_class in auto_classes:
with self.subTest(auto_class.__name__ ):
# Wrong config class will raise an error
with self.assertRaises(snake_case ):
auto_class.register(snake_case , snake_case )
auto_class.register(snake_case , snake_case )
# Trying to register something existing in the Transformers library will raise an error
with self.assertRaises(snake_case ):
auto_class.register(snake_case , snake_case )
# Now that the config is registered, it can be used as any other config with the auto-API
lowercase = BertModelTester(self ).get_config()
lowercase = NewModelConfig(**tiny_config.to_dict() )
lowercase = auto_class.from_config(snake_case )
self.assertIsInstance(snake_case , snake_case )
with tempfile.TemporaryDirectory() as tmp_dir:
model.save_pretrained(snake_case )
lowercase = auto_class.from_pretrained(snake_case )
self.assertIsInstance(snake_case , snake_case )
finally:
if "new-model" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["new-model"]
for mapping in (
TF_MODEL_MAPPING,
TF_MODEL_FOR_PRETRAINING_MAPPING,
TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
TF_MODEL_FOR_CAUSAL_LM_MAPPING,
TF_MODEL_FOR_MASKED_LM_MAPPING,
):
if NewModelConfig in mapping._extra_content:
del mapping._extra_content[NewModelConfig]
def SCREAMING_SNAKE_CASE__ ( self ):
with self.assertRaisesRegex(
snake_case , 'bert-base is not a local folder and is not a valid model identifier' ):
lowercase = TFAutoModel.from_pretrained('bert-base' )
def SCREAMING_SNAKE_CASE__ ( self ):
with self.assertRaisesRegex(
snake_case , r'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)' ):
lowercase = TFAutoModel.from_pretrained(snake_case , revision='aaaaaa' )
def SCREAMING_SNAKE_CASE__ ( self ):
with self.assertRaisesRegex(
snake_case , 'hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin' , ):
lowercase = TFAutoModel.from_pretrained('hf-internal-testing/config-no-model' )
def SCREAMING_SNAKE_CASE__ ( self ):
with self.assertRaisesRegex(snake_case , 'Use `from_pt=True` to load this model' ):
lowercase = TFAutoModel.from_pretrained('hf-internal-testing/tiny-bert-pt-only' )
def SCREAMING_SNAKE_CASE__ ( self ):
# Make sure we have cached the model.
lowercase = TFAutoModel.from_pretrained('hf-internal-testing/tiny-random-bert' )
with RequestCounter() as counter:
lowercase = TFAutoModel.from_pretrained('hf-internal-testing/tiny-random-bert' )
self.assertEqual(counter.get_request_count , 0 )
self.assertEqual(counter.head_request_count , 1 )
self.assertEqual(counter.other_request_count , 0 )
# With a sharded checkpoint
lowercase = TFAutoModel.from_pretrained('ArthurZ/tiny-random-bert-sharded' )
with RequestCounter() as counter:
lowercase = TFAutoModel.from_pretrained('ArthurZ/tiny-random-bert-sharded' )
self.assertEqual(counter.get_request_count , 0 )
self.assertEqual(counter.head_request_count , 1 )
self.assertEqual(counter.other_request_count , 0 )
| 565 |
import os
import re
import warnings
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
if TYPE_CHECKING:
from ...tokenization_utils_base import TextInput
from ...utils import logging
UpperCAmelCase = logging.get_logger(__name__)
UpperCAmelCase = {'''vocab_file''': '''spiece.model'''}
UpperCAmelCase = {
'''vocab_file''': {
'''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''',
'''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''',
'''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''',
'''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''',
'''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''',
}
}
# TODO(PVP) - this should be removed in Transformers v5
UpperCAmelCase = {
'''t5-small''': 512,
'''t5-base''': 512,
'''t5-large''': 512,
'''t5-3b''': 512,
'''t5-11b''': 512,
}
UpperCAmelCase = '''▁'''
class A_ ( __lowerCamelCase ):
'''simple docstring'''
_UpperCamelCase : List[Any] = VOCAB_FILES_NAMES
_UpperCamelCase : int = PRETRAINED_VOCAB_FILES_MAP
_UpperCamelCase : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_UpperCamelCase : List[str] = ["""input_ids""", """attention_mask"""]
def __init__( self , snake_case , snake_case="</s>" , snake_case="<unk>" , snake_case="<pad>" , snake_case=100 , snake_case=None , snake_case = None , snake_case=True , **snake_case , ):
# Add extra_ids to the special token list
if extra_ids > 0 and additional_special_tokens is None:
lowercase = [F'''<extra_id_{i}>''' for i in range(snake_case )]
elif extra_ids > 0 and additional_special_tokens is not None:
# Check that we have the right number of extra_id special tokens
lowercase = len(set(filter(lambda snake_case : bool('extra_id' in str(snake_case ) ) , snake_case ) ) )
if extra_tokens != extra_ids:
raise ValueError(
F'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are'''
' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids'
' tokens' )
if legacy:
logger.warning_once(
F'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to'''
' read the related pull request available at https://github.com/huggingface/transformers/pull/24565' )
lowercase = legacy
lowercase = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
eos_token=snake_case , unk_token=snake_case , pad_token=snake_case , extra_ids=snake_case , additional_special_tokens=snake_case , sp_model_kwargs=self.sp_model_kwargs , legacy=snake_case , **snake_case , )
lowercase = vocab_file
lowercase = extra_ids
lowercase = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(snake_case )
@staticmethod
def SCREAMING_SNAKE_CASE__ ( snake_case , snake_case , snake_case ):
if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes:
lowercase = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path]
if init_max_model_length is not None and init_max_model_length != max_model_length:
return init_max_model_length
elif init_max_model_length is None:
warnings.warn(
'This tokenizer was incorrectly instantiated with a model max length of'
F''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this'''
' behavior is kept to avoid breaking backwards compatibility when padding/encoding with'
' `truncation is True`.\n- Be aware that you SHOULD NOT rely on'
F''' {pretrained_model_name_or_path} automatically truncating your input to'''
F''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences'''
F''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with'''
' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please'
' instantiate this tokenizer with `model_max_length` set to your preferred value.' , snake_case , )
return max_model_length
@property
def SCREAMING_SNAKE_CASE__ ( self ):
return self.sp_model.get_piece_size() + self._extra_ids
def SCREAMING_SNAKE_CASE__ ( self ):
lowercase = {self.convert_ids_to_tokens(snake_case ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case = None , snake_case = False ):
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=snake_case , token_ids_a=snake_case , already_has_special_tokens=snake_case )
# normal case: some special tokens
if token_ids_a is None:
return ([0] * len(snake_case )) + [1]
return ([0] * len(snake_case )) + [1] + ([0] * len(snake_case )) + [1]
def SCREAMING_SNAKE_CASE__ ( self ):
return list(
set(filter(lambda snake_case : bool(re.search(r'<extra_id_\d+>' , snake_case ) ) is not None , self.additional_special_tokens ) ) )
def SCREAMING_SNAKE_CASE__ ( self ):
return [self._convert_token_to_id(snake_case ) for token in self.get_sentinel_tokens()]
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
if len(snake_case ) > 0 and token_ids[-1] == self.eos_token_id:
warnings.warn(
F'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated'''
' eos tokens being added.' )
return token_ids
else:
return token_ids + [self.eos_token_id]
def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case = None ):
lowercase = [self.eos_token_id]
if token_ids_a is None:
return len(token_ids_a + eos ) * [0]
return len(token_ids_a + eos + token_ids_a + eos ) * [0]
def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case = None ):
lowercase = self._add_eos_if_not_present(snake_case )
if token_ids_a is None:
return token_ids_a
else:
lowercase = self._add_eos_if_not_present(snake_case )
return token_ids_a + token_ids_a
def __getstate__( self ):
lowercase = self.__dict__.copy()
lowercase = None
return state
def __setstate__( self , snake_case ):
lowercase = d
# for backward compatibility
if not hasattr(self , 'sp_model_kwargs' ):
lowercase = {}
lowercase = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def SCREAMING_SNAKE_CASE__ ( self , snake_case , **snake_case ):
# Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at
# the beginning of the text
if not self.legacy:
lowercase = SPIECE_UNDERLINE + text.replace(snake_case , ' ' )
return super().tokenize(snake_case , **snake_case )
def SCREAMING_SNAKE_CASE__ ( self , snake_case , **snake_case ):
if not self.legacy:
lowercase = text.startswith(snake_case )
if is_first:
lowercase = text[1:]
lowercase = self.sp_model.encode(snake_case , out_type=snake_case )
if not self.legacy and not is_first and not text.startswith(' ' ) and tokens[0].startswith(snake_case ):
lowercase = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:]
return tokens
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
if token.startswith('<extra_id_' ):
lowercase = re.match(r'<extra_id_(\d+)>' , snake_case )
lowercase = int(match.group(1 ) )
return self.vocab_size - num - 1
return self.sp_model.piece_to_id(snake_case )
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
if index < self.sp_model.get_piece_size():
lowercase = self.sp_model.IdToPiece(snake_case )
else:
lowercase = F'''<extra_id_{self.vocab_size - 1 - index}>'''
return token
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
lowercase = []
lowercase = ''
lowercase = 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(snake_case ) + token
lowercase = True
lowercase = []
else:
current_sub_tokens.append(snake_case )
lowercase = False
out_string += self.sp_model.decode(snake_case )
return out_string.strip()
def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case = None ):
if not os.path.isdir(snake_case ):
logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' )
return
lowercase = os.path.join(
snake_case , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , snake_case )
elif not os.path.isfile(self.vocab_file ):
with open(snake_case , 'wb' ) as fi:
lowercase = self.sp_model.serialized_model_proto()
fi.write(snake_case )
return (out_vocab_file,)
| 565 | 1 |
import argparse
import torch
from transformers import (
UniSpeechSatConfig,
UniSpeechSatForAudioFrameClassification,
UniSpeechSatForSequenceClassification,
UniSpeechSatForXVector,
WavaVecaFeatureExtractor,
logging,
)
logging.set_verbosity_info()
lowerCAmelCase__ : Optional[Any] =logging.get_logger(__name__)
def __lowercase ( a__ , a__ , a__ ) -> Dict:
__SCREAMING_SNAKE_CASE = UniSpeechSatForSequenceClassification.from_pretrained(a__ , config=a__ )
__SCREAMING_SNAKE_CASE = downstream_dict['projector.weight']
__SCREAMING_SNAKE_CASE = downstream_dict['projector.bias']
__SCREAMING_SNAKE_CASE = downstream_dict['model.post_net.linear.weight']
__SCREAMING_SNAKE_CASE = downstream_dict['model.post_net.linear.bias']
return model
def __lowercase ( a__ , a__ , a__ ) -> str:
__SCREAMING_SNAKE_CASE = UniSpeechSatForAudioFrameClassification.from_pretrained(a__ , config=a__ )
__SCREAMING_SNAKE_CASE = downstream_dict['model.linear.weight']
__SCREAMING_SNAKE_CASE = downstream_dict['model.linear.bias']
return model
def __lowercase ( a__ , a__ , a__ ) -> Union[str, Any]:
__SCREAMING_SNAKE_CASE = UniSpeechSatForXVector.from_pretrained(a__ , config=a__ )
__SCREAMING_SNAKE_CASE = downstream_dict['connector.weight']
__SCREAMING_SNAKE_CASE = downstream_dict['connector.bias']
for i, kernel_size in enumerate(hf_config.tdnn_kernel ):
__SCREAMING_SNAKE_CASE = downstream_dict[
f"""model.framelevel_feature_extractor.module.{i}.kernel.weight"""
]
__SCREAMING_SNAKE_CASE = downstream_dict[f"""model.framelevel_feature_extractor.module.{i}.kernel.bias"""]
__SCREAMING_SNAKE_CASE = downstream_dict['model.utterancelevel_feature_extractor.linear1.weight']
__SCREAMING_SNAKE_CASE = downstream_dict['model.utterancelevel_feature_extractor.linear1.bias']
__SCREAMING_SNAKE_CASE = downstream_dict['model.utterancelevel_feature_extractor.linear2.weight']
__SCREAMING_SNAKE_CASE = downstream_dict['model.utterancelevel_feature_extractor.linear2.bias']
__SCREAMING_SNAKE_CASE = downstream_dict['objective.W']
return model
@torch.no_grad()
def __lowercase ( a__ , a__ , a__ , a__ ) -> Tuple:
__SCREAMING_SNAKE_CASE = torch.load(a__ , map_location='cpu' )
__SCREAMING_SNAKE_CASE = checkpoint['Downstream']
__SCREAMING_SNAKE_CASE = UniSpeechSatConfig.from_pretrained(a__ )
__SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained(
a__ , return_attention_mask=a__ , do_normalize=a__ )
__SCREAMING_SNAKE_CASE = hf_config.architectures[0]
if arch.endswith('ForSequenceClassification' ):
__SCREAMING_SNAKE_CASE = convert_classification(a__ , a__ , a__ )
elif arch.endswith('ForAudioFrameClassification' ):
__SCREAMING_SNAKE_CASE = convert_diarization(a__ , a__ , a__ )
elif arch.endswith('ForXVector' ):
__SCREAMING_SNAKE_CASE = convert_xvector(a__ , a__ , a__ )
else:
raise NotImplementedError(f"""S3PRL weights conversion is not supported for {arch}""" )
if hf_config.use_weighted_layer_sum:
__SCREAMING_SNAKE_CASE = checkpoint['Featurizer']['weights']
hf_feature_extractor.save_pretrained(a__ )
hf_model.save_pretrained(a__ )
if __name__ == "__main__":
lowerCAmelCase__ : Optional[Any] =argparse.ArgumentParser()
parser.add_argument(
'''--base_model_name''', default=None, type=str, help='''Name of the huggingface pretrained base model.'''
)
parser.add_argument('''--config_path''', default=None, type=str, help='''Path to the huggingface classifier config.''')
parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to the s3prl checkpoint.''')
parser.add_argument('''--model_dump_path''', default=None, type=str, help='''Path to the final converted model.''')
lowerCAmelCase__ : Any =parser.parse_args()
convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
| 148 |
import numpy as np
def __lowercase ( a__ , a__ , a__ = 1E-12 , a__ = 1_00 , ) -> tuple[float, np.ndarray]:
assert np.shape(a__ )[0] == np.shape(a__ )[1]
# Ensure proper dimensionality.
assert np.shape(a__ )[0] == np.shape(a__ )[0]
# Ensure inputs are either both complex or both real
assert np.iscomplexobj(a__ ) == np.iscomplexobj(a__ )
__SCREAMING_SNAKE_CASE = np.iscomplexobj(a__ )
if is_complex:
# Ensure complex input_matrix is Hermitian
assert np.array_equal(a__ , input_matrix.conj().T )
# Set convergence to False. Will define convergence when we exceed max_iterations
# or when we have small changes from one iteration to next.
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = 0
__SCREAMING_SNAKE_CASE = 0
__SCREAMING_SNAKE_CASE = 1E12
while not convergence:
# Multiple matrix by the vector.
__SCREAMING_SNAKE_CASE = np.dot(a__ , a__ )
# Normalize the resulting output vector.
__SCREAMING_SNAKE_CASE = w / np.linalg.norm(a__ )
# Find rayleigh quotient
# (faster than usual b/c we know vector is normalized already)
__SCREAMING_SNAKE_CASE = vector.conj().T if is_complex else vector.T
__SCREAMING_SNAKE_CASE = np.dot(a__ , np.dot(a__ , a__ ) )
# Check convergence.
__SCREAMING_SNAKE_CASE = np.abs(lambda_ - lambda_previous ) / lambda_
iterations += 1
if error <= error_tol or iterations >= max_iterations:
__SCREAMING_SNAKE_CASE = True
__SCREAMING_SNAKE_CASE = lambda_
if is_complex:
__SCREAMING_SNAKE_CASE = np.real(lambda_ )
return lambda_, vector
def __lowercase ( ) -> None:
__SCREAMING_SNAKE_CASE = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] )
__SCREAMING_SNAKE_CASE = np.array([41, 4, 20] )
__SCREAMING_SNAKE_CASE = real_input_matrix.astype(np.complexaaa )
__SCREAMING_SNAKE_CASE = np.triu(1J * complex_input_matrix , 1 )
complex_input_matrix += imag_matrix
complex_input_matrix += -1 * imag_matrix.T
__SCREAMING_SNAKE_CASE = np.array([41, 4, 20] ).astype(np.complexaaa )
for problem_type in ["real", "complex"]:
if problem_type == "real":
__SCREAMING_SNAKE_CASE = real_input_matrix
__SCREAMING_SNAKE_CASE = real_vector
elif problem_type == "complex":
__SCREAMING_SNAKE_CASE = complex_input_matrix
__SCREAMING_SNAKE_CASE = complex_vector
# Our implementation.
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = power_iteration(a__ , a__ )
# Numpy implementation.
# Get eigenvalues and eigenvectors using built-in numpy
# eigh (eigh used for symmetric or hermetian matrices).
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = np.linalg.eigh(a__ )
# Last eigenvalue is the maximum one.
__SCREAMING_SNAKE_CASE = eigen_values[-1]
# Last column in this matrix is eigenvector corresponding to largest eigenvalue.
__SCREAMING_SNAKE_CASE = eigen_vectors[:, -1]
# Check our implementation and numpy gives close answers.
assert np.abs(eigen_value - eigen_value_max ) <= 1E-6
# Take absolute values element wise of each eigenvector.
# as they are only unique to a minus sign.
assert np.linalg.norm(np.abs(a__ ) - np.abs(a__ ) ) <= 1E-6
if __name__ == "__main__":
import doctest
doctest.testmod()
test_power_iteration()
| 148 | 1 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_torch_available,
)
lowerCAmelCase__ = {"configuration_encoder_decoder": ["EncoderDecoderConfig"]}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase__ = ["EncoderDecoderModel"]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase__ = ["TFEncoderDecoderModel"]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase__ = ["FlaxEncoderDecoderModel"]
if TYPE_CHECKING:
from .configuration_encoder_decoder import EncoderDecoderConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_encoder_decoder import EncoderDecoderModel
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_encoder_decoder import TFEncoderDecoderModel
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel
else:
import sys
lowerCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 715 |
'''simple docstring'''
import hashlib
import unittest
from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available
from transformers.pipelines import DepthEstimationPipeline, pipeline
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_tf,
require_timm,
require_torch,
require_vision,
slow,
)
from .test_pipelines_common import ANY
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
else:
class SCREAMING_SNAKE_CASE__ :
"""simple docstring"""
@staticmethod
def lowerCamelCase_ ( *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Tuple ):
"""simple docstring"""
pass
def __UpperCamelCase ( _UpperCAmelCase ):
__UpperCAmelCase : Any = hashlib.mda(image.tobytes() )
return m.hexdigest()
@is_pipeline_test
@require_vision
@require_timm
@require_torch
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE = MODEL_FOR_DEPTH_ESTIMATION_MAPPING
def lowerCamelCase_ ( self : Dict , UpperCAmelCase_ : Any , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[str] ):
"""simple docstring"""
__UpperCAmelCase : int = DepthEstimationPipeline(model=UpperCAmelCase_ , image_processor=UpperCAmelCase_ )
return depth_estimator, [
"./tests/fixtures/tests_samples/COCO/000000039769.png",
"./tests/fixtures/tests_samples/COCO/000000039769.png",
]
def lowerCamelCase_ ( self : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[int] ):
"""simple docstring"""
__UpperCAmelCase : Tuple = depth_estimator("./tests/fixtures/tests_samples/COCO/000000039769.png" )
self.assertEqual({"predicted_depth": ANY(torch.Tensor ), "depth": ANY(Image.Image )} , UpperCAmelCase_ )
import datasets
__UpperCAmelCase : str = datasets.load_dataset("hf-internal-testing/fixtures_image_utils" , "image" , split="test" )
__UpperCAmelCase : Dict = depth_estimator(
[
Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ),
"http://images.cocodataset.org/val2017/000000039769.jpg",
# RGBA
dataset[0]["file"],
# LA
dataset[1]["file"],
# L
dataset[2]["file"],
] )
self.assertEqual(
[
{"predicted_depth": ANY(torch.Tensor ), "depth": ANY(Image.Image )},
{"predicted_depth": ANY(torch.Tensor ), "depth": ANY(Image.Image )},
{"predicted_depth": ANY(torch.Tensor ), "depth": ANY(Image.Image )},
{"predicted_depth": ANY(torch.Tensor ), "depth": ANY(Image.Image )},
{"predicted_depth": ANY(torch.Tensor ), "depth": ANY(Image.Image )},
] , UpperCAmelCase_ , )
@require_tf
@unittest.skip("Depth estimation is not implemented in TF" )
def lowerCamelCase_ ( self : List[str] ):
"""simple docstring"""
pass
@slow
@require_torch
def lowerCamelCase_ ( self : Optional[int] ):
"""simple docstring"""
__UpperCAmelCase : List[str] = "Intel/dpt-large"
__UpperCAmelCase : Optional[int] = pipeline("depth-estimation" , model=UpperCAmelCase_ )
__UpperCAmelCase : Any = depth_estimator("http://images.cocodataset.org/val2017/000000039769.jpg" )
__UpperCAmelCase : str = hashimage(outputs["depth"] )
# This seems flaky.
# self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977")
self.assertEqual(nested_simplify(outputs["predicted_depth"].max().item() ) , 29.304 )
self.assertEqual(nested_simplify(outputs["predicted_depth"].min().item() ) , 2.662 )
@require_torch
def lowerCamelCase_ ( self : List[str] ):
"""simple docstring"""
# This is highly irregular to have no small tests.
self.skipTest("There is not hf-internal-testing tiny model for either GLPN nor DPT" )
| 329 | 0 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCAmelCase = logging.get_logger(__name__)
__lowerCAmelCase = {
'abeja/gpt-neox-japanese-2.7b': 'https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json',
}
class _lowerCAmelCase ( lowercase__ ):
'''simple docstring'''
lowerCAmelCase_ = '''gpt_neox_japanese'''
def __init__(self , UpperCAmelCase=32000 , UpperCAmelCase=2560 , UpperCAmelCase=32 , UpperCAmelCase=32 , UpperCAmelCase=4 , UpperCAmelCase="gelu" , UpperCAmelCase=1.00 , UpperCAmelCase=10000 , UpperCAmelCase=2048 , UpperCAmelCase=0.02 , UpperCAmelCase=1e-5 , UpperCAmelCase=True , UpperCAmelCase=31996 , UpperCAmelCase=31999 , UpperCAmelCase=0.1 , UpperCAmelCase=0.0 , **UpperCAmelCase , ) -> Tuple:
super().__init__(bos_token_id=_a , eos_token_id=_a , **_a )
_snake_case = vocab_size
_snake_case = max_position_embeddings
_snake_case = hidden_size
_snake_case = num_hidden_layers
_snake_case = num_attention_heads
_snake_case = intermediate_multiple_size
_snake_case = hidden_act
_snake_case = rotary_pct
_snake_case = rotary_emb_base
_snake_case = initializer_range
_snake_case = layer_norm_eps
_snake_case = use_cache
_snake_case = attention_dropout
_snake_case = hidden_dropout | 585 |
'''simple docstring'''
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import TensorType, logging
if TYPE_CHECKING:
from ...onnx.config import PatchingSpec
from ...tokenization_utils_base import PreTrainedTokenizerBase
__lowerCAmelCase = logging.get_logger(__name__)
__lowerCAmelCase = {
"""allenai/longformer-base-4096""": """https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json""",
"""allenai/longformer-large-4096""": """https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json""",
"""allenai/longformer-large-4096-finetuned-triviaqa""": (
"""https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json"""
),
"""allenai/longformer-base-4096-extra.pos.embd.only""": (
"""https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json"""
),
"""allenai/longformer-large-4096-extra.pos.embd.only""": (
"""https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json"""
),
}
class UpperCAmelCase__ ( lowercase__ ):
"""simple docstring"""
__UpperCAmelCase : List[str] = '''longformer'''
def __init__( self : Optional[Any] ,_a : Union[List[int], int] = 512 ,_a : int = 2 ,_a : int = 1 ,_a : int = 0 ,_a : int = 2 ,_a : int = 3_0522 ,_a : int = 768 ,_a : int = 12 ,_a : int = 12 ,_a : int = 3072 ,_a : str = "gelu" ,_a : float = 0.1 ,_a : float = 0.1 ,_a : int = 512 ,_a : int = 2 ,_a : float = 0.02 ,_a : float = 1E-12 ,_a : bool = False ,**_a : Union[str, Any] ,):
'''simple docstring'''
super().__init__(pad_token_id=_a ,**_a )
_a : Tuple = attention_window
_a : int = sep_token_id
_a : Dict = bos_token_id
_a : str = eos_token_id
_a : Tuple = vocab_size
_a : Tuple = hidden_size
_a : Union[str, Any] = num_hidden_layers
_a : List[str] = num_attention_heads
_a : int = hidden_act
_a : List[str] = intermediate_size
_a : Any = hidden_dropout_prob
_a : Any = attention_probs_dropout_prob
_a : Optional[int] = max_position_embeddings
_a : Any = type_vocab_size
_a : List[Any] = initializer_range
_a : Tuple = layer_norm_eps
_a : Optional[int] = onnx_export
class UpperCAmelCase__ ( lowercase__ ):
"""simple docstring"""
def __init__( self : Optional[int] ,_a : "PretrainedConfig" ,_a : str = "default" ,_a : "List[PatchingSpec]" = None ):
'''simple docstring'''
super().__init__(_a ,_a ,_a )
_a : int = True
@property
def __lowercase ( self : List[Any] ):
'''simple docstring'''
if self.task == "multiple-choice":
_a : Union[str, Any] = {0: 'batch', 1: 'choice', 2: 'sequence'}
else:
_a : str = {0: 'batch', 1: 'sequence'}
return OrderedDict(
[
('input_ids', dynamic_axis),
('attention_mask', dynamic_axis),
('global_attention_mask', dynamic_axis),
] )
@property
def __lowercase ( self : List[Any] ):
'''simple docstring'''
_a : List[str] = super().outputs
if self.task == "default":
_a : List[str] = {0: 'batch'}
return outputs
@property
def __lowercase ( self : Optional[int] ):
'''simple docstring'''
return 1E-4
@property
def __lowercase ( self : List[str] ):
'''simple docstring'''
return max(super().default_onnx_opset ,14 )
def __lowercase ( self : int ,_a : "PreTrainedTokenizerBase" ,_a : int = -1 ,_a : int = -1 ,_a : bool = False ,_a : Optional[TensorType] = None ,):
'''simple docstring'''
_a : Union[str, Any] = super().generate_dummy_inputs(
preprocessor=_a ,batch_size=_a ,seq_length=_a ,is_pair=_a ,framework=_a )
import torch
# for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64)
# makes the export fail randomly
_a : Optional[int] = torch.zeros_like(inputs['input_ids'] )
# make every second token global
_a : List[str] = 1
return inputs
| 229 | 0 |
"""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 timm import create_model
from timm.data import resolve_data_config
from timm.data.transforms_factory import create_transform
from transformers import BitConfig, BitForImageClassification, BitImageProcessor
from transformers.image_utils import PILImageResampling
from transformers.utils import logging
logging.set_verbosity_info()
A__ : str = logging.get_logger(__name__)
def _lowerCAmelCase ( _UpperCamelCase ):
"""simple docstring"""
_lowercase: Union[str, Any] = '''huggingface/label-files'''
_lowercase: Union[str, Any] = '''imagenet-1k-id2label.json'''
_lowercase: str = json.load(open(hf_hub_download(_UpperCamelCase , _UpperCamelCase , repo_type='''dataset''' ) , '''r''' ) )
_lowercase: Optional[Any] = {int(_UpperCamelCase ): v for k, v in idalabel.items()}
_lowercase: List[str] = {v: k for k, v in idalabel.items()}
_lowercase: List[Any] = '''std_conv''' if '''bit''' in model_name else False
# note that when using BiT as backbone for ViT-hybrid checkpoints,
# one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same",
# config.conv_layer = "std_conv_same"
_lowercase: Any = BitConfig(
conv_layer=_UpperCamelCase , num_labels=1_000 , idalabel=_UpperCamelCase , labelaid=_UpperCamelCase , )
return config
def _lowerCAmelCase ( _UpperCamelCase ):
"""simple docstring"""
if "stem.conv" in name:
_lowercase: str = name.replace('''stem.conv''' , '''bit.embedder.convolution''' )
if "blocks" in name:
_lowercase: Tuple = name.replace('''blocks''' , '''layers''' )
if "head.fc" in name:
_lowercase: Optional[Any] = name.replace('''head.fc''' , '''classifier.1''' )
if name.startswith('''norm''' ):
_lowercase: int = '''bit.''' + name
if "bit" not in name and "classifier" not in name:
_lowercase: str = '''bit.encoder.''' + name
return name
def _lowerCAmelCase ( ):
"""simple docstring"""
_lowercase: List[Any] = '''http://images.cocodataset.org/val2017/000000039769.jpg'''
_lowercase: Dict = Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw )
return im
@torch.no_grad()
def _lowerCAmelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase=False ):
"""simple docstring"""
_lowercase: Tuple = get_config(_UpperCamelCase )
# load original model from timm
_lowercase: Optional[int] = create_model(_UpperCamelCase , pretrained=_UpperCamelCase )
timm_model.eval()
# load state_dict of original model
_lowercase: Union[str, Any] = timm_model.state_dict()
for key in state_dict.copy().keys():
_lowercase: Dict = state_dict.pop(_UpperCamelCase )
_lowercase: Any = val.squeeze() if '''head''' in key else val
# load HuggingFace model
_lowercase: List[str] = BitForImageClassification(_UpperCamelCase )
model.eval()
model.load_state_dict(_UpperCamelCase )
# create image processor
_lowercase: Dict = create_transform(**resolve_data_config({} , model=_UpperCamelCase ) )
_lowercase: str = transform.transforms
_lowercase: Optional[Any] = {
'''bilinear''': PILImageResampling.BILINEAR,
'''bicubic''': PILImageResampling.BICUBIC,
'''nearest''': PILImageResampling.NEAREST,
}
_lowercase: Optional[Any] = BitImageProcessor(
do_resize=_UpperCamelCase , size={'''shortest_edge''': timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=_UpperCamelCase , crop_size={'''height''': timm_transforms[1].size[0], '''width''': timm_transforms[1].size[1]} , do_normalize=_UpperCamelCase , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , )
_lowercase: Any = prepare_img()
_lowercase: Optional[Any] = transform(_UpperCamelCase ).unsqueeze(0 )
_lowercase: Dict = processor(_UpperCamelCase , return_tensors='''pt''' ).pixel_values
# verify pixel values
assert torch.allclose(_UpperCamelCase , _UpperCamelCase )
# verify logits
with torch.no_grad():
_lowercase: Dict = model(_UpperCamelCase )
_lowercase: List[str] = outputs.logits
print('''Logits:''' , logits[0, :3] )
print('''Predicted class:''' , model.config.idalabel[logits.argmax(-1 ).item()] )
_lowercase: Tuple = timm_model(_UpperCamelCase )
assert timm_logits.shape == outputs.logits.shape
assert torch.allclose(_UpperCamelCase , outputs.logits , atol=1e-3 )
print('''Looks ok!''' )
if pytorch_dump_folder_path is not None:
Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase )
print(f'''Saving model {model_name} and processor to {pytorch_dump_folder_path}''' )
model.save_pretrained(_UpperCamelCase )
processor.save_pretrained(_UpperCamelCase )
if push_to_hub:
print(f'''Pushing model {model_name} and processor to the hub''' )
model.push_to_hub(f'''ybelkada/{model_name}''' )
processor.push_to_hub(f'''ybelkada/{model_name}''' )
if __name__ == "__main__":
A__ : List[str] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--model_name',
default='resnetv2_50x1_bitm',
type=str,
help='Name of the BiT timm model you\'d like to convert.',
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.'
)
parser.add_argument(
'--push_to_hub',
action='store_true',
help='Whether to push the model to the hub.',
)
A__ : str = parser.parse_args()
convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 709 |
"""simple docstring"""
def _lowerCAmelCase ( _UpperCamelCase ):
"""simple docstring"""
if not isinstance(_UpperCamelCase , _UpperCamelCase ):
raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' )
if len(_UpperCamelCase ) == 0:
raise ValueError('''Input list must be a non empty list''' )
if len(_UpperCamelCase ) == 1:
return True
_lowercase: Any = series[1] - series[0]
for index in range(len(_UpperCamelCase ) - 1 ):
if series[index + 1] - series[index] != common_diff:
return False
return True
def _lowerCAmelCase ( _UpperCamelCase ):
"""simple docstring"""
if not isinstance(_UpperCamelCase , _UpperCamelCase ):
raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' )
if len(_UpperCamelCase ) == 0:
raise ValueError('''Input list must be a non empty list''' )
_lowercase: Tuple = 0
for val in series:
answer += val
return answer / len(_UpperCamelCase )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 272 | 0 |
'''simple docstring'''
import numpy as np
def lowerCAmelCase_ ( a : np.array ):
return 1 / (1 + np.exp(-vector ))
def lowerCAmelCase_ ( a : np.array ):
return vector * sigmoid(1.702 * vector )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 394 |
'''simple docstring'''
class _UpperCamelCase :
'''simple docstring'''
def __init__( self ):
"""simple docstring"""
a__ = {} # Mapping from char to TrieNode
a__ = False
def lowercase__ ( self , _a ):
"""simple docstring"""
for word in words:
self.insert(_a )
def lowercase__ ( self , _a ):
"""simple docstring"""
a__ = self
for char in word:
if char not in curr.nodes:
a__ = TrieNode()
a__ = curr.nodes[char]
a__ = True
def lowercase__ ( self , _a ):
"""simple docstring"""
a__ = self
for char in word:
if char not in curr.nodes:
return False
a__ = curr.nodes[char]
return curr.is_leaf
def lowercase__ ( self , _a ):
"""simple docstring"""
def _delete(_a , _a , _a ) -> bool:
if index == len(_a ):
# If word does not exist
if not curr.is_leaf:
return False
a__ = False
return len(curr.nodes ) == 0
a__ = word[index]
a__ = curr.nodes.get(_a )
# If char not in current trie node
if not char_node:
return False
# Flag to check if node can be deleted
a__ = _delete(_a , _a , index + 1 )
if delete_curr:
del curr.nodes[char]
return len(curr.nodes ) == 0
return delete_curr
_delete(self , _a , 0 )
def lowerCAmelCase_ ( a : TrieNode , a : str ):
if node.is_leaf:
print(a , end=' ' )
for key, value in node.nodes.items():
print_words(a , word + key )
def lowerCAmelCase_ ( ):
a__ = 'banana bananas bandana band apple all beast'.split()
a__ = TrieNode()
root.insert_many(a )
# print_words(root, "")
assert all(root.find(a ) for word in words )
assert root.find('banana' )
assert not root.find('bandanas' )
assert not root.find('apps' )
assert root.find('apple' )
assert root.find('all' )
root.delete('all' )
assert not root.find('all' )
root.delete('banana' )
assert not root.find('banana' )
assert root.find('bananas' )
return True
def lowerCAmelCase_ ( a : str , a : bool ):
print(str(a ) , 'works!' if passes else 'doesn\'t work :(' )
def lowerCAmelCase_ ( ):
assert test_trie()
def lowerCAmelCase_ ( ):
print_results('Testing trie functionality' , test_trie() )
if __name__ == "__main__":
main()
| 394 | 1 |
'''simple docstring'''
import colorsys
from PIL import Image # type: ignore
def A_( A : float , A : float , A : int):
UpperCamelCase = x
UpperCamelCase = y
for step in range(A): # noqa: B007
UpperCamelCase = a * a - b * b + x
UpperCamelCase = 2 * a * b + y
UpperCamelCase = a_new
# divergence happens for all complex number with an absolute value
# greater than 4
if a * a + b * b > 4:
break
return step / (max_step - 1)
def A_( A : float):
if distance == 1:
return (0, 0, 0)
else:
return (255, 255, 255)
def A_( A : float):
if distance == 1:
return (0, 0, 0)
else:
return tuple(round(i * 255) for i in colorsys.hsv_to_rgb(A , 1 , 1))
def A_( A : int = 800 , A : int = 600 , A : float = -0.6 , A : float = 0 , A : float = 3.2 , A : int = 50 , A : bool = True , ):
UpperCamelCase = Image.new('RGB' , (image_width, image_height))
UpperCamelCase = img.load()
# loop through the image-coordinates
for image_x in range(A):
for image_y in range(A):
# determine the figure-coordinates based on the image-coordinates
UpperCamelCase = figure_width / image_width * image_height
UpperCamelCase = figure_center_x + (image_x / image_width - 0.5) * figure_width
UpperCamelCase = figure_center_y + (image_y / image_height - 0.5) * figure_height
UpperCamelCase = get_distance(A , A , A)
# color the corresponding pixel based on the selected coloring-function
if use_distance_color_coding:
UpperCamelCase = get_color_coded_rgb(A)
else:
UpperCamelCase = get_black_and_white_rgb(A)
return img
if __name__ == "__main__":
import doctest
doctest.testmod()
# colored version, full figure
lowerCAmelCase : Tuple = get_image()
# uncomment for colored version, different section, zoomed in
# img = get_image(figure_center_x = -0.6, figure_center_y = -0.4,
# figure_width = 0.8)
# uncomment for black and white version, full figure
# img = get_image(use_distance_color_coding = False)
# uncomment to save the image
# img.save("mandelbrot.png")
img.show()
| 432 |
'''simple docstring'''
lowerCAmelCase : Optional[Any] = '\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n'
lowerCAmelCase : Optional[int] = [{'type': 'code', 'content': INSTALL_CONTENT}]
lowerCAmelCase : Optional[int] = {
'{processor_class}': 'FakeProcessorClass',
'{model_class}': 'FakeModelClass',
'{object_class}': 'FakeObjectClass',
}
| 432 | 1 |
"""simple docstring"""
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging
a_ = logging.get_logger(__name__)
a_ = {'vocab_file': 'sentencepiece.bpe.model'}
a_ = {
'vocab_file': {
'moussaKam/mbarthez': 'https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model',
'moussaKam/barthez': 'https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model',
'moussaKam/barthez-orangesum-title': (
'https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model'
),
},
}
a_ = {
'moussaKam/mbarthez': 1_0_2_4,
'moussaKam/barthez': 1_0_2_4,
'moussaKam/barthez-orangesum-title': 1_0_2_4,
}
a_ = '▁'
class UpperCAmelCase_ ( snake_case ):
UpperCamelCase =VOCAB_FILES_NAMES
UpperCamelCase =PRETRAINED_VOCAB_FILES_MAP
UpperCamelCase =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
UpperCamelCase =["input_ids", "attention_mask"]
def __init__( self , UpperCamelCase_ , UpperCamelCase_="<s>" , UpperCamelCase_="</s>" , UpperCamelCase_="</s>" , UpperCamelCase_="<s>" , UpperCamelCase_="<unk>" , UpperCamelCase_="<pad>" , UpperCamelCase_="<mask>" , UpperCamelCase_ = None , **UpperCamelCase_ , ) -> None:
# Mask token behave like a normal word, i.e. include the space before it
__lowercase : Tuple = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else mask_token
__lowercase : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
bos_token=UpperCamelCase_ , eos_token=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCamelCase_ , )
__lowercase : Optional[Any] = vocab_file
__lowercase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(str(UpperCamelCase_ ) )
__lowercase : List[Any] = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3}
__lowercase : str = len(self.sp_model ) - 1
__lowercase : str = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
def _lowerCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ = None ) -> List[int]:
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
__lowercase : int = [self.cls_token_id]
__lowercase : List[str] = [self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def _lowerCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = False ) -> List[int]:
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=UpperCamelCase_ , token_ids_a=UpperCamelCase_ , already_has_special_tokens=UpperCamelCase_ )
if token_ids_a is None:
return [1] + ([0] * len(UpperCamelCase_ )) + [1]
return [1] + ([0] * len(UpperCamelCase_ )) + [1, 1] + ([0] * len(UpperCamelCase_ )) + [1]
def _lowerCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ = None ) -> List[int]:
__lowercase : Any = [self.sep_token_id]
__lowercase : Union[str, Any] = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
@property
def _lowerCamelCase ( self ) -> Optional[Any]:
return len(self.sp_model )
def _lowerCamelCase ( self ) -> Optional[Any]:
__lowercase : List[str] = {self.convert_ids_to_tokens(UpperCamelCase_ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def _lowerCamelCase ( self , UpperCamelCase_ ) -> List[str]:
return self.sp_model.encode(UpperCamelCase_ , out_type=UpperCamelCase_ )
def _lowerCamelCase ( self , UpperCamelCase_ ) -> Optional[Any]:
if token in self.fairseq_tokens_to_ids:
return self.fairseq_tokens_to_ids[token]
__lowercase : Optional[Any] = self.sp_model.PieceToId(UpperCamelCase_ )
return spm_id if spm_id else self.unk_token_id
def _lowerCamelCase ( self , UpperCamelCase_ ) -> str:
if index in self.fairseq_ids_to_tokens:
return self.fairseq_ids_to_tokens[index]
return self.sp_model.IdToPiece(UpperCamelCase_ )
def _lowerCamelCase ( self , UpperCamelCase_ ) -> int:
__lowercase : Union[str, Any] = []
__lowercase : int = ''''''
__lowercase : int = False
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
if not prev_is_special:
out_string += " "
out_string += self.sp_model.decode(UpperCamelCase_ ) + token
__lowercase : List[str] = True
__lowercase : Optional[int] = []
else:
current_sub_tokens.append(UpperCamelCase_ )
__lowercase : int = False
out_string += self.sp_model.decode(UpperCamelCase_ )
return out_string.strip()
def __getstate__( self ) -> Any:
__lowercase : Optional[Any] = self.__dict__.copy()
__lowercase : Optional[int] = None
return state
def __setstate__( self , UpperCamelCase_ ) -> Tuple:
__lowercase : str = d
# for backward compatibility
if not hasattr(self , '''sp_model_kwargs''' ):
__lowercase : Any = {}
__lowercase : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def _lowerCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ = None ) -> Tuple[str]:
if not os.path.isdir(UpperCamelCase_ ):
logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" )
return
__lowercase : Tuple = os.path.join(
UpperCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase_ ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , UpperCamelCase_ )
elif not os.path.isfile(self.vocab_file ):
with open(UpperCamelCase_ , '''wb''' ) as fi:
__lowercase : Any = self.sp_model.serialized_model_proto()
fi.write(UpperCamelCase_ )
return (out_vocab_file,)
| 76 |
"""simple docstring"""
import unittest
import numpy as np
import torch
from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device
enable_full_determinism()
class lowercase ( unittest.TestCase ):
@property
def _snake_case ( self ) -> List[str]:
torch.manual_seed(0 )
lowerCAmelCase = UNetaDModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") , up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") , )
return model
def _snake_case ( self ) -> List[Any]:
lowerCAmelCase = self.dummy_uncond_unet
lowerCAmelCase = ScoreSdeVeScheduler()
lowerCAmelCase = ScoreSdeVePipeline(unet=lowercase , scheduler=lowercase )
sde_ve.to(lowercase )
sde_ve.set_progress_bar_config(disable=lowercase )
lowerCAmelCase = torch.manual_seed(0 )
lowerCAmelCase = sde_ve(num_inference_steps=2 , output_type="""numpy""" , generator=lowercase ).images
lowerCAmelCase = torch.manual_seed(0 )
lowerCAmelCase = sde_ve(num_inference_steps=2 , output_type="""numpy""" , generator=lowercase , return_dict=lowercase )[
0
]
lowerCAmelCase = image[0, -3:, -3:, -1]
lowerCAmelCase = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 32, 32, 3)
lowerCAmelCase = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
@slow
@require_torch
class lowercase ( unittest.TestCase ):
def _snake_case ( self ) -> Optional[int]:
lowerCAmelCase = """google/ncsnpp-church-256"""
lowerCAmelCase = UNetaDModel.from_pretrained(lowercase )
lowerCAmelCase = ScoreSdeVeScheduler.from_pretrained(lowercase )
lowerCAmelCase = ScoreSdeVePipeline(unet=lowercase , scheduler=lowercase )
sde_ve.to(lowercase )
sde_ve.set_progress_bar_config(disable=lowercase )
lowerCAmelCase = torch.manual_seed(0 )
lowerCAmelCase = sde_ve(num_inference_steps=10 , output_type="""numpy""" , generator=lowercase ).images
lowerCAmelCase = image[0, -3:, -3:, -1]
assert image.shape == (1, 256, 256, 3)
lowerCAmelCase = np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
| 532 | 0 |
'''simple docstring'''
def A_ ( _lowerCAmelCase : str ):
"""simple docstring"""
assert column_title.isupper()
_lowerCamelCase : Optional[Any] = 0
_lowerCamelCase : Union[str, Any] = len(_lowerCAmelCase ) - 1
_lowerCamelCase : List[Any] = 0
while index >= 0:
_lowerCamelCase : List[str] = (ord(column_title[index] ) - 64) * pow(26 , _lowerCAmelCase )
answer += value
power += 1
index -= 1
return answer
if __name__ == "__main__":
from doctest import testmod
testmod() | 706 |
'''simple docstring'''
import contextlib
import copy
import random
from typing import Any, Dict, Iterable, Optional, Union
import numpy as np
import torch
from .utils import deprecate, is_transformers_available
if is_transformers_available():
import transformers
def A_ ( _lowerCAmelCase : int ):
"""simple docstring"""
random.seed(_lowerCAmelCase )
np.random.seed(_lowerCAmelCase )
torch.manual_seed(_lowerCAmelCase )
torch.cuda.manual_seed_all(_lowerCAmelCase )
# ^^ safe to call this function even if cuda is not available
class UpperCAmelCase__ :
def __init__( self : List[str],__A : Iterable[torch.nn.Parameter],__A : float = 0.9999,__A : float = 0.0,__A : int = 0,__A : bool = False,__A : Union[float, int] = 1.0,__A : Union[float, int] = 2 / 3,__A : Optional[Any] = None,__A : Dict[str, Any] = None,**__A : Optional[Any],):
if isinstance(__A,torch.nn.Module ):
_lowerCamelCase : Any = (
"Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. "
"Please pass the parameters of the module instead."
)
deprecate(
"passing a `torch.nn.Module` to `ExponentialMovingAverage`","1.0.0",__A,standard_warn=__A,)
_lowerCamelCase : Dict = parameters.parameters()
# set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility
_lowerCamelCase : Optional[Any] = True
if kwargs.get("max_value",__A ) is not None:
_lowerCamelCase : Optional[int] = "The `max_value` argument is deprecated. Please use `decay` instead."
deprecate("max_value","1.0.0",__A,standard_warn=__A )
_lowerCamelCase : Optional[Any] = kwargs["max_value"]
if kwargs.get("min_value",__A ) is not None:
_lowerCamelCase : Tuple = "The `min_value` argument is deprecated. Please use `min_decay` instead."
deprecate("min_value","1.0.0",__A,standard_warn=__A )
_lowerCamelCase : Any = kwargs["min_value"]
_lowerCamelCase : Optional[int] = list(__A )
_lowerCamelCase : List[Any] = [p.clone().detach() for p in parameters]
if kwargs.get("device",__A ) is not None:
_lowerCamelCase : Optional[int] = "The `device` argument is deprecated. Please use `to` instead."
deprecate("device","1.0.0",__A,standard_warn=__A )
self.to(device=kwargs["device"] )
_lowerCamelCase : Tuple = None
_lowerCamelCase : Dict = decay
_lowerCamelCase : List[Any] = min_decay
_lowerCamelCase : Optional[Any] = update_after_step
_lowerCamelCase : Any = use_ema_warmup
_lowerCamelCase : Union[str, Any] = inv_gamma
_lowerCamelCase : str = power
_lowerCamelCase : Union[str, Any] = 0
_lowerCamelCase : Union[str, Any] = None # set in `step()`
_lowerCamelCase : List[str] = model_cls
_lowerCamelCase : Dict = model_config
@classmethod
def lowerCamelCase_ ( cls : Union[str, Any],__A : List[str],__A : Optional[int] ):
_lowerCamelCase , _lowerCamelCase : Optional[int] = model_cls.load_config(__A,return_unused_kwargs=__A )
_lowerCamelCase : Optional[Any] = model_cls.from_pretrained(__A )
_lowerCamelCase : Union[str, Any] = cls(model.parameters(),model_cls=__A,model_config=model.config )
ema_model.load_state_dict(__A )
return ema_model
def lowerCamelCase_ ( self : str,__A : int ):
if self.model_cls is None:
raise ValueError("`save_pretrained` can only be used if `model_cls` was defined at __init__." )
if self.model_config is None:
raise ValueError("`save_pretrained` can only be used if `model_config` was defined at __init__." )
_lowerCamelCase : Tuple = self.model_cls.from_config(self.model_config )
_lowerCamelCase : List[str] = self.state_dict()
state_dict.pop("shadow_params",__A )
model.register_to_config(**__A )
self.copy_to(model.parameters() )
model.save_pretrained(__A )
def lowerCamelCase_ ( self : Optional[int],__A : int ):
_lowerCamelCase : str = max(0,optimization_step - self.update_after_step - 1 )
if step <= 0:
return 0.0
if self.use_ema_warmup:
_lowerCamelCase : Tuple = 1 - (1 + step / self.inv_gamma) ** -self.power
else:
_lowerCamelCase : List[str] = (1 + step) / (1_0 + step)
_lowerCamelCase : Union[str, Any] = min(__A,self.decay )
# make sure decay is not smaller than min_decay
_lowerCamelCase : Union[str, Any] = max(__A,self.min_decay )
return cur_decay_value
@torch.no_grad()
def lowerCamelCase_ ( self : Any,__A : Iterable[torch.nn.Parameter] ):
if isinstance(__A,torch.nn.Module ):
_lowerCamelCase : Dict = (
"Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. "
"Please pass the parameters of the module instead."
)
deprecate(
"passing a `torch.nn.Module` to `ExponentialMovingAverage.step`","1.0.0",__A,standard_warn=__A,)
_lowerCamelCase : Any = parameters.parameters()
_lowerCamelCase : str = list(__A )
self.optimization_step += 1
# Compute the decay factor for the exponential moving average.
_lowerCamelCase : Dict = self.get_decay(self.optimization_step )
_lowerCamelCase : Optional[Any] = decay
_lowerCamelCase : List[Any] = 1 - decay
_lowerCamelCase : List[Any] = contextlib.nullcontext
if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled():
import deepspeed
for s_param, param in zip(self.shadow_params,__A ):
if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled():
_lowerCamelCase : List[Any] = deepspeed.zero.GatheredParameters(__A,modifier_rank=__A )
with context_manager():
if param.requires_grad:
s_param.sub_(one_minus_decay * (s_param - param) )
else:
s_param.copy_(__A )
def lowerCamelCase_ ( self : Dict,__A : Iterable[torch.nn.Parameter] ):
_lowerCamelCase : Tuple = list(__A )
for s_param, param in zip(self.shadow_params,__A ):
param.data.copy_(s_param.to(param.device ).data )
def lowerCamelCase_ ( self : List[str],__A : Dict=None,__A : Any=None ):
_lowerCamelCase : int = [
p.to(device=__A,dtype=__A ) if p.is_floating_point() else p.to(device=__A )
for p in self.shadow_params
]
def lowerCamelCase_ ( self : List[Any] ):
return {
"decay": self.decay,
"min_decay": self.min_decay,
"optimization_step": self.optimization_step,
"update_after_step": self.update_after_step,
"use_ema_warmup": self.use_ema_warmup,
"inv_gamma": self.inv_gamma,
"power": self.power,
"shadow_params": self.shadow_params,
}
def lowerCamelCase_ ( self : Tuple,__A : Iterable[torch.nn.Parameter] ):
_lowerCamelCase : Tuple = [param.detach().cpu().clone() for param in parameters]
def lowerCamelCase_ ( self : int,__A : Iterable[torch.nn.Parameter] ):
if self.temp_stored_params is None:
raise RuntimeError("This ExponentialMovingAverage has no `store()`ed weights " "to `restore()`" )
for c_param, param in zip(self.temp_stored_params,__A ):
param.data.copy_(c_param.data )
# Better memory-wise.
_lowerCamelCase : List[str] = None
def lowerCamelCase_ ( self : Dict,__A : dict ):
_lowerCamelCase : List[str] = copy.deepcopy(__A )
_lowerCamelCase : Optional[Any] = state_dict.get("decay",self.decay )
if self.decay < 0.0 or self.decay > 1.0:
raise ValueError("Decay must be between 0 and 1" )
_lowerCamelCase : Dict = state_dict.get("min_decay",self.min_decay )
if not isinstance(self.min_decay,__A ):
raise ValueError("Invalid min_decay" )
_lowerCamelCase : Tuple = state_dict.get("optimization_step",self.optimization_step )
if not isinstance(self.optimization_step,__A ):
raise ValueError("Invalid optimization_step" )
_lowerCamelCase : Any = state_dict.get("update_after_step",self.update_after_step )
if not isinstance(self.update_after_step,__A ):
raise ValueError("Invalid update_after_step" )
_lowerCamelCase : List[Any] = state_dict.get("use_ema_warmup",self.use_ema_warmup )
if not isinstance(self.use_ema_warmup,__A ):
raise ValueError("Invalid use_ema_warmup" )
_lowerCamelCase : Tuple = state_dict.get("inv_gamma",self.inv_gamma )
if not isinstance(self.inv_gamma,(float, int) ):
raise ValueError("Invalid inv_gamma" )
_lowerCamelCase : Union[str, Any] = state_dict.get("power",self.power )
if not isinstance(self.power,(float, int) ):
raise ValueError("Invalid power" )
_lowerCamelCase : Optional[Any] = state_dict.get("shadow_params",__A )
if shadow_params is not None:
_lowerCamelCase : str = shadow_params
if not isinstance(self.shadow_params,__A ):
raise ValueError("shadow_params must be a list" )
if not all(isinstance(__A,torch.Tensor ) for p in self.shadow_params ):
raise ValueError("shadow_params must all be Tensors" ) | 11 | 0 |
"""simple docstring"""
def lowercase_ ( _lowerCamelCase: int = 4000000 ) -> int:
'''simple docstring'''
__lowerCamelCase : List[str] = []
__lowerCamelCase : str = 0, 1
while b <= n:
if b % 2 == 0:
even_fibs.append(__UpperCAmelCase )
__lowerCamelCase : Optional[int] = b, a + b
return sum(__UpperCAmelCase )
if __name__ == "__main__":
print(F"""{solution() = }""") | 646 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
UpperCAmelCase_ = {
'configuration_rag': ['RagConfig'],
'retrieval_rag': ['RagRetriever'],
'tokenization_rag': ['RagTokenizer'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ = [
'RagModel',
'RagPreTrainedModel',
'RagSequenceForGeneration',
'RagTokenForGeneration',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ = [
'TFRagModel',
'TFRagPreTrainedModel',
'TFRagSequenceForGeneration',
'TFRagTokenForGeneration',
]
if TYPE_CHECKING:
from .configuration_rag import RagConfig
from .retrieval_rag import RagRetriever
from .tokenization_rag import RagTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_rag import (
TFRagModel,
TFRagPreTrainedModel,
TFRagSequenceForGeneration,
TFRagTokenForGeneration,
)
else:
import sys
UpperCAmelCase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 253 | 0 |
import requests
from bsa import BeautifulSoup
def _UpperCAmelCase (UpperCamelCase_ : str = "https://www.worldometers.info/coronavirus" ):
'''simple docstring'''
_lowerCAmelCase : Optional[int] = BeautifulSoup(requests.get(UpperCamelCase_ ).text , """html.parser""" )
_lowerCAmelCase : Optional[Any] = soup.findAll("""h1""" )
_lowerCAmelCase : 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(UpperCamelCase_ , UpperCamelCase_ )}
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''')
| 196 |
def _UpperCAmelCase (UpperCamelCase_ : str ):
'''simple docstring'''
_lowerCAmelCase : Dict = [0] * len(UpperCamelCase_ )
for i in range(1 , len(UpperCamelCase_ ) ):
# use last results for better performance - dynamic programming
_lowerCAmelCase : Union[str, Any] = prefix_result[i - 1]
while j > 0 and input_string[i] != input_string[j]:
_lowerCAmelCase : str = prefix_result[j - 1]
if input_string[i] == input_string[j]:
j += 1
_lowerCAmelCase : Optional[int] = j
return prefix_result
def _UpperCAmelCase (UpperCamelCase_ : str ):
'''simple docstring'''
return max(prefix_function(UpperCamelCase_ ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 196 | 1 |
'''simple docstring'''
from typing import Dict
from .base import GenericTensor, Pipeline
class lowerCAmelCase ( __A):
def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE ) -> List[Any]:
'''simple docstring'''
if tokenize_kwargs is None:
__snake_case = {}
if truncation is not None:
if "truncation" in tokenize_kwargs:
raise ValueError(
'''truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)''' )
__snake_case = truncation
__snake_case = tokenize_kwargs
__snake_case = {}
if return_tensors is not None:
__snake_case = return_tensors
return preprocess_params, {}, postprocess_params
def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) -> Optional[int]:
'''simple docstring'''
__snake_case = self.framework
__snake_case = self.tokenizer(__A , return_tensors=__A , **__A )
return model_inputs
def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE ) -> Any:
'''simple docstring'''
__snake_case = self.model(**__A )
return model_outputs
def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False ) -> int:
'''simple docstring'''
if return_tensors:
return model_outputs[0]
if self.framework == "pt":
return model_outputs[0].tolist()
elif self.framework == "tf":
return model_outputs[0].numpy().tolist()
def __call__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) -> Tuple:
'''simple docstring'''
return super().__call__(*__A , **__A )
| 24 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available
SCREAMING_SNAKE_CASE = {}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE = ['MLukeTokenizer']
if TYPE_CHECKING:
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_mluke import MLukeTokenizer
else:
import sys
SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 99 | 0 |
from collections import OrderedDict
from typing import Any, List, Mapping, Optional
from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging
A_ :List[str] = logging.get_logger(__name__)
A_ :Optional[Any] = {
'''Salesforce/codegen-350M-nl''': '''https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json''',
'''Salesforce/codegen-350M-multi''': '''https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json''',
'''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json''',
'''Salesforce/codegen-2B-nl''': '''https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json''',
'''Salesforce/codegen-2B-multi''': '''https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json''',
'''Salesforce/codegen-2B-mono''': '''https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json''',
'''Salesforce/codegen-6B-nl''': '''https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json''',
'''Salesforce/codegen-6B-multi''': '''https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json''',
'''Salesforce/codegen-6B-mono''': '''https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json''',
'''Salesforce/codegen-16B-nl''': '''https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json''',
'''Salesforce/codegen-16B-multi''': '''https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json''',
'''Salesforce/codegen-16B-mono''': '''https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json''',
}
class __A ( a ):
"""simple docstring"""
UpperCamelCase__ : Tuple ="""codegen"""
UpperCamelCase__ : int ={
"""max_position_embeddings""": """n_positions""",
"""hidden_size""": """n_embd""",
"""num_attention_heads""": """n_head""",
"""num_hidden_layers""": """n_layer""",
}
def __init__( self , lowerCamelCase__=50400 , lowerCamelCase__=2048 , lowerCamelCase__=2048 , lowerCamelCase__=4096 , lowerCamelCase__=28 , lowerCamelCase__=16 , lowerCamelCase__=64 , lowerCamelCase__=None , lowerCamelCase__="gelu_new" , lowerCamelCase__=0.0 , lowerCamelCase__=0.0 , lowerCamelCase__=0.0 , lowerCamelCase__=1E-5 , lowerCamelCase__=0.02 , lowerCamelCase__=True , lowerCamelCase__=50256 , lowerCamelCase__=50256 , lowerCamelCase__=False , **lowerCamelCase__ , ):
"""simple docstring"""
__UpperCamelCase : Optional[int] =vocab_size
__UpperCamelCase : str =n_ctx
__UpperCamelCase : Optional[Any] =n_positions
__UpperCamelCase : List[str] =n_embd
__UpperCamelCase : int =n_layer
__UpperCamelCase : List[Any] =n_head
__UpperCamelCase : List[Any] =n_inner
__UpperCamelCase : Tuple =rotary_dim
__UpperCamelCase : List[Any] =activation_function
__UpperCamelCase : Dict =resid_pdrop
__UpperCamelCase : Optional[Any] =embd_pdrop
__UpperCamelCase : Any =attn_pdrop
__UpperCamelCase : str =layer_norm_epsilon
__UpperCamelCase : List[Any] =initializer_range
__UpperCamelCase : Union[str, Any] =use_cache
__UpperCamelCase : List[str] =bos_token_id
__UpperCamelCase : Any =eos_token_id
super().__init__(
bos_token_id=lowerCamelCase__ , eos_token_id=lowerCamelCase__ , tie_word_embeddings=lowerCamelCase__ , **lowerCamelCase__ )
class __A ( a ):
"""simple docstring"""
def __init__( self , lowerCamelCase__ , lowerCamelCase__ = "default" , lowerCamelCase__ = None , lowerCamelCase__ = False , ):
"""simple docstring"""
super().__init__(lowerCamelCase__ , task=lowerCamelCase__ , patching_specs=lowerCamelCase__ , use_past=lowerCamelCase__ )
if not getattr(self._config , 'pad_token_id' , lowerCamelCase__ ):
# TODO: how to do that better?
__UpperCamelCase : Optional[Any] =0
@property
def __lowercase ( self ):
"""simple docstring"""
__UpperCamelCase : Optional[Any] =OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} )
if self.use_past:
self.fill_with_past_key_values_(lowerCamelCase__ , direction='inputs' )
__UpperCamelCase : List[Any] ={0: 'batch', 1: 'past_sequence + sequence'}
else:
__UpperCamelCase : int ={0: 'batch', 1: 'sequence'}
return common_inputs
@property
def __lowercase ( self ):
"""simple docstring"""
return self._config.n_layer
@property
def __lowercase ( self ):
"""simple docstring"""
return self._config.n_head
def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ = -1 , lowerCamelCase__ = -1 , lowerCamelCase__ = False , lowerCamelCase__ = None , ):
"""simple docstring"""
__UpperCamelCase : str =super(lowerCamelCase__ , self ).generate_dummy_inputs(
lowerCamelCase__ , batch_size=lowerCamelCase__ , seq_length=lowerCamelCase__ , is_pair=lowerCamelCase__ , framework=lowerCamelCase__ )
# We need to order the input in the way they appears in the forward()
__UpperCamelCase : Tuple =OrderedDict({'input_ids': common_inputs['input_ids']} )
# Need to add the past_keys
if self.use_past:
if not is_torch_available():
raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' )
else:
import torch
__UpperCamelCase : str =common_inputs['input_ids'].shape
# Not using the same length for past_key_values
__UpperCamelCase : List[Any] =seqlen + 2
__UpperCamelCase : Tuple =(
batch,
self.num_attention_heads,
past_key_values_length,
self._config.hidden_size // self.num_attention_heads,
)
__UpperCamelCase : Dict =[
(torch.zeros(lowerCamelCase__ ), torch.zeros(lowerCamelCase__ )) for _ in range(self.num_layers )
]
__UpperCamelCase : List[str] =common_inputs['attention_mask']
if self.use_past:
__UpperCamelCase : Tuple =ordered_inputs['attention_mask'].dtype
__UpperCamelCase : int =torch.cat(
[ordered_inputs['attention_mask'], torch.ones(lowerCamelCase__ , lowerCamelCase__ , dtype=lowerCamelCase__ )] , dim=1 )
return ordered_inputs
@property
def __lowercase ( self ):
"""simple docstring"""
return 13
| 705 |
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.linear_model import LinearRegression
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
# Fitting Polynomial Regression to the dataset
from sklearn.preprocessing import PolynomialFeatures
# Importing the dataset
A_ :int = pd.read_csv(
'''https://s3.us-west-2.amazonaws.com/public.gamelab.fun/dataset/'''
'''position_salaries.csv'''
)
A_ :str = dataset.iloc[:, 1:2].values
A_ :int = dataset.iloc[:, 2].values
A_ ,A_ ,A_ ,A_ :str = train_test_split(X, y, test_size=0.2, random_state=0)
A_ :Optional[int] = PolynomialFeatures(degree=4)
A_ :Optional[int] = poly_reg.fit_transform(X)
A_ :Tuple = LinearRegression()
pol_reg.fit(X_poly, y)
def A ( ) -> List[str]:
plt.scatter(a_ ,a_ ,color='red' )
plt.plot(a_ ,pol_reg.predict(poly_reg.fit_transform(a_ ) ) ,color='blue' )
plt.title('Truth or Bluff (Linear Regression)' )
plt.xlabel('Position level' )
plt.ylabel('Salary' )
plt.show()
if __name__ == "__main__":
viz_polymonial()
# Predicting a new result with Polymonial Regression
pol_reg.predict(poly_reg.fit_transform([[5.5]]))
# output should be 132148.43750003
| 154 | 0 |
import json
import os
import unittest
from transformers.models.roc_bert.tokenization_roc_bert import (
VOCAB_FILES_NAMES,
RoCBertBasicTokenizer,
RoCBertTokenizer,
RoCBertWordpieceTokenizer,
_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 _UpperCamelCase ( lowerCamelCase__ , unittest.TestCase ):
'''simple docstring'''
_A = RoCBertTokenizer
_A = None
_A = False
_A = True
_A = filter_non_english
def _UpperCAmelCase ( self : int ):
super().setUp()
_a = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', '你', '好', '是', '谁', 'a', 'b', 'c', 'd']
_a = {}
_a = {}
for i, value in enumerate(SCREAMING_SNAKE_CASE_ ):
_a = i
_a = i
_a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] )
_a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_shape_file'] )
_a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_pronunciation_file'] )
with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer:
vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) )
with open(self.word_shape_file , 'w' , encoding='utf-8' ) as word_shape_writer:
json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ensure_ascii=SCREAMING_SNAKE_CASE_ )
with open(self.word_pronunciation_file , 'w' , encoding='utf-8' ) as word_pronunciation_writer:
json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ensure_ascii=SCREAMING_SNAKE_CASE_ )
def _UpperCAmelCase ( self : List[str] ):
_a = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file )
_a = tokenizer.tokenize('你好[SEP]你是谁' )
self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['你', '好', '[SEP]', '你', '是', '谁'] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [5, 6, 2, 5, 7, 8] )
self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(SCREAMING_SNAKE_CASE_ ) , [5, 6, 2, 5, 7, 8] )
self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(SCREAMING_SNAKE_CASE_ ) , [5, 6, 2, 5, 7, 8] )
def _UpperCAmelCase ( self : Optional[Any] ):
_a = RoCBertBasicTokenizer()
self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] )
def _UpperCAmelCase ( self : Optional[Any] ):
_a = RoCBertBasicTokenizer(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 _UpperCAmelCase ( self : str ):
_a = RoCBertBasicTokenizer(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 _UpperCAmelCase ( self : Tuple ):
_a = RoCBertBasicTokenizer(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 _UpperCAmelCase ( self : Optional[int] ):
_a = RoCBertBasicTokenizer(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 _UpperCAmelCase ( self : int ):
_a = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ )
self.assertListEqual(
tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] )
def _UpperCAmelCase ( self : Union[str, Any] ):
_a = RoCBertBasicTokenizer(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 _UpperCAmelCase ( self : Any ):
_a = RoCBertBasicTokenizer(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 _UpperCAmelCase ( self : List[str] ):
_a = RoCBertBasicTokenizer(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 _UpperCAmelCase ( self : Union[str, Any] ):
_a = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing']
_a = {}
for i, token in enumerate(SCREAMING_SNAKE_CASE_ ):
_a = i
_a = RoCBertWordpieceTokenizer(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 _UpperCAmelCase ( self : Dict ):
self.assertTrue(_is_whitespace(' ' ) )
self.assertTrue(_is_whitespace('\t' ) )
self.assertTrue(_is_whitespace('\r' ) )
self.assertTrue(_is_whitespace('\n' ) )
self.assertTrue(_is_whitespace('\u00A0' ) )
self.assertFalse(_is_whitespace('A' ) )
self.assertFalse(_is_whitespace('-' ) )
def _UpperCAmelCase ( self : List[str] ):
self.assertTrue(_is_control('\u0005' ) )
self.assertFalse(_is_control('A' ) )
self.assertFalse(_is_control(' ' ) )
self.assertFalse(_is_control('\t' ) )
self.assertFalse(_is_control('\r' ) )
def _UpperCAmelCase ( self : List[str] ):
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 _UpperCAmelCase ( self : Union[str, Any] ):
_a = self.get_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]']] )
if self.test_rust_tokenizer:
_a = self.get_rust_tokenizer()
self.assertListEqual(
[rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] )
def _UpperCAmelCase ( self : List[Any] ):
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ):
_a = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
_a = f"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence."""
_a = 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_ , )
_a = tokenizer_r.do_lower_case if hasattr(SCREAMING_SNAKE_CASE_ , 'do_lower_case' ) else False
_a = (
[
((0, 0), tokenizer_r.cls_token),
((0, 1), 'A'),
((1, 2), ','),
((3, 5), 'na'),
((5, 6), '##ï'),
((6, 8), '##ve'),
((9, 1_5), tokenizer_r.mask_token),
((1_6, 2_1), 'Allen'),
((2_1, 2_3), '##NL'),
((2_3, 2_4), '##P'),
((2_5, 3_3), 'sentence'),
((3_3, 3_4), '.'),
((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, 1_5), tokenizer_r.mask_token),
((1_6, 2_1), 'allen'),
((2_1, 2_3), '##nl'),
((2_3, 2_4), '##p'),
((2_5, 3_3), 'sentence'),
((3_3, 3_4), '.'),
((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 _UpperCAmelCase ( self : int ):
_a = ['的', '人', '有']
_a = ''.join(SCREAMING_SNAKE_CASE_ )
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ):
_a = True
_a = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
_a = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
_a = tokenizer_p.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ )
_a = tokenizer_r.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ )
_a = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ )
_a = 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_ )
_a = False
_a = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
_a = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
_a = tokenizer_r.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ )
_a = tokenizer_p.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ )
_a = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ )
_a = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ )
# it is expected that only the first Chinese character is not preceded by "##".
_a = [
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_ )
@slow
def _UpperCAmelCase ( self : Tuple ):
_a = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file )
_a = tokenizer.encode('你好' , add_special_tokens=SCREAMING_SNAKE_CASE_ )
_a = tokenizer.encode('你是谁' , add_special_tokens=SCREAMING_SNAKE_CASE_ )
_a = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ )
_a = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
assert encoded_sentence == [1] + text + [2]
assert encoded_pair == [1] + text + [2] + text_a + [2]
def _UpperCAmelCase ( self : Optional[int] ):
_a = self.get_tokenizers(do_lower_case=SCREAMING_SNAKE_CASE_ )
for tokenizer in tokenizers:
with self.subTest(f"""{tokenizer.__class__.__name__}""" ):
_a = '你好,你是谁'
_a = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ )
_a = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ )
_a = tokenizer.convert_tokens_to_shape_ids(SCREAMING_SNAKE_CASE_ )
_a = tokenizer.convert_tokens_to_pronunciation_ids(SCREAMING_SNAKE_CASE_ )
_a = tokenizer.prepare_for_model(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ )
_a = tokenizer.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ )
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
| 562 |
import argparse
from typing import List
import evaluate
import numpy as np
import torch
from datasets import DatasetDict, load_dataset
# New Code #
# We'll be using StratifiedKFold for this example
from sklearn.model_selection import StratifiedKFold
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to perform Cross Validation,
# and builds off the `nlp_example.py` script.
#
# 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 help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# 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
#
########################################################################
lowercase_ = 16
lowercase_ = 32
def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 16 ) -> Any:
_a = AutoTokenizer.from_pretrained('bert-base-cased' )
_a = DatasetDict(
{
'train': dataset['train'].select(_UpperCAmelCase ),
'validation': dataset['train'].select(_UpperCAmelCase ),
'test': dataset['validation'],
} )
def tokenize_function(_UpperCAmelCase ):
# max_length=None => use the model max length (it's actually the default)
_a = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase )
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():
_a = datasets.map(
_UpperCAmelCase , batched=_UpperCAmelCase , 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
_a = tokenized_datasets.rename_column('label' , 'labels' )
def collate_fn(_UpperCAmelCase ):
# On TPU it's best to pad everything to the same length or training will be very slow.
_a = 128 if accelerator.distributed_type == DistributedType.TPU else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
_a = 16
elif accelerator.mixed_precision != "no":
_a = 8
else:
_a = None
return tokenizer.pad(
_UpperCAmelCase , padding='longest' , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_tensors='pt' , )
# Instantiate dataloaders.
_a = DataLoader(
tokenized_datasets['train'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase )
_a = DataLoader(
tokenized_datasets['validation'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase )
_a = DataLoader(
tokenized_datasets['test'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase )
return train_dataloader, eval_dataloader, test_dataloader
def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase ) -> Dict:
# New Code #
_a = []
# Download the dataset
_a = load_dataset('glue' , 'mrpc' )
# Create our splits
_a = StratifiedKFold(n_splits=int(args.num_folds ) )
# Initialize accelerator
_a = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
_a = config['lr']
_a = int(config['num_epochs'] )
_a = int(config['seed'] )
_a = int(config['batch_size'] )
_a = evaluate.load('glue' , 'mrpc' )
# If the batch size is too big we use gradient accumulation
_a = 1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
_a = batch_size // MAX_GPU_BATCH_SIZE
_a = MAX_GPU_BATCH_SIZE
set_seed(_UpperCAmelCase )
# New Code #
# Create our folds:
_a = kfold.split(np.zeros(datasets['train'].num_rows ) , datasets['train']['label'] )
_a = []
# Iterate over them
for i, (train_idxs, valid_idxs) in enumerate(_UpperCAmelCase ):
_a , _a , _a = get_fold_dataloaders(
_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
_a = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=_UpperCAmelCase )
# 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).
_a = model.to(accelerator.device )
# Instantiate optimizer
_a = AdamW(params=model.parameters() , lr=_UpperCAmelCase )
# Instantiate scheduler
_a = get_linear_schedule_with_warmup(
optimizer=_UpperCAmelCase , num_warmup_steps=100 , num_training_steps=(len(_UpperCAmelCase ) * num_epochs) // gradient_accumulation_steps , )
# 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.
_a , _a , _a , _a , _a = accelerator.prepare(
_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
# Now we train the model
for epoch in range(_UpperCAmelCase ):
model.train()
for step, batch in enumerate(_UpperCAmelCase ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
_a = model(**_UpperCAmelCase )
_a = outputs.loss
_a = loss / gradient_accumulation_steps
accelerator.backward(_UpperCAmelCase )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
for step, batch in enumerate(_UpperCAmelCase ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
_a = model(**_UpperCAmelCase )
_a = outputs.logits.argmax(dim=-1 )
_a , _a = accelerator.gather_for_metrics((predictions, batch['labels']) )
metric.add_batch(
predictions=_UpperCAmelCase , references=_UpperCAmelCase , )
_a = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f"""epoch {epoch}:""" , _UpperCAmelCase )
# New Code #
# We also run predictions on the test set at the very end
_a = []
for step, batch in enumerate(_UpperCAmelCase ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
_a = model(**_UpperCAmelCase )
_a = outputs.logits
_a , _a = accelerator.gather_for_metrics((predictions, batch['labels']) )
fold_predictions.append(predictions.cpu() )
if i == 0:
# We need all of the test predictions
test_references.append(references.cpu() )
# Use accelerator.print to print only on the main process.
test_predictions.append(torch.cat(_UpperCAmelCase , dim=0 ) )
# We now need to release all our memory and get rid of the current model, optimizer, etc
accelerator.free_memory()
# New Code #
# Finally we check the accuracy of our folded results:
_a = torch.cat(_UpperCAmelCase , dim=0 )
_a = torch.stack(_UpperCAmelCase , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 )
_a = metric.compute(predictions=_UpperCAmelCase , references=_UpperCAmelCase )
accelerator.print('Average test metrics from all folds:' , _UpperCAmelCase )
def SCREAMING_SNAKE_CASE ( ) -> List[Any]:
_a = argparse.ArgumentParser(description='Simple example of training script.' )
parser.add_argument(
'--mixed_precision' , type=_UpperCAmelCase , default=_UpperCAmelCase , 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.' )
# New Code #
parser.add_argument('--num_folds' , type=_UpperCAmelCase , default=3 , help='The number of splits to perform across the dataset' )
_a = parser.parse_args()
_a = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16}
training_function(_UpperCAmelCase , _UpperCAmelCase )
if __name__ == "__main__":
main()
| 562 | 1 |
'''simple docstring'''
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging
lowerCAmelCase_ : Tuple = logging.get_logger(__name__)
lowerCAmelCase_ : int = '▁'
lowerCAmelCase_ : List[Any] = {'vocab_file': 'sentencepiece.bpe.model', 'monolingual_vocab_file': 'dict.txt'}
lowerCAmelCase_ : Union[str, Any] = {
'vocab_file': {
'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model',
},
'monolingual_vocab_file': {
'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt',
},
}
lowerCAmelCase_ : Any = {'vinai/bartpho-syllable': 1024}
class lowerCamelCase_ ( snake_case_ ):
_lowerCAmelCase : int = VOCAB_FILES_NAMES
_lowerCAmelCase : int = PRETRAINED_VOCAB_FILES_MAP
_lowerCAmelCase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_lowerCAmelCase : Union[str, Any] = ['input_ids', 'attention_mask']
def __init__( self : Tuple , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : List[str]="<s>" , lowerCAmelCase__ : Optional[Any]="</s>" , lowerCAmelCase__ : Optional[int]="</s>" , lowerCAmelCase__ : Dict="<s>" , lowerCAmelCase__ : Dict="<unk>" , lowerCAmelCase__ : Optional[int]="<pad>" , lowerCAmelCase__ : str="<mask>" , lowerCAmelCase__ : Optional[Dict[str, Any]] = None , **lowerCAmelCase__ : List[str] , ):
"""simple docstring"""
# Mask token behave like a normal word, i.e. include the space before it
SCREAMING_SNAKE_CASE : Optional[int] = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else mask_token
SCREAMING_SNAKE_CASE : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
bos_token=lowerCAmelCase__ , eos_token=lowerCAmelCase__ , unk_token=lowerCAmelCase__ , sep_token=lowerCAmelCase__ , cls_token=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , mask_token=lowerCAmelCase__ , sp_model_kwargs=self.sp_model_kwargs , **lowerCAmelCase__ , )
SCREAMING_SNAKE_CASE : Optional[int] = vocab_file
SCREAMING_SNAKE_CASE : List[Any] = monolingual_vocab_file
SCREAMING_SNAKE_CASE : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(str(lowerCAmelCase__ ) )
# Load the reduced vocab
# Keep order of special tokens for backward compatibility
SCREAMING_SNAKE_CASE : int = {}
SCREAMING_SNAKE_CASE : Dict = 0
for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]:
if str(lowerCAmelCase__ ) not in self.fairseq_tokens_to_ids:
SCREAMING_SNAKE_CASE : Optional[Any] = cnt
cnt += 1
with open(lowerCAmelCase__ , '''r''' , encoding='''utf-8''' ) as f:
for line in f.readlines():
SCREAMING_SNAKE_CASE : Any = line.strip().split()[0]
SCREAMING_SNAKE_CASE : int = len(self.fairseq_tokens_to_ids )
if str(lowerCAmelCase__ ) not in self.fairseq_tokens_to_ids:
SCREAMING_SNAKE_CASE : Dict = len(self.fairseq_tokens_to_ids )
SCREAMING_SNAKE_CASE : Optional[int] = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
def __getstate__( self : Tuple ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : int = self.__dict__.copy()
SCREAMING_SNAKE_CASE : Any = None
SCREAMING_SNAKE_CASE : Union[str, Any] = self.sp_model.serialized_model_proto()
return state
def __setstate__( self : Union[str, Any] , lowerCAmelCase__ : List[str] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Tuple = d
# for backward compatibility
if not hasattr(self , '''sp_model_kwargs''' ):
SCREAMING_SNAKE_CASE : Union[str, Any] = {}
SCREAMING_SNAKE_CASE : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.LoadFromSerializedProto(self.sp_model_proto )
def __lowercase ( self : Optional[Any] , lowerCAmelCase__ : List[int] , lowerCAmelCase__ : Optional[List[int]] = None ):
"""simple docstring"""
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
SCREAMING_SNAKE_CASE : Dict = [self.cls_token_id]
SCREAMING_SNAKE_CASE : Tuple = [self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def __lowercase ( self : List[str] , lowerCAmelCase__ : List[int] , lowerCAmelCase__ : Optional[List[int]] = None , lowerCAmelCase__ : bool = False ):
"""simple docstring"""
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=lowerCAmelCase__ , token_ids_a=lowerCAmelCase__ , already_has_special_tokens=lowerCAmelCase__ )
if token_ids_a is None:
return [1] + ([0] * len(lowerCAmelCase__ )) + [1]
return [1] + ([0] * len(lowerCAmelCase__ )) + [1, 1] + ([0] * len(lowerCAmelCase__ )) + [1]
def __lowercase ( self : List[Any] , lowerCAmelCase__ : List[int] , lowerCAmelCase__ : Optional[List[int]] = None ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Tuple = [self.sep_token_id]
SCREAMING_SNAKE_CASE : Union[str, Any] = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
@property
def __lowercase ( self : List[str] ):
"""simple docstring"""
return len(self.fairseq_ids_to_tokens )
def __lowercase ( self : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Tuple = {self.convert_ids_to_tokens(lowerCAmelCase__ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __lowercase ( self : Any , lowerCAmelCase__ : str ):
"""simple docstring"""
return self.sp_model.encode(lowerCAmelCase__ , out_type=lowerCAmelCase__ )
def __lowercase ( self : int , lowerCAmelCase__ : Dict ):
"""simple docstring"""
if token in self.fairseq_tokens_to_ids:
return self.fairseq_tokens_to_ids[token]
else:
return self.unk_token_id
def __lowercase ( self : Union[str, Any] , lowerCAmelCase__ : Dict ):
"""simple docstring"""
return self.fairseq_ids_to_tokens[index]
def __lowercase ( self : List[str] , lowerCAmelCase__ : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Union[str, Any] = ''''''.join(lowerCAmelCase__ ).replace(lowerCAmelCase__ , ''' ''' ).strip()
return out_string
def __lowercase ( self : Dict , lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[str] = None ):
"""simple docstring"""
if not os.path.isdir(lowerCAmelCase__ ):
logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" )
return
SCREAMING_SNAKE_CASE : str = os.path.join(
lowerCAmelCase__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(
lowerCAmelCase__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''monolingual_vocab_file'''] , )
if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCAmelCase__ ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , lowerCAmelCase__ )
elif not os.path.isfile(self.vocab_file ):
with open(lowerCAmelCase__ , '''wb''' ) as fi:
SCREAMING_SNAKE_CASE : str = self.sp_model.serialized_model_proto()
fi.write(lowerCAmelCase__ )
if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath(
lowerCAmelCase__ ) and os.path.isfile(self.monolingual_vocab_file ):
copyfile(self.monolingual_vocab_file , lowerCAmelCase__ )
elif not os.path.isfile(self.monolingual_vocab_file ):
with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' ) as fp:
for token in self.fairseq_tokens_to_ids:
if token not in self.all_special_tokens:
fp.write(F"""{str(lowerCAmelCase__ )} \n""" )
return out_vocab_file, out_monolingual_vocab_file
| 464 |
'''simple docstring'''
import unittest
from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
lowerCAmelCase_ : Dict = get_tests_dir('fixtures/spiece.model')
@require_sentencepiece
@require_tokenizers
class lowerCamelCase_ ( snake_case_ , unittest.TestCase ):
_lowerCAmelCase : Union[str, Any] = DebertaVaTokenizer
_lowerCAmelCase : List[Any] = DebertaVaTokenizerFast
_lowerCAmelCase : Optional[Any] = True
_lowerCAmelCase : int = True
def __lowercase ( self : Optional[Any] ):
"""simple docstring"""
super().setUp()
# We have a SentencePiece fixture for testing
SCREAMING_SNAKE_CASE : Tuple = DebertaVaTokenizer(lowerCAmelCase__ , unk_token='''<unk>''' )
tokenizer.save_pretrained(self.tmpdirname )
def __lowercase ( self : List[str] , lowerCAmelCase__ : Any ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : List[str] = '''this is a test'''
SCREAMING_SNAKE_CASE : Tuple = '''this is a test'''
return input_text, output_text
def __lowercase ( self : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Optional[Any] = '''<pad>'''
SCREAMING_SNAKE_CASE : Tuple = 0
self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCAmelCase__ ) , lowerCAmelCase__ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCAmelCase__ ) , lowerCAmelCase__ )
def __lowercase ( self : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Tuple = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , '''<pad>''' )
self.assertEqual(vocab_keys[1] , '''<unk>''' )
self.assertEqual(vocab_keys[-1] , '''[PAD]''' )
self.assertEqual(len(lowerCAmelCase__ ) , 3_00_01 )
def __lowercase ( self : str ):
"""simple docstring"""
self.assertEqual(self.get_tokenizer().vocab_size , 3_00_00 )
def __lowercase ( self : List[str] ):
"""simple docstring"""
# fmt: off
SCREAMING_SNAKE_CASE : int = ''' \tHeLLo!how \n Are yoU? '''
SCREAMING_SNAKE_CASE : Optional[Any] = ['''▁hello''', '''!''', '''how''', '''▁are''', '''▁you''', '''?''']
# fmt: on
SCREAMING_SNAKE_CASE : Any = DebertaVaTokenizer(lowerCAmelCase__ , do_lower_case=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Tuple = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Dict = DebertaVaTokenizerFast(lowerCAmelCase__ , do_lower_case=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Union[str, Any] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
@unittest.skip('''There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.''' )
def __lowercase ( self : Dict ):
"""simple docstring"""
pass
@unittest.skip('''There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.''' )
def __lowercase ( self : str ):
"""simple docstring"""
pass
def __lowercase ( self : int ):
"""simple docstring"""
# fmt: off
SCREAMING_SNAKE_CASE : List[Any] = '''I was born in 92000, and this is falsé.'''
SCREAMING_SNAKE_CASE : Any = ['''▁''', '''<unk>''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', '''▁''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''▁''', '''.''', ]
# fmt: on
SCREAMING_SNAKE_CASE : Dict = DebertaVaTokenizer(lowerCAmelCase__ , split_by_punct=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Optional[int] = DebertaVaTokenizerFast(lowerCAmelCase__ , split_by_punct=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : str = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
def __lowercase ( self : Optional[Any] ):
"""simple docstring"""
# fmt: off
SCREAMING_SNAKE_CASE : Optional[int] = '''I was born in 92000, and this is falsé.'''
SCREAMING_SNAKE_CASE : List[str] = ['''▁i''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', '''▁''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''▁''', '''.''', ]
# fmt: on
SCREAMING_SNAKE_CASE : Union[str, Any] = DebertaVaTokenizer(lowerCAmelCase__ , do_lower_case=lowerCAmelCase__ , split_by_punct=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : int = DebertaVaTokenizerFast(lowerCAmelCase__ , do_lower_case=lowerCAmelCase__ , split_by_punct=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Any = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
def __lowercase ( self : Any ):
"""simple docstring"""
# fmt: off
SCREAMING_SNAKE_CASE : List[Any] = '''I was born in 92000, and this is falsé.'''
SCREAMING_SNAKE_CASE : Dict = ['''▁i''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''.''', ]
# fmt: on
SCREAMING_SNAKE_CASE : Tuple = DebertaVaTokenizer(lowerCAmelCase__ , do_lower_case=lowerCAmelCase__ , split_by_punct=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Any = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Any = DebertaVaTokenizerFast(lowerCAmelCase__ , do_lower_case=lowerCAmelCase__ , split_by_punct=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Optional[Any] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
def __lowercase ( self : Dict ):
"""simple docstring"""
# fmt: off
SCREAMING_SNAKE_CASE : str = '''I was born in 92000, and this is falsé.'''
SCREAMING_SNAKE_CASE : Union[str, Any] = ['''▁''', '''<unk>''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', '''▁''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''▁''', '''.''', ]
# fmt: on
SCREAMING_SNAKE_CASE : List[Any] = DebertaVaTokenizer(lowerCAmelCase__ , do_lower_case=lowerCAmelCase__ , split_by_punct=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : str = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Union[str, Any] = DebertaVaTokenizerFast(lowerCAmelCase__ , do_lower_case=lowerCAmelCase__ , split_by_punct=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : List[str] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
def __lowercase ( self : Union[str, Any] ):
"""simple docstring"""
# fmt: off
SCREAMING_SNAKE_CASE : Optional[int] = ''' \tHeLLo!how \n Are yoU? '''
SCREAMING_SNAKE_CASE : Optional[Any] = ['''▁''', '''<unk>''', '''e''', '''<unk>''', '''o''', '''!''', '''how''', '''▁''', '''<unk>''', '''re''', '''▁yo''', '''<unk>''', '''?''']
# fmt: on
SCREAMING_SNAKE_CASE : List[str] = DebertaVaTokenizer(lowerCAmelCase__ , do_lower_case=lowerCAmelCase__ , split_by_punct=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Any = DebertaVaTokenizerFast(lowerCAmelCase__ , do_lower_case=lowerCAmelCase__ , split_by_punct=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : List[Any] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
def __lowercase ( self : List[str] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer()
SCREAMING_SNAKE_CASE : Optional[int] = self.get_rust_tokenizer()
SCREAMING_SNAKE_CASE : Optional[int] = '''I was born in 92000, and this is falsé.'''
SCREAMING_SNAKE_CASE : Tuple = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) )
SCREAMING_SNAKE_CASE : List[str] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : List[Any] = tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : str = rust_tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Tuple = self.get_rust_tokenizer()
SCREAMING_SNAKE_CASE : List[Any] = tokenizer.encode(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Any = rust_tokenizer.encode(lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
def __lowercase ( self : List[str] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Tuple = '''This is a test'''
SCREAMING_SNAKE_CASE : List[str] = [13, 1, 43_98, 25, 21, 12_89]
SCREAMING_SNAKE_CASE : Tuple = ['''▁''', '''T''', '''his''', '''▁is''', '''▁a''', '''▁test''']
SCREAMING_SNAKE_CASE : Any = ['''▁''', '''<unk>''', '''his''', '''▁is''', '''▁a''', '''▁test''']
SCREAMING_SNAKE_CASE : List[str] = DebertaVaTokenizer(lowerCAmelCase__ , keep_accents=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : str = DebertaVaTokenizerFast(lowerCAmelCase__ , keep_accents=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : List[Any] = tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : List[Any] = tokenizer.tokenize(lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Any = tokenizer.convert_ids_to_tokens(lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : List[str] = rust_tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : str = rust_tokenizer.tokenize(lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Any = rust_tokenizer.convert_ids_to_tokens(lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
# fmt: off
SCREAMING_SNAKE_CASE : Optional[Any] = '''I was born in 92000, and this is falsé.'''
SCREAMING_SNAKE_CASE : int = [13, 1, 23, 3_86, 19, 5_61, 30_50, 15, 17, 48, 25, 82_56, 18, 1, 9]
SCREAMING_SNAKE_CASE : Dict = ['''▁''', '''I''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''é''', '''.''', ]
SCREAMING_SNAKE_CASE : List[Any] = ['''▁''', '''<unk>''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''.''', ]
# fmt: on
SCREAMING_SNAKE_CASE : List[Any] = tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Tuple = tokenizer.tokenize(lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.convert_ids_to_tokens(lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : int = rust_tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Tuple = rust_tokenizer.tokenize(lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Union[str, Any] = rust_tokenizer.convert_ids_to_tokens(lowerCAmelCase__ )
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
def __lowercase ( self : Any ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : str = DebertaVaTokenizer(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : List[str] = tokenizer.encode('''sequence builders''' )
SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.encode('''multi-sequence build''' )
SCREAMING_SNAKE_CASE : List[Any] = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Tuple = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__ , lowerCAmelCase__ )
self.assertEqual([tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] , lowerCAmelCase__ )
self.assertEqual(
[tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [tokenizer.sep_token_id] , lowerCAmelCase__ , )
@slow
def __lowercase ( self : Optional[Any] ):
"""simple docstring"""
# fmt: off
SCREAMING_SNAKE_CASE : str = {'''input_ids''': [[1, 3_98_67, 36, 1_93_90, 4_86, 27, 3_50_52, 8_14_36, 18, 6_06_85, 12_25, 7, 3_50_52, 8_14_36, 18, 93_67, 1_68_99, 18, 1_59_37, 53, 5_94, 7_73, 18, 1_62_87, 3_04_65, 36, 1_59_37, 6, 4_11_39, 38, 3_69_79, 6_07_63, 1_91, 6, 3_41_32, 99, 6, 5_05_38, 3_90, 4_32_30, 6, 3_41_32, 27_79, 2_08_50, 14, 6_99, 10_72, 11_94, 36, 3_82, 1_09_01, 53, 7, 6_99, 10_72, 20_84, 36, 2_04_22, 6_30, 53, 19, 1_05, 30_49, 18_96, 10_53, 1_68_99, 15_06, 11, 3_79_78, 42_43, 7, 12_37, 3_18_69, 2_00, 1_65_66, 6_54, 6, 3_50_52, 8_14_36, 7, 5_56_30, 1_35_93, 4, 2], [1, 26, 1_50_11, 13, 6_67, 8, 10_53, 18, 2_36_11, 12_37, 7_23_56, 1_28_20, 34, 10_41_34, 12_09, 35, 1_33_13, 66_27, 21, 2_02, 3_47, 7, 1_64, 23_99, 11, 46, 44_85, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 5, 12_32, 28_64, 1_57_85, 1_49_51, 1_05, 5, 85_81, 12_50, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''token_type_ids''': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=lowerCAmelCase__ , model_name='''microsoft/deberta-v2-xlarge''' , revision='''ad6e42c1532ddf3a15c39246b63f5559d558b670''' , )
| 464 | 1 |
import unittest
from datasets import load_dataset
from transformers import BloomTokenizerFast
from transformers.testing_utils import require_tokenizers
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class UpperCamelCase ( __a , unittest.TestCase ):
a__ :List[str] = None
a__ :int = BloomTokenizerFast
a__ :Any = BloomTokenizerFast
a__ :List[str] = True
a__ :str = False
a__ :Dict = '''tokenizer_file'''
a__ :Optional[int] = {'''bos_token''': '''<s>''', '''eos_token''': '''</s>''', '''unk_token''': '''<unk>''', '''pad_token''': '''<pad>'''}
def A_ (self ) -> Any:
super().setUp()
UpperCamelCase_ : List[Any] = BloomTokenizerFast.from_pretrained("""bigscience/tokenizer""" )
tokenizer.save_pretrained(self.tmpdirname )
def A_ (self , **__UpperCamelCase ) -> Optional[Any]:
kwargs.update(self.special_tokens_map )
return BloomTokenizerFast.from_pretrained(self.tmpdirname , **__UpperCamelCase )
def A_ (self ) -> List[Any]:
UpperCamelCase_ : List[str] = self.get_rust_tokenizer()
UpperCamelCase_ : int = ["""The quick brown fox</s>""", """jumps over the lazy dog</s>"""]
UpperCamelCase_ : Dict = [[2_175, 23_714, 73_173, 144_252, 2], [77, 132_619, 3_478, 368, 109_586, 35_433, 2]]
UpperCamelCase_ : Optional[Any] = tokenizer.batch_encode_plus(__UpperCamelCase )["""input_ids"""]
self.assertListEqual(__UpperCamelCase , __UpperCamelCase )
UpperCamelCase_ : Any = tokenizer.batch_decode(__UpperCamelCase )
self.assertListEqual(__UpperCamelCase , __UpperCamelCase )
def A_ (self , __UpperCamelCase=6 ) -> str:
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
UpperCamelCase_ : int = self.rust_tokenizer_class.from_pretrained(__UpperCamelCase , **__UpperCamelCase )
# tokenizer_r.pad_token = None # Hotfixing padding = None
# Simple input
UpperCamelCase_ : str = """This is a simple input"""
UpperCamelCase_ : Tuple = ["""This is a simple input 1""", """This is a simple input 2"""]
UpperCamelCase_ : List[Any] = ("""This is a simple input""", """This is a pair""")
UpperCamelCase_ : List[str] = [
("""This is a simple input 1""", """This is a simple input 2"""),
("""This is a simple pair 1""", """This is a simple pair 2"""),
]
# Simple input tests
try:
tokenizer_r.encode(__UpperCamelCase , max_length=__UpperCamelCase )
tokenizer_r.encode_plus(__UpperCamelCase , max_length=__UpperCamelCase )
tokenizer_r.batch_encode_plus(__UpperCamelCase , max_length=__UpperCamelCase )
tokenizer_r.encode(__UpperCamelCase , max_length=__UpperCamelCase )
tokenizer_r.batch_encode_plus(__UpperCamelCase , max_length=__UpperCamelCase )
except ValueError:
self.fail("""Bloom Tokenizer should be able to deal with padding""" )
UpperCamelCase_ : Dict = None # Hotfixing padding = None
self.assertRaises(__UpperCamelCase , tokenizer_r.encode , __UpperCamelCase , max_length=__UpperCamelCase , padding="""max_length""" )
# Simple input
self.assertRaises(__UpperCamelCase , tokenizer_r.encode_plus , __UpperCamelCase , max_length=__UpperCamelCase , padding="""max_length""" )
# Simple input
self.assertRaises(
__UpperCamelCase , tokenizer_r.batch_encode_plus , __UpperCamelCase , max_length=__UpperCamelCase , padding="""max_length""" , )
# Pair input
self.assertRaises(__UpperCamelCase , tokenizer_r.encode , __UpperCamelCase , max_length=__UpperCamelCase , padding="""max_length""" )
# Pair input
self.assertRaises(__UpperCamelCase , tokenizer_r.encode_plus , __UpperCamelCase , max_length=__UpperCamelCase , padding="""max_length""" )
# Pair input
self.assertRaises(
__UpperCamelCase , tokenizer_r.batch_encode_plus , __UpperCamelCase , max_length=__UpperCamelCase , padding="""max_length""" , )
def A_ (self ) -> Tuple:
UpperCamelCase_ : Optional[Any] = self.get_rust_tokenizer()
UpperCamelCase_ : List[str] = load_dataset("""xnli""" , """all_languages""" , split="""test""" , streaming=__UpperCamelCase )
UpperCamelCase_ : Dict = next(iter(__UpperCamelCase ) )["""premise"""] # pick up one data
UpperCamelCase_ : List[str] = list(sample_data.values() )
UpperCamelCase_ : int = list(map(tokenizer.encode , __UpperCamelCase ) )
UpperCamelCase_ : Tuple = [tokenizer.decode(__UpperCamelCase , clean_up_tokenization_spaces=__UpperCamelCase ) for x in output_tokens]
self.assertListEqual(__UpperCamelCase , __UpperCamelCase )
def A_ (self ) -> Tuple:
# The test has to be overriden because BLOOM uses ALiBi positional embeddings that does not have
# any sequence length constraints. This test of the parent class will fail since it relies on the
# maximum sequence length of the positoonal embeddings.
self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map ) , 1 )
self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values() )[0] ) , 1 )
| 635 | import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_funnel import FunnelTokenizer
SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE : Dict = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
SCREAMING_SNAKE_CASE : Dict = [
"small",
"small-base",
"medium",
"medium-base",
"intermediate",
"intermediate-base",
"large",
"large-base",
"xlarge",
"xlarge-base",
]
SCREAMING_SNAKE_CASE : int = {
"vocab_file": {
"funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt",
"funnel-transformer/small-base": "https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt",
"funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt",
"funnel-transformer/medium-base": (
"https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt"
),
"funnel-transformer/intermediate": (
"https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt"
),
"funnel-transformer/intermediate-base": (
"https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt"
),
"funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt",
"funnel-transformer/large-base": "https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt",
"funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt",
"funnel-transformer/xlarge-base": (
"https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt"
),
},
"tokenizer_file": {
"funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json",
"funnel-transformer/small-base": (
"https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json"
),
"funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json",
"funnel-transformer/medium-base": (
"https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json"
),
"funnel-transformer/intermediate": (
"https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json"
),
"funnel-transformer/intermediate-base": (
"https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json"
),
"funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json",
"funnel-transformer/large-base": (
"https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json"
),
"funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json",
"funnel-transformer/xlarge-base": (
"https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json"
),
},
}
SCREAMING_SNAKE_CASE : Any = {F'''funnel-transformer/{name}''': 512 for name in _model_names}
SCREAMING_SNAKE_CASE : Tuple = {F'''funnel-transformer/{name}''': {"do_lower_case": True} for name in _model_names}
class UpperCamelCase ( __a ):
a__ :Dict = VOCAB_FILES_NAMES
a__ :Dict = PRETRAINED_VOCAB_FILES_MAP
a__ :Dict = PRETRAINED_INIT_CONFIGURATION
a__ :str = FunnelTokenizer
a__ :List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
a__ :int = 2
def __init__(self , __UpperCamelCase=None , __UpperCamelCase=None , __UpperCamelCase=True , __UpperCamelCase="<unk>" , __UpperCamelCase="<sep>" , __UpperCamelCase="<pad>" , __UpperCamelCase="<cls>" , __UpperCamelCase="<mask>" , __UpperCamelCase="<s>" , __UpperCamelCase="</s>" , __UpperCamelCase=True , __UpperCamelCase=True , __UpperCamelCase=None , __UpperCamelCase="##" , **__UpperCamelCase , ) -> List[Any]:
super().__init__(
__UpperCamelCase , tokenizer_file=__UpperCamelCase , do_lower_case=__UpperCamelCase , unk_token=__UpperCamelCase , sep_token=__UpperCamelCase , pad_token=__UpperCamelCase , cls_token=__UpperCamelCase , mask_token=__UpperCamelCase , bos_token=__UpperCamelCase , eos_token=__UpperCamelCase , clean_text=__UpperCamelCase , tokenize_chinese_chars=__UpperCamelCase , strip_accents=__UpperCamelCase , wordpieces_prefix=__UpperCamelCase , **__UpperCamelCase , )
UpperCamelCase_ : List[str] = json.loads(self.backend_tokenizer.normalizer.__getstate__() )
if (
normalizer_state.get("""lowercase""" , __UpperCamelCase ) != do_lower_case
or normalizer_state.get("""strip_accents""" , __UpperCamelCase ) != strip_accents
or normalizer_state.get("""handle_chinese_chars""" , __UpperCamelCase ) != tokenize_chinese_chars
):
UpperCamelCase_ : List[Any] = getattr(__UpperCamelCase , normalizer_state.pop("""type""" ) )
UpperCamelCase_ : Union[str, Any] = do_lower_case
UpperCamelCase_ : Tuple = strip_accents
UpperCamelCase_ : Dict = tokenize_chinese_chars
UpperCamelCase_ : Union[str, Any] = normalizer_class(**__UpperCamelCase )
UpperCamelCase_ : Dict = do_lower_case
def A_ (self , __UpperCamelCase , __UpperCamelCase=None ) -> Dict:
UpperCamelCase_ : Any = [self.cls_token_id] + token_ids_a + [self.sep_token_id]
if token_ids_a:
output += token_ids_a + [self.sep_token_id]
return output
def A_ (self , __UpperCamelCase , __UpperCamelCase = None ) -> List[int]:
UpperCamelCase_ : Optional[Any] = [self.sep_token_id]
UpperCamelCase_ : Any = [self.cls_token_id]
if token_ids_a is None:
return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0]
return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def A_ (self , __UpperCamelCase , __UpperCamelCase = None ) -> Tuple[str]:
UpperCamelCase_ : int = self._tokenizer.model.save(__UpperCamelCase , name=__UpperCamelCase )
return tuple(__UpperCamelCase )
| 635 | 1 |
import argparse
import os
from transformers.utils import direct_transformers_import
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_task_guides.py
__snake_case : Optional[Any] = "src/transformers"
__snake_case : Optional[int] = "docs/source/en/tasks"
def _lowercase ( SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Optional[Any] ):
"""simple docstring"""
with open(SCREAMING_SNAKE_CASE_ , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f:
UpperCamelCase = f.readlines()
# Find the start prompt.
UpperCamelCase = 0
while not lines[start_index].startswith(SCREAMING_SNAKE_CASE_ ):
start_index += 1
start_index += 1
UpperCamelCase = start_index
while not lines[end_index].startswith(SCREAMING_SNAKE_CASE_ ):
end_index += 1
end_index -= 1
while len(lines[start_index] ) <= 1:
start_index += 1
while len(lines[end_index] ) <= 1:
end_index -= 1
end_index += 1
return "".join(lines[start_index:end_index] ), start_index, end_index, lines
# This is to make sure the transformers module imported is the one in the repo.
__snake_case : List[str] = direct_transformers_import(TRANSFORMERS_PATH)
__snake_case : Optional[int] = {
"asr.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES,
"audio_classification.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES,
"language_modeling.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,
"image_classification.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES,
"masked_language_modeling.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES,
"multiple_choice.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES,
"object_detection.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES,
"question_answering.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES,
"semantic_segmentation.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES,
"sequence_classification.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES,
"summarization.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,
"token_classification.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES,
"translation.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,
"video_classification.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES,
"document_question_answering.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES,
"monocular_depth_estimation.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES,
}
# This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any
# `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`).
__snake_case : Tuple = {
"summarization.md": ("nllb",),
"translation.md": ("nllb",),
}
def _lowercase ( SCREAMING_SNAKE_CASE_ : Union[str, Any] ):
"""simple docstring"""
UpperCamelCase = TASK_GUIDE_TO_MODELS[task_guide]
UpperCamelCase = SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(SCREAMING_SNAKE_CASE_ , set() )
UpperCamelCase = {
code: name
for code, name in transformers_module.MODEL_NAMES_MAPPING.items()
if (code in model_maping_names or code in special_model_types)
}
return ", ".join([f'[{name}](../model_doc/{code})' for code, name in model_names.items()] ) + "\n"
def _lowercase ( SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Dict=False ):
"""simple docstring"""
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = _find_text_in_file(
filename=os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , start_prompt="""<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->""" , end_prompt="""<!--End of the generated tip-->""" , )
UpperCamelCase = get_model_list_for_task(SCREAMING_SNAKE_CASE_ )
if current_list != new_list:
if overwrite:
with open(os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f:
f.writelines(lines[:start_index] + [new_list] + lines[end_index:] )
else:
raise ValueError(
f'The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`'
""" to fix this.""" )
if __name__ == "__main__":
__snake_case : Any = argparse.ArgumentParser()
parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.")
__snake_case : List[str] = parser.parse_args()
for task_guide in TASK_GUIDE_TO_MODELS.keys():
check_model_list_for_task(task_guide, args.fix_and_overwrite)
| 720 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__snake_case = logging.get_logger(__name__)
__snake_case = {
"microsoft/markuplm-base": "https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json",
"microsoft/markuplm-large": "https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json",
}
class UpperCAmelCase ( __snake_case ):
lowercase = """markuplm"""
def __init__( self : Optional[Any] , __magic_name__ : List[Any]=3_0_5_2_2 , __magic_name__ : int=7_6_8 , __magic_name__ : List[Any]=1_2 , __magic_name__ : List[Any]=1_2 , __magic_name__ : str=3_0_7_2 , __magic_name__ : Optional[int]="gelu" , __magic_name__ : Dict=0.1 , __magic_name__ : Optional[int]=0.1 , __magic_name__ : Any=5_1_2 , __magic_name__ : List[str]=2 , __magic_name__ : Dict=0.02 , __magic_name__ : List[str]=1e-12 , __magic_name__ : str=0 , __magic_name__ : List[str]=0 , __magic_name__ : Optional[Any]=2 , __magic_name__ : Dict=2_5_6 , __magic_name__ : Tuple=1_0_2_4 , __magic_name__ : Any=2_1_6 , __magic_name__ : str=1_0_0_1 , __magic_name__ : Dict=3_2 , __magic_name__ : Optional[int]=5_0 , __magic_name__ : List[Any]="absolute" , __magic_name__ : Any=True , __magic_name__ : Optional[Any]=None , **__magic_name__ : List[str] , ):
"""simple docstring"""
super().__init__(
pad_token_id=__magic_name__ , bos_token_id=__magic_name__ , eos_token_id=__magic_name__ , **__magic_name__ , )
UpperCamelCase = vocab_size
UpperCamelCase = hidden_size
UpperCamelCase = num_hidden_layers
UpperCamelCase = num_attention_heads
UpperCamelCase = hidden_act
UpperCamelCase = intermediate_size
UpperCamelCase = hidden_dropout_prob
UpperCamelCase = attention_probs_dropout_prob
UpperCamelCase = max_position_embeddings
UpperCamelCase = type_vocab_size
UpperCamelCase = initializer_range
UpperCamelCase = layer_norm_eps
UpperCamelCase = position_embedding_type
UpperCamelCase = use_cache
UpperCamelCase = classifier_dropout
# additional properties
UpperCamelCase = max_depth
UpperCamelCase = max_xpath_tag_unit_embeddings
UpperCamelCase = max_xpath_subs_unit_embeddings
UpperCamelCase = tag_pad_id
UpperCamelCase = subs_pad_id
UpperCamelCase = xpath_unit_hidden_size
| 181 | 0 |
import importlib
import os
import sys
# This is required to make the module import works (when the python process is running from the root of the repo)
sys.path.append(""".""")
def SCREAMING_SNAKE_CASE_ ( _snake_case :Tuple ) -> Dict:
_A = test_file.split(os.path.sep )
if components[0:2] != ["tests", "models"]:
raise ValueError(
'''`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got '''
F'''{test_file} instead.''' )
_A = components[-1]
if not test_fn.endswith('''py''' ):
raise ValueError(F'''`test_file` should be a python file. Got {test_fn} instead.''' )
if not test_fn.startswith('''test_modeling_''' ):
raise ValueError(
F'''`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.''' )
_A = components[:-1] + [test_fn.replace('''.py''' , '''''' )]
_A = '''.'''.join(_snake_case )
return test_module_path
def SCREAMING_SNAKE_CASE_ ( _snake_case :Union[str, Any] ) -> Any:
_A = get_module_path(_snake_case )
_A = importlib.import_module(_snake_case )
return test_module
def SCREAMING_SNAKE_CASE_ ( _snake_case :List[str] ) -> int:
_A = []
_A = get_test_module(_snake_case )
for attr in dir(_snake_case ):
if attr.endswith('''ModelTester''' ):
tester_classes.append(getattr(_snake_case , _snake_case ) )
# sort with class names
return sorted(_snake_case , key=lambda _snake_case : x.__name__ )
def SCREAMING_SNAKE_CASE_ ( _snake_case :int ) -> Union[str, Any]:
_A = []
_A = get_test_module(_snake_case )
for attr in dir(_snake_case ):
_A = getattr(_snake_case , _snake_case )
# (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking
# `all_model_classes` is not empty (which also excludes other special classes).
_A = getattr(_snake_case , '''all_model_classes''' , [] )
if len(_snake_case ) > 0:
test_classes.append(_snake_case )
# sort with class names
return sorted(_snake_case , key=lambda _snake_case : x.__name__ )
def SCREAMING_SNAKE_CASE_ ( _snake_case :Any ) -> Union[str, Any]:
_A = get_test_classes(_snake_case )
_A = set()
for test_class in test_classes:
model_classes.update(test_class.all_model_classes )
# sort with class names
return sorted(_snake_case , key=lambda _snake_case : x.__name__ )
def SCREAMING_SNAKE_CASE_ ( _snake_case :List[str] ) -> Optional[int]:
_A = test_class()
if hasattr(_snake_case , '''setUp''' ):
test.setUp()
_A = None
if hasattr(_snake_case , '''model_tester''' ):
# `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case.
if test.model_tester is not None:
_A = test.model_tester.__class__
return model_tester
def SCREAMING_SNAKE_CASE_ ( _snake_case :str , _snake_case :Tuple ) -> List[str]:
_A = get_test_classes(_snake_case )
_A = []
for test_class in test_classes:
if model_class in test_class.all_model_classes:
target_test_classes.append(_snake_case )
# sort with class names
return sorted(_snake_case , key=lambda _snake_case : x.__name__ )
def SCREAMING_SNAKE_CASE_ ( _snake_case :List[str] , _snake_case :List[Any] ) -> Dict:
_A = get_test_classes_for_model(_snake_case , _snake_case )
_A = []
for test_class in test_classes:
_A = get_model_tester_from_test_class(_snake_case )
if tester_class is not None:
tester_classes.append(_snake_case )
# sort with class names
return sorted(_snake_case , key=lambda _snake_case : x.__name__ )
def SCREAMING_SNAKE_CASE_ ( _snake_case :Optional[int] ) -> Tuple:
_A = get_test_classes(_snake_case )
_A = {test_class: get_model_tester_from_test_class(_snake_case ) for test_class in test_classes}
return test_tester_mapping
def SCREAMING_SNAKE_CASE_ ( _snake_case :str ) -> Any:
_A = get_model_classes(_snake_case )
_A = {
model_class: get_test_classes_for_model(_snake_case , _snake_case ) for model_class in model_classes
}
return model_test_mapping
def SCREAMING_SNAKE_CASE_ ( _snake_case :List[Any] ) -> int:
_A = get_model_classes(_snake_case )
_A = {
model_class: get_tester_classes_for_model(_snake_case , _snake_case ) for model_class in model_classes
}
return model_to_tester_mapping
def SCREAMING_SNAKE_CASE_ ( _snake_case :Optional[int] ) -> List[Any]:
if isinstance(_snake_case , _snake_case ):
return o
elif isinstance(_snake_case , _snake_case ):
return o.__name__
elif isinstance(_snake_case , (list, tuple) ):
return [to_json(_snake_case ) for x in o]
elif isinstance(_snake_case , _snake_case ):
return {to_json(_snake_case ): to_json(_snake_case ) for k, v in o.items()}
else:
return o
| 2 |
'''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,
)
UpperCamelCase_ = """\
Text data.
Second line of data."""
UpperCamelCase_ = """file"""
@pytest.fixture(scope="""session""" )
def _UpperCAmelCase ( _lowerCamelCase : str ) -> Union[str, Any]:
_lowerCAmelCase : Optional[Any] = tmp_path_factory.mktemp("""data""" ) / (FILE_PATH + """.zstd""")
_lowerCAmelCase : Tuple = bytes(_lowerCamelCase , """utf-8""" )
with zstd.open(_lowerCamelCase , """wb""" ) as f:
f.write(_lowerCamelCase )
return path
@pytest.fixture
def _UpperCAmelCase ( _lowerCamelCase : Dict ) -> Dict:
with open(os.path.join(tmpfs.local_root_dir , _lowerCamelCase ) , """w""" ) as f:
f.write(_lowerCamelCase )
return FILE_PATH
@pytest.mark.parametrize("""compression_format""" , ["""gzip""", """xz""", """zstd"""] )
def _UpperCAmelCase ( _lowerCamelCase : Dict , _lowerCamelCase : Dict , _lowerCamelCase : List[Any] , _lowerCamelCase : str , _lowerCamelCase : str , _lowerCamelCase : int ) -> Optional[Any]:
_lowerCAmelCase : Tuple = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path}
_lowerCAmelCase : Dict = input_paths[compression_format]
_lowerCAmelCase : List[Any] = tmp_path / """cache"""
_lowerCAmelCase : Optional[int] = DownloadConfig(cache_dir=_lowerCamelCase , extract_compressed_file=_lowerCamelCase )
_lowerCAmelCase : Optional[Any] = cached_path(_lowerCamelCase , download_config=_lowerCamelCase )
with open(_lowerCamelCase ) as f:
_lowerCAmelCase : Dict = f.read()
with open(_lowerCamelCase ) as f:
_lowerCAmelCase : 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 _UpperCAmelCase ( _lowerCamelCase : List[str] , _lowerCamelCase : Optional[int] , _lowerCamelCase : Dict , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Dict ) -> int:
_lowerCAmelCase : List[str] = """custom_cache"""
_lowerCAmelCase : Tuple = """custom_extracted_dir"""
_lowerCAmelCase : Dict = tmp_path / """custom_extracted_path"""
if default_extracted:
_lowerCAmelCase : int = ("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""")
else:
monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR""" , _lowerCamelCase )
monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH""" , str(_lowerCamelCase ) )
_lowerCAmelCase : int = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir)
_lowerCAmelCase : Optional[Any] = xz_file
_lowerCAmelCase : Any = (
DownloadConfig(extract_compressed_file=_lowerCamelCase )
if default_cache_dir
else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=_lowerCamelCase )
)
_lowerCAmelCase : List[Any] = cached_path(_lowerCamelCase , download_config=_lowerCamelCase )
assert Path(_lowerCamelCase ).parent.parts[-2:] == expected
def _UpperCAmelCase ( _lowerCamelCase : str ) -> Dict:
# absolute path
_lowerCAmelCase : List[Any] = str(Path(_lowerCamelCase ).resolve() )
assert cached_path(_lowerCamelCase ) == text_file
# relative path
_lowerCAmelCase : Any = str(Path(_lowerCamelCase ).resolve().relative_to(Path(os.getcwd() ) ) )
assert cached_path(_lowerCamelCase ) == text_file
def _UpperCAmelCase ( _lowerCamelCase : Dict ) -> Optional[int]:
# absolute path
_lowerCAmelCase : Optional[Any] = str(tmp_path.resolve() / """__missing_file__.txt""" )
with pytest.raises(_lowerCamelCase ):
cached_path(_lowerCamelCase )
# relative path
_lowerCAmelCase : int = """./__missing_file__.txt"""
with pytest.raises(_lowerCamelCase ):
cached_path(_lowerCamelCase )
def _UpperCAmelCase ( _lowerCamelCase : Union[str, Any] ) -> Union[str, Any]:
_lowerCAmelCase : str = get_from_cache(f'tmp://{tmpfs_file}' )
with open(_lowerCamelCase ) as f:
_lowerCAmelCase : Tuple = f.read()
assert output_file_content == FILE_CONTENT
@patch("""datasets.config.HF_DATASETS_OFFLINE""" , _lowerCamelCase )
def _UpperCAmelCase ( ) -> str:
with pytest.raises(_lowerCamelCase ):
cached_path("""https://huggingface.co""" )
@patch("""datasets.config.HF_DATASETS_OFFLINE""" , _lowerCamelCase )
def _UpperCAmelCase ( _lowerCamelCase : List[Any] ) -> str:
_lowerCAmelCase : int = tmp_path_factory.mktemp("""data""" ) / """file.html"""
with pytest.raises(_lowerCamelCase ):
http_get("""https://huggingface.co""" , temp_file=_lowerCamelCase )
with pytest.raises(_lowerCamelCase ):
http_head("""https://huggingface.co""" )
@patch("""datasets.config.HF_DATASETS_OFFLINE""" , _lowerCamelCase )
def _UpperCAmelCase ( _lowerCamelCase : List[Any] ) -> Optional[int]:
_lowerCAmelCase : Tuple = tmp_path_factory.mktemp("""data""" ) / """file.html"""
with pytest.raises(_lowerCamelCase ):
ftp_get("""ftp://huggingface.co""" , temp_file=_lowerCamelCase )
with pytest.raises(_lowerCamelCase ):
ftp_head("""ftp://huggingface.co""" )
@patch("""datasets.config.HF_DATASETS_OFFLINE""" , _lowerCamelCase )
def _UpperCAmelCase ( _lowerCamelCase : int ) -> Optional[int]:
_lowerCAmelCase : Dict = tmp_path_factory.mktemp("""data""" ) / """file.html"""
with pytest.raises(_lowerCamelCase ):
fsspec_get("""s3://huggingface.co""" , temp_file=_lowerCamelCase )
with pytest.raises(_lowerCamelCase ):
fsspec_head("""s3://huggingface.co""" )
| 384 | 0 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
_lowerCamelCase : Any = {
"configuration_swinv2": ["SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Swinv2Config"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase : Any = [
"SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST",
"Swinv2ForImageClassification",
"Swinv2ForMaskedImageModeling",
"Swinv2Model",
"Swinv2PreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_swinva import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinvaConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_swinva import (
SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST,
SwinvaForImageClassification,
SwinvaForMaskedImageModeling,
SwinvaModel,
SwinvaPreTrainedModel,
)
else:
import sys
_lowerCamelCase : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 703 |
'''simple docstring'''
import copy
import inspect
import unittest
from transformers import AutoBackbone
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import require_timm, require_torch, torch_device
from transformers.utils.import_utils import is_torch_available
from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor
if is_torch_available():
import torch
from transformers import TimmBackbone, TimmBackboneConfig
from ...test_pipeline_mixin import PipelineTesterMixin
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self : Optional[int] , UpperCamelCase__ : str , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : int=None , UpperCamelCase__ : Union[str, Any]="resnet50" , UpperCamelCase__ : Any=3 , UpperCamelCase__ : Union[str, Any]=3_2 , UpperCamelCase__ : Optional[int]=3 , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : List[Any]=True , ):
"""simple docstring"""
UpperCamelCase = parent
UpperCamelCase = out_indices if out_indices is not None else [4]
UpperCamelCase = stage_names
UpperCamelCase = out_features
UpperCamelCase = backbone
UpperCamelCase = batch_size
UpperCamelCase = image_size
UpperCamelCase = num_channels
UpperCamelCase = use_pretrained_backbone
UpperCamelCase = is_training
def A ( self : Optional[Any] ):
"""simple docstring"""
UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
UpperCamelCase = self.get_config()
return config, pixel_values
def A ( self : Any ):
"""simple docstring"""
return TimmBackboneConfig(
image_size=self.image_size , num_channels=self.num_channels , out_features=self.out_features , out_indices=self.out_indices , stage_names=self.stage_names , use_pretrained_backbone=self.use_pretrained_backbone , backbone=self.backbone , )
def A ( self : Any , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[Any] ):
"""simple docstring"""
UpperCamelCase = TimmBackbone(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
with torch.no_grad():
UpperCamelCase = model(UpperCamelCase__ )
self.parent.assertEqual(
result.feature_map[-1].shape , (self.batch_size, model.channels[-1], 1_4, 1_4) , )
def A ( self : Optional[int] ):
"""simple docstring"""
UpperCamelCase = self.prepare_config_and_inputs()
UpperCamelCase , UpperCamelCase = config_and_inputs
UpperCamelCase = {'pixel_values': pixel_values}
return config, inputs_dict
@require_torch
@require_timm
class SCREAMING_SNAKE_CASE ( _a , _a , _a , unittest.TestCase ):
"""simple docstring"""
_SCREAMING_SNAKE_CASE = (TimmBackbone,) if is_torch_available() else ()
_SCREAMING_SNAKE_CASE = {"""feature-extraction""": TimmBackbone} if is_torch_available() else {}
_SCREAMING_SNAKE_CASE = False
_SCREAMING_SNAKE_CASE = False
_SCREAMING_SNAKE_CASE = False
_SCREAMING_SNAKE_CASE = False
def A ( self : Any ):
"""simple docstring"""
UpperCamelCase = TimmBackboneModelTester(self )
UpperCamelCase = ConfigTester(self , config_class=UpperCamelCase__ , has_text_modality=UpperCamelCase__ )
def A ( self : str ):
"""simple docstring"""
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def A ( self : Union[str, Any] ):
"""simple docstring"""
UpperCamelCase = 'resnet18'
UpperCamelCase = 'microsoft/resnet-18'
UpperCamelCase = AutoBackbone.from_pretrained(UpperCamelCase__ , use_timm_backbone=UpperCamelCase__ )
UpperCamelCase = AutoBackbone.from_pretrained(UpperCamelCase__ )
self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) )
self.assertEqual(len(timm_model.stage_names ) , len(transformers_model.stage_names ) )
self.assertEqual(timm_model.channels , transformers_model.channels )
# Out indices are set to the last layer by default. For timm models, we don't know
# the number of layers in advance, so we set it to (-1,), whereas for transformers
# models, we set it to [len(stage_names) - 1] (kept for backward compatibility).
self.assertEqual(timm_model.out_indices , (-1,) )
self.assertEqual(transformers_model.out_indices , [len(timm_model.stage_names ) - 1] )
UpperCamelCase = AutoBackbone.from_pretrained(UpperCamelCase__ , use_timm_backbone=UpperCamelCase__ , out_indices=[1, 2, 3] )
UpperCamelCase = AutoBackbone.from_pretrained(UpperCamelCase__ , out_indices=[1, 2, 3] )
self.assertEqual(timm_model.out_indices , transformers_model.out_indices )
self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) )
self.assertEqual(timm_model.channels , transformers_model.channels )
@unittest.skip('TimmBackbone doesn\'t support feed forward chunking' )
def A ( self : Union[str, Any] ):
"""simple docstring"""
pass
@unittest.skip('TimmBackbone doesn\'t have num_hidden_layers attribute' )
def A ( self : Dict ):
"""simple docstring"""
pass
@unittest.skip('TimmBackbone initialization is managed on the timm side' )
def A ( self : List[Any] ):
"""simple docstring"""
pass
@unittest.skip('TimmBackbone models doesn\'t have inputs_embeds' )
def A ( self : int ):
"""simple docstring"""
pass
@unittest.skip('TimmBackbone models doesn\'t have inputs_embeds' )
def A ( self : Optional[Any] ):
"""simple docstring"""
pass
@unittest.skip('TimmBackbone model cannot be created without specifying a backbone checkpoint' )
def A ( self : int ):
"""simple docstring"""
pass
@unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone' )
def A ( self : Dict ):
"""simple docstring"""
pass
@unittest.skip('model weights aren\'t tied in TimmBackbone.' )
def A ( self : Optional[int] ):
"""simple docstring"""
pass
@unittest.skip('model weights aren\'t tied in TimmBackbone.' )
def A ( self : str ):
"""simple docstring"""
pass
@unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone' )
def A ( self : Optional[Any] ):
"""simple docstring"""
pass
@unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone' )
def A ( self : Optional[Any] ):
"""simple docstring"""
pass
@unittest.skip('TimmBackbone doesn\'t have hidden size info in its configuration.' )
def A ( self : str ):
"""simple docstring"""
pass
@unittest.skip('TimmBackbone doesn\'t support output_attentions.' )
def A ( self : Any ):
"""simple docstring"""
pass
@unittest.skip('Safetensors is not supported by timm.' )
def A ( self : int ):
"""simple docstring"""
pass
@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' )
def A ( self : Union[str, Any] ):
"""simple docstring"""
pass
def A ( self : Any ):
"""simple docstring"""
UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase = model_class(UpperCamelCase__ )
UpperCamelCase = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
UpperCamelCase = [*signature.parameters.keys()]
UpperCamelCase = ['pixel_values']
self.assertListEqual(arg_names[:1] , UpperCamelCase__ )
def A ( self : int ):
"""simple docstring"""
UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
UpperCamelCase = True
UpperCamelCase = self.has_attentions
# no need to test all models as different heads yield the same functionality
UpperCamelCase = self.all_model_classes[0]
UpperCamelCase = model_class(UpperCamelCase__ )
model.to(UpperCamelCase__ )
UpperCamelCase = self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ )
UpperCamelCase = model(**UpperCamelCase__ )
UpperCamelCase = outputs[0][-1]
# Encoder-/Decoder-only models
UpperCamelCase = outputs.hidden_states[0]
hidden_states.retain_grad()
if self.has_attentions:
UpperCamelCase = outputs.attentions[0]
attentions.retain_grad()
output.flatten()[0].backward(retain_graph=UpperCamelCase__ )
self.assertIsNotNone(hidden_states.grad )
if self.has_attentions:
self.assertIsNotNone(attentions.grad )
def A ( self : Optional[int] ):
"""simple docstring"""
UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase = model_class(UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
UpperCamelCase = model(**UpperCamelCase__ )
self.assertEqual(len(result.feature_maps ) , len(config.out_indices ) )
self.assertEqual(len(model.channels ) , len(config.out_indices ) )
# Check output of last stage is taken if out_features=None, out_indices=None
UpperCamelCase = copy.deepcopy(UpperCamelCase__ )
UpperCamelCase = None
UpperCamelCase = model_class(UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
UpperCamelCase = model(**UpperCamelCase__ )
self.assertEqual(len(result.feature_maps ) , 1 )
self.assertEqual(len(model.channels ) , 1 )
# Check backbone can be initialized with fresh weights
UpperCamelCase = copy.deepcopy(UpperCamelCase__ )
UpperCamelCase = False
UpperCamelCase = model_class(UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
UpperCamelCase = model(**UpperCamelCase__ )
| 324 | 0 |
'''simple docstring'''
import argparse
import collections
import json
import os
import re
import string
import sys
import numpy as np
lowerCAmelCase :Union[str, Any] = re.compile(r'''\b(a|an|the)\b''', re.UNICODE)
lowerCAmelCase :Union[str, Any] = None
def lowerCamelCase ( ):
"""simple docstring"""
__magic_name__ : str = argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.' )
parser.add_argument('data_file' , metavar='data.json' , help='Input data JSON file.' )
parser.add_argument('pred_file' , metavar='pred.json' , help='Model predictions.' )
parser.add_argument(
'--out-file' , '-o' , metavar='eval.json' , help='Write accuracy metrics to file (default is stdout).' )
parser.add_argument(
'--na-prob-file' , '-n' , metavar='na_prob.json' , help='Model estimates of probability of no answer.' )
parser.add_argument(
'--na-prob-thresh' , '-t' , type=lowerCAmelCase , default=1.0 , help='Predict "" if no-answer probability exceeds this (default = 1.0).' , )
parser.add_argument(
'--out-image-dir' , '-p' , metavar='out_images' , default=lowerCAmelCase , help='Save precision-recall curves to directory.' )
parser.add_argument('--verbose' , '-v' , action='store_true' )
if len(sys.argv ) == 1:
parser.print_help()
sys.exit(1 )
return parser.parse_args()
def lowerCamelCase ( lowerCAmelCase : Any ):
"""simple docstring"""
__magic_name__ : Any = {}
for article in dataset:
for p in article["paragraphs"]:
for qa in p["qas"]:
__magic_name__ : List[str] = bool(qa['answers']['text'] )
return qid_to_has_ans
def lowerCamelCase ( lowerCAmelCase : List[Any] ):
"""simple docstring"""
def remove_articles(lowerCAmelCase : str ):
return ARTICLES_REGEX.sub(' ' , lowerCAmelCase )
def white_space_fix(lowerCAmelCase : List[str] ):
return " ".join(text.split() )
def remove_punc(lowerCAmelCase : List[Any] ):
__magic_name__ : Optional[Any] = set(string.punctuation )
return "".join(ch for ch in text if ch not in exclude )
def lower(lowerCAmelCase : str ):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(lowerCAmelCase ) ) ) )
def lowerCamelCase ( lowerCAmelCase : Optional[int] ):
"""simple docstring"""
if not s:
return []
return normalize_answer(lowerCAmelCase ).split()
def lowerCamelCase ( lowerCAmelCase : Union[str, Any] , lowerCAmelCase : str ):
"""simple docstring"""
return int(normalize_answer(lowerCAmelCase ) == normalize_answer(lowerCAmelCase ) )
def lowerCamelCase ( lowerCAmelCase : str , lowerCAmelCase : str ):
"""simple docstring"""
__magic_name__ : Optional[Any] = get_tokens(lowerCAmelCase )
__magic_name__ : Optional[int] = get_tokens(lowerCAmelCase )
__magic_name__ : List[Any] = collections.Counter(lowerCAmelCase ) & collections.Counter(lowerCAmelCase )
__magic_name__ : str = sum(common.values() )
if len(lowerCAmelCase ) == 0 or len(lowerCAmelCase ) == 0:
# If either is no-answer, then F1 is 1 if they agree, 0 otherwise
return int(gold_toks == pred_toks )
if num_same == 0:
return 0
__magic_name__ : Any = 1.0 * num_same / len(lowerCAmelCase )
__magic_name__ : Tuple = 1.0 * num_same / len(lowerCAmelCase )
__magic_name__ : str = (2 * precision * recall) / (precision + recall)
return fa
def lowerCamelCase ( lowerCAmelCase : Any , lowerCAmelCase : Any ):
"""simple docstring"""
__magic_name__ : Dict = {}
__magic_name__ : int = {}
for article in dataset:
for p in article["paragraphs"]:
for qa in p["qas"]:
__magic_name__ : Dict = qa['id']
__magic_name__ : List[Any] = [t for t in qa['answers']['text'] if normalize_answer(lowerCAmelCase )]
if not gold_answers:
# For unanswerable questions, only correct answer is empty string
__magic_name__ : List[str] = ['']
if qid not in preds:
print(f'Missing prediction for {qid}' )
continue
__magic_name__ : str = preds[qid]
# Take max over all gold answers
__magic_name__ : Tuple = max(compute_exact(lowerCAmelCase , lowerCAmelCase ) for a in gold_answers )
__magic_name__ : List[str] = max(compute_fa(lowerCAmelCase , lowerCAmelCase ) for a in gold_answers )
return exact_scores, fa_scores
def lowerCamelCase ( lowerCAmelCase : Tuple , lowerCAmelCase : List[Any] , lowerCAmelCase : List[Any] , lowerCAmelCase : Union[str, Any] ):
"""simple docstring"""
__magic_name__ : str = {}
for qid, s in scores.items():
__magic_name__ : List[Any] = na_probs[qid] > na_prob_thresh
if pred_na:
__magic_name__ : Optional[Any] = float(not qid_to_has_ans[qid] )
else:
__magic_name__ : int = s
return new_scores
def lowerCamelCase ( lowerCAmelCase : Optional[Any] , lowerCAmelCase : Dict , lowerCAmelCase : Any=None ):
"""simple docstring"""
if not qid_list:
__magic_name__ : Tuple = len(lowerCAmelCase )
return collections.OrderedDict(
[
('exact', 100.0 * sum(exact_scores.values() ) / total),
('f1', 100.0 * sum(fa_scores.values() ) / total),
('total', total),
] )
else:
__magic_name__ : Dict = len(lowerCAmelCase )
return collections.OrderedDict(
[
('exact', 100.0 * sum(exact_scores[k] for k in qid_list ) / total),
('f1', 100.0 * sum(fa_scores[k] for k in qid_list ) / total),
('total', total),
] )
def lowerCamelCase ( lowerCAmelCase : Any , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Tuple ):
"""simple docstring"""
for k in new_eval:
__magic_name__ : int = new_eval[k]
def lowerCamelCase ( lowerCAmelCase : List[str] , lowerCAmelCase : str , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Any ):
"""simple docstring"""
plt.step(lowerCAmelCase , lowerCAmelCase , color='b' , alpha=0.2 , where='post' )
plt.fill_between(lowerCAmelCase , lowerCAmelCase , step='post' , alpha=0.2 , color='b' )
plt.xlabel('Recall' )
plt.ylabel('Precision' )
plt.xlim([0.0, 1.05] )
plt.ylim([0.0, 1.05] )
plt.title(lowerCAmelCase )
plt.savefig(lowerCAmelCase )
plt.clf()
def lowerCamelCase ( lowerCAmelCase : int , lowerCAmelCase : List[Any] , lowerCAmelCase : List[str] , lowerCAmelCase : List[str] , lowerCAmelCase : Union[str, Any]=None , lowerCAmelCase : List[str]=None ):
"""simple docstring"""
__magic_name__ : Tuple = sorted(lowerCAmelCase , key=lambda lowerCAmelCase : na_probs[k] )
__magic_name__ : Dict = 0.0
__magic_name__ : int = 1.0
__magic_name__ : List[str] = 0.0
__magic_name__ : str = [1.0]
__magic_name__ : str = [0.0]
__magic_name__ : Dict = 0.0
for i, qid in enumerate(lowerCAmelCase ):
if qid_to_has_ans[qid]:
true_pos += scores[qid]
__magic_name__ : str = true_pos / float(i + 1 )
__magic_name__ : int = true_pos / float(lowerCAmelCase )
if i == len(lowerCAmelCase ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]:
# i.e., if we can put a threshold after this point
avg_prec += cur_p * (cur_r - recalls[-1])
precisions.append(lowerCAmelCase )
recalls.append(lowerCAmelCase )
if out_image:
plot_pr_curve(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )
return {"ap": 100.0 * avg_prec}
def lowerCamelCase ( lowerCAmelCase : str , lowerCAmelCase : Tuple , lowerCAmelCase : Dict , lowerCAmelCase : Any , lowerCAmelCase : Optional[Any] , lowerCAmelCase : str ):
"""simple docstring"""
if out_image_dir and not os.path.exists(lowerCAmelCase ):
os.makedirs(lowerCAmelCase )
__magic_name__ : List[Any] = sum(1 for v in qid_to_has_ans.values() if v )
if num_true_pos == 0:
return
__magic_name__ : str = make_precision_recall_eval(
lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , out_image=os.path.join(lowerCAmelCase , 'pr_exact.png' ) , title='Precision-Recall curve for Exact Match score' , )
__magic_name__ : str = make_precision_recall_eval(
lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , out_image=os.path.join(lowerCAmelCase , 'pr_f1.png' ) , title='Precision-Recall curve for F1 score' , )
__magic_name__ : Tuple = {k: float(lowerCAmelCase ) for k, v in qid_to_has_ans.items()}
__magic_name__ : Dict = make_precision_recall_eval(
lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , out_image=os.path.join(lowerCAmelCase , 'pr_oracle.png' ) , title='Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)' , )
merge_eval(lowerCAmelCase , lowerCAmelCase , 'pr_exact' )
merge_eval(lowerCAmelCase , lowerCAmelCase , 'pr_f1' )
merge_eval(lowerCAmelCase , lowerCAmelCase , 'pr_oracle' )
def lowerCamelCase ( lowerCAmelCase : Optional[int] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : List[Any] , lowerCAmelCase : str ):
"""simple docstring"""
if not qid_list:
return
__magic_name__ : Dict = [na_probs[k] for k in qid_list]
__magic_name__ : Optional[Any] = np.ones_like(lowerCAmelCase ) / float(len(lowerCAmelCase ) )
plt.hist(lowerCAmelCase , weights=lowerCAmelCase , bins=20 , range=(0.0, 1.0) )
plt.xlabel('Model probability of no-answer' )
plt.ylabel('Proportion of dataset' )
plt.title(f'Histogram of no-answer probability: {name}' )
plt.savefig(os.path.join(lowerCAmelCase , f'na_prob_hist_{name}.png' ) )
plt.clf()
def lowerCamelCase ( lowerCAmelCase : Union[str, Any] , lowerCAmelCase : str , lowerCAmelCase : Optional[int] , lowerCAmelCase : int ):
"""simple docstring"""
__magic_name__ : List[Any] = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] )
__magic_name__ : Union[str, Any] = num_no_ans
__magic_name__ : Any = cur_score
__magic_name__ : Union[str, Any] = 0.0
__magic_name__ : int = sorted(lowerCAmelCase , key=lambda lowerCAmelCase : na_probs[k] )
for i, qid in enumerate(lowerCAmelCase ):
if qid not in scores:
continue
if qid_to_has_ans[qid]:
__magic_name__ : List[str] = scores[qid]
else:
if preds[qid]:
__magic_name__ : str = -1
else:
__magic_name__ : Optional[int] = 0
cur_score += diff
if cur_score > best_score:
__magic_name__ : int = cur_score
__magic_name__ : List[str] = na_probs[qid]
return 100.0 * best_score / len(lowerCAmelCase ), best_thresh
def lowerCamelCase ( lowerCAmelCase : str , lowerCAmelCase : Tuple , lowerCAmelCase : Dict , lowerCAmelCase : int , lowerCAmelCase : Dict , lowerCAmelCase : Optional[Any] ):
"""simple docstring"""
__magic_name__ , __magic_name__ : int = find_best_thresh(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )
__magic_name__ , __magic_name__ : Tuple = find_best_thresh(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )
__magic_name__ : Tuple = best_exact
__magic_name__ : Optional[Any] = exact_thresh
__magic_name__ : Tuple = best_fa
__magic_name__ : str = fa_thresh
def lowerCamelCase ( ):
"""simple docstring"""
with open(OPTS.data_file ) as f:
__magic_name__ : List[str] = json.load(lowerCAmelCase )
__magic_name__ : List[Any] = dataset_json['data']
with open(OPTS.pred_file ) as f:
__magic_name__ : Optional[int] = json.load(lowerCAmelCase )
if OPTS.na_prob_file:
with open(OPTS.na_prob_file ) as f:
__magic_name__ : Union[str, Any] = json.load(lowerCAmelCase )
else:
__magic_name__ : Any = {k: 0.0 for k in preds}
__magic_name__ : Tuple = make_qid_to_has_ans(lowerCAmelCase ) # maps qid to True/False
__magic_name__ : Tuple = [k for k, v in qid_to_has_ans.items() if v]
__magic_name__ : List[str] = [k for k, v in qid_to_has_ans.items() if not v]
__magic_name__ , __magic_name__ : Union[str, Any] = get_raw_scores(lowerCAmelCase , lowerCAmelCase )
__magic_name__ : Dict = apply_no_ans_threshold(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , OPTS.na_prob_thresh )
__magic_name__ : Union[str, Any] = apply_no_ans_threshold(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , OPTS.na_prob_thresh )
__magic_name__ : int = make_eval_dict(lowerCAmelCase , lowerCAmelCase )
if has_ans_qids:
__magic_name__ : Dict = make_eval_dict(lowerCAmelCase , lowerCAmelCase , qid_list=lowerCAmelCase )
merge_eval(lowerCAmelCase , lowerCAmelCase , 'HasAns' )
if no_ans_qids:
__magic_name__ : Optional[int] = make_eval_dict(lowerCAmelCase , lowerCAmelCase , qid_list=lowerCAmelCase )
merge_eval(lowerCAmelCase , lowerCAmelCase , 'NoAns' )
if OPTS.na_prob_file:
find_all_best_thresh(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )
if OPTS.na_prob_file and OPTS.out_image_dir:
run_precision_recall_analysis(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , OPTS.out_image_dir )
histogram_na_prob(lowerCAmelCase , lowerCAmelCase , OPTS.out_image_dir , 'hasAns' )
histogram_na_prob(lowerCAmelCase , lowerCAmelCase , OPTS.out_image_dir , 'noAns' )
if OPTS.out_file:
with open(OPTS.out_file , 'w' ) as f:
json.dump(lowerCAmelCase , lowerCAmelCase )
else:
print(json.dumps(lowerCAmelCase , indent=2 ) )
if __name__ == "__main__":
lowerCAmelCase :List[str] = parse_args()
if OPTS.out_image_dir:
import matplotlib
matplotlib.use('''Agg''')
import matplotlib.pyplot as plt
main() | 561 |
'''simple docstring'''
import json
import sys
import tempfile
import unittest
from pathlib import Path
import transformers
from transformers import (
CONFIG_MAPPING,
FEATURE_EXTRACTOR_MAPPING,
AutoConfig,
AutoFeatureExtractor,
WavaVecaConfig,
WavaVecaFeatureExtractor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir
sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils'''))
from test_module.custom_configuration import CustomConfig # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402
lowerCAmelCase :Optional[int] = get_tests_dir('''fixtures''')
lowerCAmelCase :Any = get_tests_dir('''fixtures/dummy_feature_extractor_config.json''')
lowerCAmelCase :Tuple = get_tests_dir('''fixtures/dummy-config.json''')
class _lowerCamelCase ( unittest.TestCase ):
'''simple docstring'''
def __lowerCAmelCase ( self : Union[str, Any] ) -> int:
__magic_name__ : str = 0
def __lowerCAmelCase ( self : int ) -> Tuple:
__magic_name__ : List[str] = AutoFeatureExtractor.from_pretrained('facebook/wav2vec2-base-960h' )
self.assertIsInstance(_A , _A )
def __lowerCAmelCase ( self : Tuple ) -> List[Any]:
__magic_name__ : List[str] = AutoFeatureExtractor.from_pretrained(_A )
self.assertIsInstance(_A , _A )
def __lowerCAmelCase ( self : Tuple ) -> Optional[Any]:
with tempfile.TemporaryDirectory() as tmpdirname:
__magic_name__ : Union[str, Any] = WavaVecaConfig()
# remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
__magic_name__ : Dict = AutoFeatureExtractor.from_pretrained(_A ).to_dict()
config_dict.pop('feature_extractor_type' )
__magic_name__ : int = WavaVecaFeatureExtractor(**_A )
# save in new folder
model_config.save_pretrained(_A )
config.save_pretrained(_A )
__magic_name__ : Union[str, Any] = AutoFeatureExtractor.from_pretrained(_A )
# make sure private variable is not incorrectly saved
__magic_name__ : List[str] = json.loads(config.to_json_string() )
self.assertTrue('_processor_class' not in dict_as_saved )
self.assertIsInstance(_A , _A )
def __lowerCAmelCase ( self : int ) -> Union[str, Any]:
__magic_name__ : Tuple = AutoFeatureExtractor.from_pretrained(_A )
self.assertIsInstance(_A , _A )
def __lowerCAmelCase ( self : List[str] ) -> Optional[int]:
with self.assertRaisesRegex(
_A , 'bert-base is not a local folder and is not a valid model identifier' ):
__magic_name__ : str = AutoFeatureExtractor.from_pretrained('bert-base' )
def __lowerCAmelCase ( self : Any ) -> Tuple:
with self.assertRaisesRegex(
_A , R'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)' ):
__magic_name__ : Tuple = AutoFeatureExtractor.from_pretrained(_A , revision='aaaaaa' )
def __lowerCAmelCase ( self : Dict ) -> str:
with self.assertRaisesRegex(
_A , 'hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.' , ):
__magic_name__ : Union[str, Any] = AutoFeatureExtractor.from_pretrained('hf-internal-testing/config-no-model' )
def __lowerCAmelCase ( self : Optional[int] ) -> Union[str, Any]:
# If remote code is not set, we will time out when asking whether to load the model.
with self.assertRaises(_A ):
__magic_name__ : Dict = AutoFeatureExtractor.from_pretrained(
'hf-internal-testing/test_dynamic_feature_extractor' )
# If remote code is disabled, we can't load this config.
with self.assertRaises(_A ):
__magic_name__ : Optional[Any] = AutoFeatureExtractor.from_pretrained(
'hf-internal-testing/test_dynamic_feature_extractor' , trust_remote_code=_A )
__magic_name__ : List[Any] = AutoFeatureExtractor.from_pretrained(
'hf-internal-testing/test_dynamic_feature_extractor' , trust_remote_code=_A )
self.assertEqual(feature_extractor.__class__.__name__ , 'NewFeatureExtractor' )
# Test feature extractor can be reloaded.
with tempfile.TemporaryDirectory() as tmp_dir:
feature_extractor.save_pretrained(_A )
__magic_name__ : List[Any] = AutoFeatureExtractor.from_pretrained(_A , trust_remote_code=_A )
self.assertEqual(reloaded_feature_extractor.__class__.__name__ , 'NewFeatureExtractor' )
def __lowerCAmelCase ( self : str ) -> Tuple:
try:
AutoConfig.register('custom' , _A )
AutoFeatureExtractor.register(_A , _A )
# Trying to register something existing in the Transformers library will raise an error
with self.assertRaises(_A ):
AutoFeatureExtractor.register(_A , _A )
# Now that the config is registered, it can be used as any other config with the auto-API
__magic_name__ : str = CustomFeatureExtractor.from_pretrained(_A )
with tempfile.TemporaryDirectory() as tmp_dir:
feature_extractor.save_pretrained(_A )
__magic_name__ : List[Any] = AutoFeatureExtractor.from_pretrained(_A )
self.assertIsInstance(_A , _A )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
def __lowerCAmelCase ( self : Optional[Any] ) -> Dict:
class _lowerCamelCase ( lowercase__ ):
'''simple docstring'''
A_ : Any = True
try:
AutoConfig.register('custom' , _A )
AutoFeatureExtractor.register(_A , _A )
# If remote code is not set, the default is to use local
__magic_name__ : Optional[Any] = AutoFeatureExtractor.from_pretrained(
'hf-internal-testing/test_dynamic_feature_extractor' )
self.assertEqual(feature_extractor.__class__.__name__ , 'NewFeatureExtractor' )
self.assertTrue(feature_extractor.is_local )
# If remote code is disabled, we load the local one.
__magic_name__ : str = AutoFeatureExtractor.from_pretrained(
'hf-internal-testing/test_dynamic_feature_extractor' , trust_remote_code=_A )
self.assertEqual(feature_extractor.__class__.__name__ , 'NewFeatureExtractor' )
self.assertTrue(feature_extractor.is_local )
# If remote is enabled, we load from the Hub
__magic_name__ : Tuple = AutoFeatureExtractor.from_pretrained(
'hf-internal-testing/test_dynamic_feature_extractor' , trust_remote_code=_A )
self.assertEqual(feature_extractor.__class__.__name__ , 'NewFeatureExtractor' )
self.assertTrue(not hasattr(_A , 'is_local' ) )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] | 561 | 1 |
"""simple docstring"""
import argparse
import json
from collections import OrderedDict
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor
from transformers.utils import logging
logging.set_verbosity_info()
UpperCamelCase__ = logging.get_logger(__name__)
def UpperCAmelCase ( lowercase_ : Optional[int] , lowercase_ : Optional[int] , lowercase_ : Optional[int] , lowercase_ : Union[str, Any] ):
_lowerCAmelCase:Any = original_name.split('''.''' )[0]
_lowerCAmelCase:Union[str, Any] = key.split('''.''' )
_lowerCAmelCase:Any = int(key_list[key_list.index(lowercase_ ) - 2] )
_lowerCAmelCase:Any = int(key_list[key_list.index(lowercase_ ) - 1] )
_lowerCAmelCase:str = orig_block_num - offset
_lowerCAmelCase:Dict = key.replace(F'{orig_block_num}.{layer_num}.{original_name}' , F'block.{new_block_num}.{layer_num}.{new_name}' )
return key
def UpperCAmelCase ( lowercase_ : Dict ):
_lowerCAmelCase:Optional[int] = OrderedDict()
_lowerCAmelCase:str = 0, 0
for key, value in state_dict.items():
if key.startswith('''network''' ):
_lowerCAmelCase:Dict = key.replace('''network''' , '''poolformer.encoder''' )
if "proj" in key:
# Works for the first embedding as well as the internal embedding layers
if key.endswith('''bias''' ) and "patch_embed" not in key:
patch_emb_offset += 1
_lowerCAmelCase:Optional[Any] = key[: key.find('''proj''' )]
_lowerCAmelCase:Optional[int] = key.replace(lowercase_ , F'patch_embeddings.{total_embed_found}.' )
_lowerCAmelCase:Tuple = key.replace('''proj''' , '''projection''' )
if key.endswith('''bias''' ):
total_embed_found += 1
if "patch_embeddings" in key:
_lowerCAmelCase:Union[str, Any] = '''poolformer.encoder.''' + key
if "mlp.fc1" in key:
_lowerCAmelCase:int = replace_key_with_offset(lowercase_ , lowercase_ , '''mlp.fc1''' , '''output.conv1''' )
if "mlp.fc2" in key:
_lowerCAmelCase:List[Any] = replace_key_with_offset(lowercase_ , lowercase_ , '''mlp.fc2''' , '''output.conv2''' )
if "norm1" in key:
_lowerCAmelCase:Union[str, Any] = replace_key_with_offset(lowercase_ , lowercase_ , '''norm1''' , '''before_norm''' )
if "norm2" in key:
_lowerCAmelCase:int = replace_key_with_offset(lowercase_ , lowercase_ , '''norm2''' , '''after_norm''' )
if "layer_scale_1" in key:
_lowerCAmelCase:Union[str, Any] = replace_key_with_offset(lowercase_ , lowercase_ , '''layer_scale_1''' , '''layer_scale_1''' )
if "layer_scale_2" in key:
_lowerCAmelCase:Optional[Any] = replace_key_with_offset(lowercase_ , lowercase_ , '''layer_scale_2''' , '''layer_scale_2''' )
if "head" in key:
_lowerCAmelCase:List[Any] = key.replace('''head''' , '''classifier''' )
_lowerCAmelCase:List[Any] = value
return new_state_dict
def UpperCAmelCase ( ):
_lowerCAmelCase:Tuple = '''http://images.cocodataset.org/val2017/000000039769.jpg'''
_lowerCAmelCase:List[Any] = Image.open(requests.get(lowercase_ , stream=lowercase_ ).raw )
return image
@torch.no_grad()
def UpperCAmelCase ( lowercase_ : Dict , lowercase_ : str , lowercase_ : int ):
_lowerCAmelCase:Optional[Any] = PoolFormerConfig()
# set attributes based on model_name
_lowerCAmelCase:List[Any] = '''huggingface/label-files'''
_lowerCAmelCase:Dict = model_name[-3:]
_lowerCAmelCase:int = 1000
_lowerCAmelCase:int = '''imagenet-1k-id2label.json'''
_lowerCAmelCase:str = (1, 1000)
# set config attributes
_lowerCAmelCase:Optional[int] = json.load(open(hf_hub_download(lowercase_ , lowercase_ , repo_type='''dataset''' ) , '''r''' ) )
_lowerCAmelCase:int = {int(lowercase_ ): v for k, v in idalabel.items()}
_lowerCAmelCase:Optional[int] = idalabel
_lowerCAmelCase:Any = {v: k for k, v in idalabel.items()}
if size == "s12":
_lowerCAmelCase:str = [2, 2, 6, 2]
_lowerCAmelCase:str = [64, 128, 320, 512]
_lowerCAmelCase:Dict = 4.0
_lowerCAmelCase:int = 0.9
elif size == "s24":
_lowerCAmelCase:List[Any] = [4, 4, 12, 4]
_lowerCAmelCase:Optional[Any] = [64, 128, 320, 512]
_lowerCAmelCase:List[str] = 4.0
_lowerCAmelCase:List[Any] = 0.9
elif size == "s36":
_lowerCAmelCase:Optional[int] = [6, 6, 18, 6]
_lowerCAmelCase:List[str] = [64, 128, 320, 512]
_lowerCAmelCase:List[str] = 4.0
_lowerCAmelCase:Tuple = 1e-6
_lowerCAmelCase:str = 0.9
elif size == "m36":
_lowerCAmelCase:Any = [6, 6, 18, 6]
_lowerCAmelCase:Optional[int] = [96, 192, 384, 768]
_lowerCAmelCase:Tuple = 4.0
_lowerCAmelCase:Any = 1e-6
_lowerCAmelCase:Tuple = 0.95
elif size == "m48":
_lowerCAmelCase:int = [8, 8, 24, 8]
_lowerCAmelCase:Union[str, Any] = [96, 192, 384, 768]
_lowerCAmelCase:Union[str, Any] = 4.0
_lowerCAmelCase:Tuple = 1e-6
_lowerCAmelCase:int = 0.95
else:
raise ValueError(F'Size {size} not supported' )
# load image processor
_lowerCAmelCase:Optional[Any] = PoolFormerImageProcessor(crop_pct=lowercase_ )
# Prepare image
_lowerCAmelCase:int = prepare_img()
_lowerCAmelCase:int = image_processor(images=lowercase_ , return_tensors='''pt''' ).pixel_values
logger.info(F'Converting model {model_name}...' )
# load original state dict
_lowerCAmelCase:int = torch.load(lowercase_ , map_location=torch.device('''cpu''' ) )
# rename keys
_lowerCAmelCase:int = rename_keys(lowercase_ )
# create HuggingFace model and load state dict
_lowerCAmelCase:Dict = PoolFormerForImageClassification(lowercase_ )
model.load_state_dict(lowercase_ )
model.eval()
# Define image processor
_lowerCAmelCase:Dict = PoolFormerImageProcessor(crop_pct=lowercase_ )
_lowerCAmelCase:Optional[Any] = image_processor(images=prepare_img() , return_tensors='''pt''' ).pixel_values
# forward pass
_lowerCAmelCase:Tuple = model(lowercase_ )
_lowerCAmelCase:str = outputs.logits
# define expected logit slices for different models
if size == "s12":
_lowerCAmelCase:List[str] = torch.tensor([-0.30_45, -0.67_58, -0.48_69] )
elif size == "s24":
_lowerCAmelCase:Any = torch.tensor([0.44_02, -0.13_74, -0.80_45] )
elif size == "s36":
_lowerCAmelCase:Tuple = torch.tensor([-0.60_80, -0.51_33, -0.58_98] )
elif size == "m36":
_lowerCAmelCase:List[str] = torch.tensor([0.39_52, 0.22_63, -1.26_68] )
elif size == "m48":
_lowerCAmelCase:Optional[int] = torch.tensor([0.11_67, -0.06_56, -0.34_23] )
else:
raise ValueError(F'Size {size} not supported' )
# verify logits
assert logits.shape == expected_shape
assert torch.allclose(logits[0, :3] , lowercase_ , atol=1e-2 )
# finally, save model and image processor
logger.info(F'Saving PyTorch model and image processor to {pytorch_dump_folder_path}...' )
Path(lowercase_ ).mkdir(exist_ok=lowercase_ )
model.save_pretrained(lowercase_ )
print(F'Saving image processor to {pytorch_dump_folder_path}' )
image_processor.save_pretrained(lowercase_ )
if __name__ == "__main__":
UpperCamelCase__ = argparse.ArgumentParser()
parser.add_argument(
'''--model_name''',
default='''poolformer_s12''',
type=str,
help='''Name of the model you\'d like to convert.''',
)
parser.add_argument(
'''--checkpoint_path''', default=None, type=str, help='''Path to the original PyTorch checkpoint (.pth file).'''
)
parser.add_argument(
'''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.'''
)
UpperCamelCase__ = parser.parse_args()
convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
| 708 |
"""simple docstring"""
from dataclasses import dataclass
from typing import List, Optional, Union
import numpy as np
import torch
from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available
@dataclass
class a__ ( UpperCamelCase_ ):
snake_case__ = 42
try:
if not (is_transformers_available() and is_torch_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_torch_and_transformers_objects import * # noqa F403
else:
from .pipeline_text_to_video_synth import TextToVideoSDPipeline
from .pipeline_text_to_video_synth_imgaimg import VideoToVideoSDPipeline # noqa: F401
from .pipeline_text_to_video_zero import TextToVideoZeroPipeline
| 439 | 0 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase : Optional[int] = logging.get_logger(__name__)
UpperCamelCase : List[str] = {
"""tiiuae/falcon-40b""": """https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json""",
"""tiiuae/falcon-7b""": """https://huggingface.co/tiiuae/falcon-7b/resolve/main/config.json""",
}
class A__ ( A__ ):
"""simple docstring"""
_lowercase = 'falcon'
_lowercase = ['past_key_values']
def __init__( self : Optional[Any] , lowerCamelCase__ : Union[str, Any]=65_024 , lowerCamelCase__ : List[Any]=4_544 , lowerCamelCase__ : str=32 , lowerCamelCase__ : List[Any]=71 , lowerCamelCase__ : List[Any]=1E-5 , lowerCamelCase__ : List[Any]=0.02 , lowerCamelCase__ : Optional[int]=True , lowerCamelCase__ : Optional[int]=0.0 , lowerCamelCase__ : Optional[int]=0.0 , lowerCamelCase__ : Optional[Any]=None , lowerCamelCase__ : Optional[int]=False , lowerCamelCase__ : Tuple=False , lowerCamelCase__ : List[Any]=True , lowerCamelCase__ : Any=True , lowerCamelCase__ : List[Any]=False , lowerCamelCase__ : int=11 , lowerCamelCase__ : List[Any]=11 , **lowerCamelCase__ : int , ):
a__ : Any = vocab_size
# Backward compatibility with n_embed kwarg
a__ : Dict = kwargs.pop("n_embed" , lowerCamelCase__ )
a__ : str = hidden_size if n_embed is None else n_embed
a__ : Tuple = num_hidden_layers
a__ : Dict = num_attention_heads
a__ : Tuple = layer_norm_epsilon
a__ : List[str] = initializer_range
a__ : Dict = use_cache
a__ : Tuple = hidden_dropout
a__ : str = attention_dropout
a__ : str = bos_token_id
a__ : Any = eos_token_id
a__ : Tuple = num_attention_heads if num_kv_heads is None else num_kv_heads
a__ : Union[str, Any] = alibi
a__ : List[str] = new_decoder_architecture
a__ : Optional[Any] = multi_query # Ignored when new_decoder_architecture is True
a__ : int = parallel_attn
a__ : Any = bias
super().__init__(bos_token_id=lowerCamelCase__ , eos_token_id=lowerCamelCase__ , **lowerCamelCase__ )
@property
def _UpperCamelCase( self : Optional[Any] ):
return self.hidden_size // self.num_attention_heads
@property
def _UpperCamelCase( self : Dict ):
return not self.alibi
| 37 |
'''simple docstring'''
from collections import OrderedDict
from typing import Any, Mapping, Optional, Union
from ...configuration_utils import PretrainedConfig
from ...feature_extraction_utils import FeatureExtractionMixin
from ...onnx import OnnxConfig
from ...onnx.utils import compute_effective_axis_dimension
from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import TensorType, logging
lowerCAmelCase : Any = logging.get_logger(__name__)
lowerCAmelCase : Optional[int] = {
'deepmind/language-perceiver': 'https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json',
# See all Perceiver models at https://huggingface.co/models?filter=perceiver
}
class SCREAMING_SNAKE_CASE__ ( snake_case_):
lowerCAmelCase_ = """perceiver"""
def __init__( self , A_=256 , A_=1280 , A_=768 , A_=1 , A_=26 , A_=8 , A_=8 , A_=None , A_=None , A_="kv" , A_=1 , A_=1 , A_="gelu" , A_=0.1 , A_=0.02 , A_=1e-12 , A_=True , A_=262 , A_=2048 , A_=56 , A_=[368, 496] , A_=16 , A_=1920 , A_=16 , A_=[1, 16, 224, 224] , **A_ , )-> str:
'''simple docstring'''
super().__init__(**A_ )
UpperCamelCase = num_latents
UpperCamelCase = d_latents
UpperCamelCase = d_model
UpperCamelCase = num_blocks
UpperCamelCase = num_self_attends_per_block
UpperCamelCase = num_self_attention_heads
UpperCamelCase = num_cross_attention_heads
UpperCamelCase = qk_channels
UpperCamelCase = v_channels
UpperCamelCase = cross_attention_shape_for_attention
UpperCamelCase = self_attention_widening_factor
UpperCamelCase = cross_attention_widening_factor
UpperCamelCase = hidden_act
UpperCamelCase = attention_probs_dropout_prob
UpperCamelCase = initializer_range
UpperCamelCase = layer_norm_eps
UpperCamelCase = use_query_residual
# masked language modeling attributes
UpperCamelCase = vocab_size
UpperCamelCase = max_position_embeddings
# image classification attributes
UpperCamelCase = image_size
# flow attributes
UpperCamelCase = train_size
# multimodal autoencoding attributes
UpperCamelCase = num_frames
UpperCamelCase = audio_samples_per_frame
UpperCamelCase = samples_per_patch
UpperCamelCase = output_shape
class SCREAMING_SNAKE_CASE__ ( snake_case_):
@property
def UpperCAmelCase_ ( self )-> Mapping[str, Mapping[int, str]]:
'''simple docstring'''
if self.task == "multiple-choice":
UpperCamelCase = {0: 'batch', 1: 'choice', 2: 'sequence'}
else:
UpperCamelCase = {0: 'batch', 1: 'sequence'}
return OrderedDict(
[
('inputs', dynamic_axis),
('attention_mask', dynamic_axis),
] )
@property
def UpperCAmelCase_ ( self )-> float:
'''simple docstring'''
return 1e-4
def UpperCAmelCase_ ( self , A_ , A_ = -1 , A_ = -1 , A_ = -1 , A_ = False , A_ = None , A_ = 3 , A_ = 40 , A_ = 40 , )-> Mapping[str, Any]:
'''simple docstring'''
if isinstance(A_ , A_ ):
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
UpperCamelCase = compute_effective_axis_dimension(
A_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 )
# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
UpperCamelCase = preprocessor.num_special_tokens_to_add(A_ )
UpperCamelCase = compute_effective_axis_dimension(
A_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=A_ )
# Generate dummy inputs according to compute batch and sequence
UpperCamelCase = [' '.join(['a'] ) * seq_length] * batch_size
UpperCamelCase = dict(preprocessor(A_ , return_tensors=A_ ) )
UpperCamelCase = inputs.pop('input_ids' )
return inputs
elif isinstance(A_ , A_ ) and preprocessor.model_input_names[0] == "pixel_values":
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
UpperCamelCase = compute_effective_axis_dimension(A_ , fixed_dimension=OnnxConfig.default_fixed_batch )
UpperCamelCase = self._generate_dummy_images(A_ , A_ , A_ , A_ )
UpperCamelCase = dict(preprocessor(images=A_ , return_tensors=A_ ) )
UpperCamelCase = inputs.pop('pixel_values' )
return inputs
else:
raise ValueError(
'Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor.' )
| 3 | 0 |
"""simple docstring"""
from __future__ import annotations
def UpperCAmelCase ( a_ ):
'''simple docstring'''
lowerCamelCase : int = 2
lowerCamelCase : Tuple = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(a_ )
if n > 1:
factors.append(a_ )
return factors
if __name__ == "__main__":
import doctest
doctest.testmod()
| 133 |
"""simple docstring"""
import gc
import unittest
from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline
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 _lowercase ( unittest.TestCase ):
def _UpperCamelCase ( self ) -> List[Any]:
# clean up the VRAM after each test
super().tearDown()
gc.collect()
def _UpperCamelCase ( self ) -> List[str]:
lowerCamelCase , lowerCamelCase : int = FlaxControlNetModel.from_pretrained(
'lllyasviel/sd-controlnet-canny' , from_pt=UpperCAmelCase_ , dtype=jnp.bfloataa )
lowerCamelCase , lowerCamelCase : Tuple = FlaxStableDiffusionControlNetPipeline.from_pretrained(
'runwayml/stable-diffusion-v1-5' , controlnet=UpperCAmelCase_ , from_pt=UpperCAmelCase_ , dtype=jnp.bfloataa )
lowerCamelCase : Optional[Any] = controlnet_params
lowerCamelCase : Dict = 'bird'
lowerCamelCase : Optional[int] = jax.device_count()
lowerCamelCase : Dict = pipe.prepare_text_inputs([prompts] * num_samples )
lowerCamelCase : Tuple = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png' )
lowerCamelCase : Union[str, Any] = pipe.prepare_image_inputs([canny_image] * num_samples )
lowerCamelCase : List[str] = jax.random.PRNGKey(0 )
lowerCamelCase : int = jax.random.split(UpperCAmelCase_ , jax.device_count() )
lowerCamelCase : Union[str, Any] = replicate(UpperCAmelCase_ )
lowerCamelCase : Tuple = shard(UpperCAmelCase_ )
lowerCamelCase : Tuple = shard(UpperCAmelCase_ )
lowerCamelCase : Tuple = pipe(
prompt_ids=UpperCAmelCase_ , image=UpperCAmelCase_ , params=UpperCAmelCase_ , prng_seed=UpperCAmelCase_ , num_inference_steps=50 , jit=UpperCAmelCase_ , ).images
assert images.shape == (jax.device_count(), 1, 768, 512, 3)
lowerCamelCase : List[str] = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
lowerCamelCase : Any = images[0, 253:256, 253:256, -1]
lowerCamelCase : int = jnp.asarray(jax.device_get(image_slice.flatten() ) )
lowerCamelCase : List[Any] = jnp.array(
[0.167969, 0.116699, 0.081543, 0.154297, 0.132812, 0.108887, 0.169922, 0.169922, 0.205078] )
print(F"""output_slice: {output_slice}""" )
assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
def _UpperCamelCase ( self ) -> Optional[Any]:
lowerCamelCase , lowerCamelCase : Dict = FlaxControlNetModel.from_pretrained(
'lllyasviel/sd-controlnet-openpose' , from_pt=UpperCAmelCase_ , dtype=jnp.bfloataa )
lowerCamelCase , lowerCamelCase : Optional[Any] = FlaxStableDiffusionControlNetPipeline.from_pretrained(
'runwayml/stable-diffusion-v1-5' , controlnet=UpperCAmelCase_ , from_pt=UpperCAmelCase_ , dtype=jnp.bfloataa )
lowerCamelCase : int = controlnet_params
lowerCamelCase : Dict = 'Chef in the kitchen'
lowerCamelCase : Dict = jax.device_count()
lowerCamelCase : List[Any] = pipe.prepare_text_inputs([prompts] * num_samples )
lowerCamelCase : Tuple = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png' )
lowerCamelCase : int = pipe.prepare_image_inputs([pose_image] * num_samples )
lowerCamelCase : int = jax.random.PRNGKey(0 )
lowerCamelCase : str = jax.random.split(UpperCAmelCase_ , jax.device_count() )
lowerCamelCase : int = replicate(UpperCAmelCase_ )
lowerCamelCase : int = shard(UpperCAmelCase_ )
lowerCamelCase : Optional[int] = shard(UpperCAmelCase_ )
lowerCamelCase : Union[str, Any] = pipe(
prompt_ids=UpperCAmelCase_ , image=UpperCAmelCase_ , params=UpperCAmelCase_ , prng_seed=UpperCAmelCase_ , num_inference_steps=50 , jit=UpperCAmelCase_ , ).images
assert images.shape == (jax.device_count(), 1, 768, 512, 3)
lowerCamelCase : Tuple = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
lowerCamelCase : Optional[Any] = images[0, 253:256, 253:256, -1]
lowerCamelCase : Dict = jnp.asarray(jax.device_get(image_slice.flatten() ) )
lowerCamelCase : List[str] = jnp.array(
[[0.271484, 0.261719, 0.275391, 0.277344, 0.279297, 0.291016, 0.294922, 0.302734, 0.302734]] )
print(F"""output_slice: {output_slice}""" )
assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
| 133 | 1 |
snake_case = "\n# Transformers 설치 방법\n! pip install transformers datasets\n# 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요.\n# ! pip install git+https://github.com/huggingface/transformers.git\n"
snake_case = [{"type": "code", "content": INSTALL_CONTENT}]
snake_case = {
"{processor_class}": "FakeProcessorClass",
"{model_class}": "FakeModelClass",
"{object_class}": "FakeObjectClass",
}
| 424 | from collections import OrderedDict
from typing import Any, Mapping, Optional
from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging
snake_case = logging.get_logger(__name__)
snake_case = {
"Helsinki-NLP/opus-mt-en-de": "https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/config.json",
# See all Marian models at https://huggingface.co/models?filter=marian
}
class __A ( snake_case__ ):
'''simple docstring'''
a_ = '''marian'''
a_ = ['''past_key_values''']
a_ = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''}
def __init__( self , _snake_case=5_8101 , _snake_case=None , _snake_case=1024 , _snake_case=12 , _snake_case=4096 , _snake_case=16 , _snake_case=12 , _snake_case=4096 , _snake_case=16 , _snake_case=0.0 , _snake_case=0.0 , _snake_case=True , _snake_case=True , _snake_case="gelu" , _snake_case=1024 , _snake_case=0.1 , _snake_case=0.0 , _snake_case=0.0 , _snake_case=0.02 , _snake_case=5_8100 , _snake_case=False , _snake_case=5_8100 , _snake_case=0 , _snake_case=0 , _snake_case=True , **_snake_case , ):
_lowerCAmelCase : List[Any] = vocab_size
_lowerCAmelCase : Optional[int] = decoder_vocab_size or vocab_size
_lowerCAmelCase : int = max_position_embeddings
_lowerCAmelCase : Tuple = d_model
_lowerCAmelCase : Any = encoder_ffn_dim
_lowerCAmelCase : int = encoder_layers
_lowerCAmelCase : Optional[Any] = encoder_attention_heads
_lowerCAmelCase : Optional[Any] = decoder_ffn_dim
_lowerCAmelCase : Tuple = decoder_layers
_lowerCAmelCase : List[Any] = decoder_attention_heads
_lowerCAmelCase : int = dropout
_lowerCAmelCase : Optional[Any] = attention_dropout
_lowerCAmelCase : str = activation_dropout
_lowerCAmelCase : List[str] = activation_function
_lowerCAmelCase : int = init_std
_lowerCAmelCase : Any = encoder_layerdrop
_lowerCAmelCase : str = decoder_layerdrop
_lowerCAmelCase : List[str] = use_cache
_lowerCAmelCase : Optional[int] = encoder_layers
_lowerCAmelCase : Optional[int] = scale_embedding # scale factor will be sqrt(d_model) if True
_lowerCAmelCase : Optional[Any] = share_encoder_decoder_embeddings
super().__init__(
pad_token_id=_snake_case , eos_token_id=_snake_case , is_encoder_decoder=_snake_case , decoder_start_token_id=_snake_case , forced_eos_token_id=_snake_case , **_snake_case , )
class __A ( snake_case__ ):
'''simple docstring'''
@property
# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.inputs
def SCREAMING_SNAKE_CASE__ ( self ):
if self.task in ["default", "seq2seq-lm"]:
_lowerCAmelCase : List[str] = OrderedDict(
[
("input_ids", {0: "batch", 1: "encoder_sequence"}),
("attention_mask", {0: "batch", 1: "encoder_sequence"}),
] )
if self.use_past:
_lowerCAmelCase : Optional[Any] = {0: "batch"}
_lowerCAmelCase : Tuple = {0: "batch", 1: "past_decoder_sequence + sequence"}
else:
_lowerCAmelCase : str = {0: "batch", 1: "decoder_sequence"}
_lowerCAmelCase : str = {0: "batch", 1: "decoder_sequence"}
if self.use_past:
self.fill_with_past_key_values_(_snake_case , direction="inputs" )
elif self.task == "causal-lm":
# TODO: figure this case out.
_lowerCAmelCase : Union[str, Any] = OrderedDict(
[
("input_ids", {0: "batch", 1: "encoder_sequence"}),
("attention_mask", {0: "batch", 1: "encoder_sequence"}),
] )
if self.use_past:
_lowerCAmelCase , _lowerCAmelCase : Tuple = self.num_layers
for i in range(_snake_case ):
_lowerCAmelCase : Union[str, Any] = {0: "batch", 2: "past_sequence + sequence"}
_lowerCAmelCase : Optional[int] = {0: "batch", 2: "past_sequence + sequence"}
else:
_lowerCAmelCase : List[Any] = OrderedDict(
[
("input_ids", {0: "batch", 1: "encoder_sequence"}),
("attention_mask", {0: "batch", 1: "encoder_sequence"}),
("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}),
("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}),
] )
return common_inputs
@property
# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
def SCREAMING_SNAKE_CASE__ ( self ):
if self.task in ["default", "seq2seq-lm"]:
_lowerCAmelCase : Tuple = super().outputs
else:
_lowerCAmelCase : Dict = super(_snake_case , self ).outputs
if self.use_past:
_lowerCAmelCase , _lowerCAmelCase : Any = self.num_layers
for i in range(_snake_case ):
_lowerCAmelCase : Optional[Any] = {0: "batch", 2: "past_sequence + sequence"}
_lowerCAmelCase : str = {0: "batch", 2: "past_sequence + sequence"}
return common_outputs
def SCREAMING_SNAKE_CASE__ ( self , _snake_case , _snake_case = -1 , _snake_case = -1 , _snake_case = False , _snake_case = None , ):
_lowerCAmelCase : Dict = self._generate_dummy_inputs_for_encoder_and_decoder(
_snake_case , _snake_case , _snake_case , _snake_case , _snake_case )
# Generate decoder inputs
_lowerCAmelCase : Union[str, Any] = seq_length if not self.use_past else 1
_lowerCAmelCase : Optional[int] = self._generate_dummy_inputs_for_encoder_and_decoder(
_snake_case , _snake_case , _snake_case , _snake_case , _snake_case )
_lowerCAmelCase : Union[str, Any] = {F"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()}
_lowerCAmelCase : Union[str, Any] = dict(**_snake_case , **_snake_case )
if self.use_past:
if not is_torch_available():
raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." )
else:
import torch
_lowerCAmelCase , _lowerCAmelCase : Tuple = common_inputs["input_ids"].shape
_lowerCAmelCase : List[str] = common_inputs["decoder_input_ids"].shape[1]
_lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = self.num_attention_heads
_lowerCAmelCase : List[Any] = (
batch,
num_encoder_attention_heads,
encoder_seq_length,
self._config.hidden_size // num_encoder_attention_heads,
)
_lowerCAmelCase : Dict = decoder_seq_length + 3
_lowerCAmelCase : Any = (
batch,
num_decoder_attention_heads,
decoder_past_length,
self._config.hidden_size // num_decoder_attention_heads,
)
_lowerCAmelCase : Union[str, Any] = torch.cat(
[common_inputs["decoder_attention_mask"], torch.ones(_snake_case , _snake_case )] , dim=1 )
_lowerCAmelCase : Any = []
# If the number of encoder and decoder layers are present in the model configuration, both are considered
_lowerCAmelCase , _lowerCAmelCase : Dict = self.num_layers
_lowerCAmelCase : Union[str, Any] = min(_snake_case , _snake_case )
_lowerCAmelCase : List[Any] = max(_snake_case , _snake_case ) - min_num_layers
_lowerCAmelCase : str = "encoder" if num_encoder_layers > num_decoder_layers else "decoder"
for _ in range(_snake_case ):
common_inputs["past_key_values"].append(
(
torch.zeros(_snake_case ),
torch.zeros(_snake_case ),
torch.zeros(_snake_case ),
torch.zeros(_snake_case ),
) )
# TODO: test this.
_lowerCAmelCase : int = encoder_shape if remaining_side_name == "encoder" else decoder_shape
for _ in range(_snake_case , _snake_case ):
common_inputs["past_key_values"].append((torch.zeros(_snake_case ), torch.zeros(_snake_case )) )
return common_inputs
def SCREAMING_SNAKE_CASE__ ( self , _snake_case , _snake_case = -1 , _snake_case = -1 , _snake_case = False , _snake_case = None , ):
_lowerCAmelCase : Optional[int] = self._generate_dummy_inputs_for_encoder_and_decoder(
_snake_case , _snake_case , _snake_case , _snake_case , _snake_case )
if self.use_past:
if not is_torch_available():
raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." )
else:
import torch
_lowerCAmelCase , _lowerCAmelCase : int = common_inputs["input_ids"].shape
# Not using the same length for past_key_values
_lowerCAmelCase : Union[str, Any] = seqlen + 2
_lowerCAmelCase , _lowerCAmelCase : Tuple = self.num_layers
_lowerCAmelCase , _lowerCAmelCase : Any = self.num_attention_heads
_lowerCAmelCase : List[str] = (
batch,
num_encoder_attention_heads,
past_key_values_length,
self._config.hidden_size // num_encoder_attention_heads,
)
_lowerCAmelCase : Union[str, Any] = common_inputs["attention_mask"].dtype
_lowerCAmelCase : Union[str, Any] = torch.cat(
[common_inputs["attention_mask"], torch.ones(_snake_case , _snake_case , dtype=_snake_case )] , dim=1 )
_lowerCAmelCase : Tuple = [
(torch.zeros(_snake_case ), torch.zeros(_snake_case )) for _ in range(_snake_case )
]
return common_inputs
def SCREAMING_SNAKE_CASE__ ( self , _snake_case , _snake_case = -1 , _snake_case = -1 , _snake_case = False , _snake_case = None , ):
# Copied from OnnxConfig.generate_dummy_inputs
# Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
_lowerCAmelCase : Union[str, Any] = compute_effective_axis_dimension(
_snake_case , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 )
# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
_lowerCAmelCase : int = tokenizer.num_special_tokens_to_add(_snake_case )
_lowerCAmelCase : Optional[Any] = compute_effective_axis_dimension(
_snake_case , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=_snake_case )
# Generate dummy inputs according to compute batch and sequence
_lowerCAmelCase : Any = [" ".join([tokenizer.unk_token] ) * seq_length] * batch_size
_lowerCAmelCase : Union[str, Any] = dict(tokenizer(_snake_case , return_tensors=_snake_case ) )
return common_inputs
def SCREAMING_SNAKE_CASE__ ( self , _snake_case , _snake_case = -1 , _snake_case = -1 , _snake_case = False , _snake_case = None , ):
if self.task in ["default", "seq2seq-lm"]:
_lowerCAmelCase : int = self._generate_dummy_inputs_for_default_and_seqaseq_lm(
_snake_case , batch_size=_snake_case , seq_length=_snake_case , is_pair=_snake_case , framework=_snake_case )
else:
_lowerCAmelCase : Tuple = self._generate_dummy_inputs_for_causal_lm(
_snake_case , batch_size=_snake_case , seq_length=_snake_case , is_pair=_snake_case , framework=_snake_case )
return common_inputs
def SCREAMING_SNAKE_CASE__ ( self , _snake_case , _snake_case , _snake_case , _snake_case ):
if self.task in ["default", "seq2seq-lm"]:
_lowerCAmelCase : Any = super()._flatten_past_key_values_(_snake_case , _snake_case , _snake_case , _snake_case )
else:
_lowerCAmelCase : int = super(_snake_case , self )._flatten_past_key_values_(
_snake_case , _snake_case , _snake_case , _snake_case )
@property
def SCREAMING_SNAKE_CASE__ ( self ):
return 1E-4
| 424 | 1 |
def __lowerCAmelCase( __UpperCAmelCase ,__UpperCAmelCase ):
"""simple docstring"""
_lowercase : Optional[int] = len(__UpperCAmelCase )
_lowercase : List[str] = []
for i in range(len(__UpperCAmelCase ) - pat_len + 1 ):
_lowercase : List[Any] = True
for j in range(__UpperCAmelCase ):
if s[i + j] != pattern[j]:
_lowercase : Optional[Any] = False
break
if match_found:
position.append(__UpperCAmelCase )
return position
if __name__ == "__main__":
assert naive_pattern_search('ABCDEFG', 'DE') == [3]
print(naive_pattern_search('ABAAABCDBBABCDDEBCABC', 'ABC'))
| 708 | """simple docstring"""
from __future__ import annotations
import math
import random
from collections.abc import Collection
from typing import overload
class _lowerCamelCase :
def __init__( self : str , lowerCamelCase_ : Collection[float] | None = None ):
"""simple docstring"""
if components is None:
_lowercase : Any = []
_lowercase : int = list(lowerCamelCase_ )
def __len__( self : int ):
"""simple docstring"""
return len(self.__components )
def __str__( self : List[Any] ):
"""simple docstring"""
return "(" + ",".join(map(lowerCamelCase_ , self.__components ) ) + ")"
def __add__( self : Dict , lowerCamelCase_ : Vector ):
"""simple docstring"""
_lowercase : Union[str, Any] = len(self )
if size == len(lowerCamelCase_ ):
_lowercase : int = [self.__components[i] + other.component(lowerCamelCase_ ) for i in range(lowerCamelCase_ )]
return Vector(lowerCamelCase_ )
else:
raise Exception('must have the same size' )
def __sub__( self : int , lowerCamelCase_ : Vector ):
"""simple docstring"""
_lowercase : Optional[int] = len(self )
if size == len(lowerCamelCase_ ):
_lowercase : Optional[int] = [self.__components[i] - other.component(lowerCamelCase_ ) for i in range(lowerCamelCase_ )]
return Vector(lowerCamelCase_ )
else: # error case
raise Exception('must have the same size' )
@overload
def __mul__( self : Tuple , lowerCamelCase_ : float ):
"""simple docstring"""
...
@overload
def __mul__( self : Tuple , lowerCamelCase_ : Vector ):
"""simple docstring"""
...
def __mul__( self : int , lowerCamelCase_ : float | Vector ):
"""simple docstring"""
if isinstance(lowerCamelCase_ , (float, int) ):
_lowercase : List[Any] = [c * other for c in self.__components]
return Vector(lowerCamelCase_ )
elif isinstance(lowerCamelCase_ , lowerCamelCase_ ) and len(self ) == len(lowerCamelCase_ ):
_lowercase : Any = len(self )
_lowercase : List[Any] = [self.__components[i] * other.component(lowerCamelCase_ ) for i in range(lowerCamelCase_ )]
return sum(lowerCamelCase_ )
else: # error case
raise Exception('invalid operand!' )
def __UpperCAmelCase ( self : Dict ):
"""simple docstring"""
return Vector(self.__components )
def __UpperCAmelCase ( self : List[str] , lowerCamelCase_ : int ):
"""simple docstring"""
if isinstance(lowerCamelCase_ , lowerCamelCase_ ) and -len(self.__components ) <= i < len(self.__components ):
return self.__components[i]
else:
raise Exception('index out of range' )
def __UpperCAmelCase ( self : str , lowerCamelCase_ : int , lowerCamelCase_ : float ):
"""simple docstring"""
assert -len(self.__components ) <= pos < len(self.__components )
_lowercase : Tuple = value
def __UpperCAmelCase ( self : List[Any] ):
"""simple docstring"""
if len(self.__components ) == 0:
raise Exception('Vector is empty' )
_lowercase : Optional[int] = [c**2 for c in self.__components]
return math.sqrt(sum(lowerCamelCase_ ) )
def __UpperCAmelCase ( self : int , lowerCamelCase_ : Vector , lowerCamelCase_ : bool = False ):
"""simple docstring"""
_lowercase : int = self * other
_lowercase : Any = self.euclidean_length() * other.euclidean_length()
if deg:
return math.degrees(math.acos(num / den ) )
else:
return math.acos(num / den )
def __lowerCAmelCase( __UpperCAmelCase ):
"""simple docstring"""
assert isinstance(__UpperCAmelCase ,__UpperCAmelCase )
return Vector([0] * dimension )
def __lowerCAmelCase( __UpperCAmelCase ,__UpperCAmelCase ):
"""simple docstring"""
assert isinstance(__UpperCAmelCase ,__UpperCAmelCase ) and (isinstance(__UpperCAmelCase ,__UpperCAmelCase ))
_lowercase : str = [0] * dimension
_lowercase : List[Any] = 1
return Vector(__UpperCAmelCase )
def __lowerCAmelCase( __UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ):
"""simple docstring"""
assert (
isinstance(__UpperCAmelCase ,__UpperCAmelCase )
and isinstance(__UpperCAmelCase ,__UpperCAmelCase )
and (isinstance(__UpperCAmelCase ,(int, float) ))
)
return x * scalar + y
def __lowerCAmelCase( __UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ):
"""simple docstring"""
random.seed(__UpperCAmelCase )
_lowercase : Tuple = [random.randint(__UpperCAmelCase ,__UpperCAmelCase ) for _ in range(__UpperCAmelCase )]
return Vector(__UpperCAmelCase )
class _lowerCamelCase :
def __init__( self : Dict , lowerCamelCase_ : list[list[float]] , lowerCamelCase_ : int , lowerCamelCase_ : int ):
"""simple docstring"""
_lowercase : Tuple = matrix
_lowercase : str = w
_lowercase : Tuple = h
def __str__( self : int ):
"""simple docstring"""
_lowercase : Tuple = ''
for i in range(self.__height ):
ans += "|"
for j in range(self.__width ):
if j < self.__width - 1:
ans += str(self.__matrix[i][j] ) + ","
else:
ans += str(self.__matrix[i][j] ) + "|\n"
return ans
def __add__( self : Dict , lowerCamelCase_ : Matrix ):
"""simple docstring"""
if self.__width == other.width() and self.__height == other.height():
_lowercase : Dict = []
for i in range(self.__height ):
_lowercase : Tuple = [
self.__matrix[i][j] + other.component(lowerCamelCase_ , lowerCamelCase_ )
for j in range(self.__width )
]
matrix.append(lowerCamelCase_ )
return Matrix(lowerCamelCase_ , self.__width , self.__height )
else:
raise Exception('matrix must have the same dimension!' )
def __sub__( self : str , lowerCamelCase_ : Matrix ):
"""simple docstring"""
if self.__width == other.width() and self.__height == other.height():
_lowercase : List[Any] = []
for i in range(self.__height ):
_lowercase : int = [
self.__matrix[i][j] - other.component(lowerCamelCase_ , lowerCamelCase_ )
for j in range(self.__width )
]
matrix.append(lowerCamelCase_ )
return Matrix(lowerCamelCase_ , self.__width , self.__height )
else:
raise Exception('matrices must have the same dimension!' )
@overload
def __mul__( self : Union[str, Any] , lowerCamelCase_ : float ):
"""simple docstring"""
...
@overload
def __mul__( self : List[str] , lowerCamelCase_ : Vector ):
"""simple docstring"""
...
def __mul__( self : int , lowerCamelCase_ : float | Vector ):
"""simple docstring"""
if isinstance(lowerCamelCase_ , lowerCamelCase_ ): # matrix-vector
if len(lowerCamelCase_ ) == self.__width:
_lowercase : Optional[int] = zero_vector(self.__height )
for i in range(self.__height ):
_lowercase : Optional[Any] = [
self.__matrix[i][j] * other.component(lowerCamelCase_ )
for j in range(self.__width )
]
ans.change_component(lowerCamelCase_ , sum(lowerCamelCase_ ) )
return ans
else:
raise Exception(
'vector must have the same size as the '
'number of columns of the matrix!' )
elif isinstance(lowerCamelCase_ , (int, float) ): # matrix-scalar
_lowercase : Optional[int] = [
[self.__matrix[i][j] * other for j in range(self.__width )]
for i in range(self.__height )
]
return Matrix(lowerCamelCase_ , self.__width , self.__height )
return None
def __UpperCAmelCase ( self : Union[str, Any] ):
"""simple docstring"""
return self.__height
def __UpperCAmelCase ( self : List[Any] ):
"""simple docstring"""
return self.__width
def __UpperCAmelCase ( self : Optional[Any] , lowerCamelCase_ : int , lowerCamelCase_ : int ):
"""simple docstring"""
if 0 <= x < self.__height and 0 <= y < self.__width:
return self.__matrix[x][y]
else:
raise Exception('change_component: indices out of bounds' )
def __UpperCAmelCase ( self : Optional[Any] , lowerCamelCase_ : int , lowerCamelCase_ : int , lowerCamelCase_ : float ):
"""simple docstring"""
if 0 <= x < self.__height and 0 <= y < self.__width:
_lowercase : int = value
else:
raise Exception('change_component: indices out of bounds' )
def __UpperCAmelCase ( self : int , lowerCamelCase_ : int , lowerCamelCase_ : int ):
"""simple docstring"""
if self.__height != self.__width:
raise Exception('Matrix is not square' )
_lowercase : Union[str, Any] = self.__matrix[:x] + self.__matrix[x + 1 :]
for i in range(len(lowerCamelCase_ ) ):
_lowercase : int = minor[i][:y] + minor[i][y + 1 :]
return Matrix(lowerCamelCase_ , self.__width - 1 , self.__height - 1 ).determinant()
def __UpperCAmelCase ( self : List[str] , lowerCamelCase_ : int , lowerCamelCase_ : int ):
"""simple docstring"""
if self.__height != self.__width:
raise Exception('Matrix is not square' )
if 0 <= x < self.__height and 0 <= y < self.__width:
return (-1) ** (x + y) * self.minor(lowerCamelCase_ , lowerCamelCase_ )
else:
raise Exception('Indices out of bounds' )
def __UpperCAmelCase ( self : Dict ):
"""simple docstring"""
if self.__height != self.__width:
raise Exception('Matrix is not square' )
if self.__height < 1:
raise Exception('Matrix has no element' )
elif self.__height == 1:
return self.__matrix[0][0]
elif self.__height == 2:
return (
self.__matrix[0][0] * self.__matrix[1][1]
- self.__matrix[0][1] * self.__matrix[1][0]
)
else:
_lowercase : Union[str, Any] = [
self.__matrix[0][y] * self.cofactor(0 , lowerCamelCase_ ) for y in range(self.__width )
]
return sum(lowerCamelCase_ )
def __lowerCAmelCase( __UpperCAmelCase ):
"""simple docstring"""
_lowercase : list[list[float]] = [[0] * n for _ in range(__UpperCAmelCase )]
return Matrix(__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase )
def __lowerCAmelCase( __UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ):
"""simple docstring"""
random.seed(__UpperCAmelCase )
_lowercase : list[list[float]] = [
[random.randint(__UpperCAmelCase ,__UpperCAmelCase ) for _ in range(__UpperCAmelCase )] for _ in range(__UpperCAmelCase )
]
return Matrix(__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase )
| 283 | 0 |
from PIL import Image
def _A ( _lowercase ) -> Image:
"""simple docstring"""
__UpperCamelCase, __UpperCamelCase = image.size
__UpperCamelCase = 0
__UpperCamelCase = image.load()
for i in range(_lowercase ):
for j in range(_lowercase ):
__UpperCamelCase = pixels[j, i]
mean += pixel
mean //= width * height
for j in range(_lowercase ):
for i in range(_lowercase ):
__UpperCamelCase = 2_55 if pixels[i, j] > mean else 0
return image
if __name__ == "__main__":
__snake_case = mean_threshold(Image.open('''path_to_image''').convert('''L'''))
image.save('''output_image_path''')
| 1 | from decimal import Decimal, getcontext
from math import ceil, factorial
def SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_: int ):
if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ):
raise TypeError("Undefined for non-integers" )
elif precision < 1:
raise ValueError("Undefined for non-natural numbers" )
snake_case_ : List[str] = precision
snake_case_ : Union[str, Any] = ceil(precision / 1_4 )
snake_case_ : List[str] = 4_2_6_8_8_0 * Decimal(1_0_0_0_5 ).sqrt()
snake_case_ : str = 1
snake_case_ : List[str] = 1_3_5_9_1_4_0_9
snake_case_ : str = Decimal(lowerCAmelCase_ )
for k in range(1 , lowerCAmelCase_ ):
snake_case_ : Tuple = factorial(6 * k ) // (factorial(3 * k ) * factorial(lowerCAmelCase_ ) ** 3)
linear_term += 5_4_5_1_4_0_1_3_4
exponential_term *= -2_6_2_5_3_7_4_1_2_6_4_0_7_6_8_0_0_0
partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term
return str(constant_term / partial_sum )[:-1]
if __name__ == "__main__":
UpperCAmelCase = 5_0
print(F"The first {n} digits of pi is: {pi(n)}")
| 666 | 0 |
'''simple docstring'''
def UpperCAmelCase_ ( lowerCAmelCase_ , lowerCAmelCase_ ):
"""simple docstring"""
if mass < 0:
raise ValueError("The mass of a body cannot be negative" )
return 0.5 * mass * abs(lowerCAmelCase_ ) * abs(lowerCAmelCase_ )
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
| 459 |
'''simple docstring'''
from __future__ import annotations
class UpperCAmelCase :
def __init__(self : Dict , A__ : str , A__ : str ) -> str:
lowercase , lowercase = text, pattern
lowercase , lowercase = len(A__ ), len(A__ )
def UpperCAmelCase__ (self : Any , A__ : str ) -> int:
for i in range(self.patLen - 1 , -1 , -1 ):
if char == self.pattern[i]:
return i
return -1
def UpperCAmelCase__ (self : List[Any] , A__ : int ) -> int:
for i in range(self.patLen - 1 , -1 , -1 ):
if self.pattern[i] != self.text[current_pos + i]:
return current_pos + i
return -1
def UpperCAmelCase__ (self : Optional[Any] ) -> list[int]:
# searches pattern in text and returns index positions
lowercase = []
for i in range(self.textLen - self.patLen + 1 ):
lowercase = self.mismatch_in_text(A__ )
if mismatch_index == -1:
positions.append(A__ )
else:
lowercase = self.match_in_pattern(self.text[mismatch_index] )
lowercase = (
mismatch_index - match_index
) # shifting index lgtm [py/multiple-definition]
return positions
__lowerCamelCase : List[str] = "ABAABA"
__lowerCamelCase : List[str] = "AB"
__lowerCamelCase : Union[str, Any] = BoyerMooreSearch(text, pattern)
__lowerCamelCase : List[str] = bms.bad_character_heuristic()
if len(positions) == 0:
print("No match found")
else:
print("Pattern found in following positions: ")
print(positions)
| 459 | 1 |
import argparse
import torch
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt
if __name__ == "__main__":
SCREAMING_SNAKE_CASE : int = argparse.ArgumentParser()
parser.add_argument(
"--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert."
)
# !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml
parser.add_argument(
"--original_config_file",
default=None,
type=str,
help="The YAML config file corresponding to the original architecture.",
)
parser.add_argument(
"--num_in_channels",
default=None,
type=int,
help="The number of input channels. If `None` number of input channels will be automatically inferred.",
)
parser.add_argument(
"--scheduler_type",
default="pndm",
type=str,
help="Type of scheduler to use. Should be one of ['pndm', 'lms', 'ddim', 'euler', 'euler-ancestral', 'dpm']",
)
parser.add_argument(
"--pipeline_type",
default=None,
type=str,
help=(
"The pipeline type. One of 'FrozenOpenCLIPEmbedder', 'FrozenCLIPEmbedder', 'PaintByExample'"
". If `None` pipeline will be automatically inferred."
),
)
parser.add_argument(
"--image_size",
default=None,
type=int,
help=(
"The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2"
" Base. Use 768 for Stable Diffusion v2."
),
)
parser.add_argument(
"--prediction_type",
default=None,
type=str,
help=(
"The prediction type that the model was trained on. Use 'epsilon' for Stable Diffusion v1.X and Stable"
" Diffusion v2 Base. Use 'v_prediction' for Stable Diffusion v2."
),
)
parser.add_argument(
"--extract_ema",
action="store_true",
help=(
"Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights"
" or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield"
" higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning."
),
)
parser.add_argument(
"--upcast_attention",
action="store_true",
help=(
"Whether the attention computation should always be upcasted. This is necessary when running stable"
" diffusion 2.1."
),
)
parser.add_argument(
"--from_safetensors",
action="store_true",
help="If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.",
)
parser.add_argument(
"--to_safetensors",
action="store_true",
help="Whether to store pipeline in safetensors format or not.",
)
parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.")
parser.add_argument("--device", type=str, help="Device to use (e.g. cpu, cuda:0, cuda:1, etc.)")
parser.add_argument(
"--stable_unclip",
type=str,
default=None,
required=False,
help="Set if this is a stable unCLIP model. One of 'txt2img' or 'img2img'.",
)
parser.add_argument(
"--stable_unclip_prior",
type=str,
default=None,
required=False,
help="Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.",
)
parser.add_argument(
"--clip_stats_path",
type=str,
help="Path to the clip stats file. Only required if the stable unclip model's config specifies `model.params.noise_aug_config.params.clip_stats_path`.",
required=False,
)
parser.add_argument(
"--controlnet", action="store_true", default=None, help="Set flag if this is a controlnet checkpoint."
)
parser.add_argument("--half", action="store_true", help="Save weights in half precision.")
parser.add_argument(
"--vae_path",
type=str,
default=None,
required=False,
help="Set to a path, hub id to an already converted vae to not convert it again.",
)
SCREAMING_SNAKE_CASE : List[Any] = parser.parse_args()
SCREAMING_SNAKE_CASE : str = download_from_original_stable_diffusion_ckpt(
checkpoint_path=args.checkpoint_path,
original_config_file=args.original_config_file,
image_size=args.image_size,
prediction_type=args.prediction_type,
model_type=args.pipeline_type,
extract_ema=args.extract_ema,
scheduler_type=args.scheduler_type,
num_in_channels=args.num_in_channels,
upcast_attention=args.upcast_attention,
from_safetensors=args.from_safetensors,
device=args.device,
stable_unclip=args.stable_unclip,
stable_unclip_prior=args.stable_unclip_prior,
clip_stats_path=args.clip_stats_path,
controlnet=args.controlnet,
vae_path=args.vae_path,
)
if args.half:
pipe.to(torch_dtype=torch.floataa)
if args.controlnet:
# only save the controlnet model
pipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
else:
pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
| 419 |
import datasets
from .evaluate import evaluate
SCREAMING_SNAKE_CASE : Union[str, Any] = "\\n@inproceedings{Rajpurkar2016SQuAD10,\n title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},\n author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},\n booktitle={EMNLP},\n year={2016}\n}\n"
SCREAMING_SNAKE_CASE : List[Any] = "\nThis metric wrap the official scoring script for version 1 of the Stanford Question Answering Dataset (SQuAD).\n\nStanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by\ncrowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,\nfrom the corresponding reading passage, or the question might be unanswerable.\n"
SCREAMING_SNAKE_CASE : Any = "\nComputes SQuAD scores (F1 and EM).\nArgs:\n predictions: List of question-answers dictionaries with the following key-values:\n - 'id': id of the question-answer pair as given in the references (see below)\n - 'prediction_text': the text of the answer\n references: List of question-answers dictionaries with the following key-values:\n - 'id': id of the question-answer pair (see above),\n - 'answers': a Dict in the SQuAD dataset format\n {\n 'text': list of possible texts for the answer, as a list of strings\n 'answer_start': list of start positions for the answer, as a list of ints\n }\n Note that answer_start values are not taken into account to compute the metric.\nReturns:\n 'exact_match': Exact match (the normalized answer exactly match the gold answer)\n 'f1': The F-score of predicted tokens versus the gold answer\nExamples:\n\n >>> predictions = [{'prediction_text': '1976', 'id': '56e10a3be3433e1400422b22'}]\n >>> references = [{'answers': {'answer_start': [97], 'text': ['1976']}, 'id': '56e10a3be3433e1400422b22'}]\n >>> squad_metric = datasets.load_metric(\"squad\")\n >>> results = squad_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'exact_match': 100.0, 'f1': 100.0}\n"
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class snake_case__ ( datasets.Metric ):
def A ( self ) -> List[Any]:
"""simple docstring"""
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"""predictions""": {"""id""": datasets.Value("""string""" ), """prediction_text""": datasets.Value("""string""" )},
"""references""": {
"""id""": datasets.Value("""string""" ),
"""answers""": datasets.features.Sequence(
{
"""text""": datasets.Value("""string""" ),
"""answer_start""": datasets.Value("""int32""" ),
} ),
},
} ) , codebase_urls=["""https://rajpurkar.github.io/SQuAD-explorer/"""] , reference_urls=["""https://rajpurkar.github.io/SQuAD-explorer/"""] , )
def A ( self , UpperCamelCase_ , UpperCamelCase_ ) -> List[Any]:
"""simple docstring"""
a_ : Optional[int] = {prediction["""id"""]: prediction["""prediction_text"""] for prediction in predictions}
a_ : Dict = [
{
"""paragraphs""": [
{
"""qas""": [
{
"""answers""": [{"""text""": answer_text} for answer_text in ref["""answers"""]["""text"""]],
"""id""": ref["""id"""],
}
for ref in references
]
}
]
}
]
a_ : Optional[Any] = evaluate(dataset=UpperCamelCase_ , predictions=UpperCamelCase_ )
return score
| 419 | 1 |
"""simple docstring"""
def UpperCamelCase ( UpperCAmelCase = 1_000_000 ) ->int:
"""simple docstring"""
a_ = limit + 1
a_ = [0] * limit
for first_term in range(1 , UpperCAmelCase ):
for n in range(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ):
a_ = first_term + n / first_term
if common_difference % 4: # d must be divisble by 4
continue
else:
common_difference /= 4
if (
first_term > common_difference
and first_term < 4 * common_difference
): # since x,y,z are positive integers
frequency[n] += 1 # so z>0 and a>d ,also 4d<a
a_ = sum(1 for x in frequency[1:limit] if x == 10 )
return count
if __name__ == "__main__":
print(F"""{solution() = }""") | 708 |
"""simple docstring"""
def UpperCamelCase ( UpperCAmelCase ) ->list:
"""simple docstring"""
a_ = False
while is_sorted is False: # Until all the indices are traversed keep looping
a_ = True
for i in range(0 , len(UpperCAmelCase ) - 1 , 2 ): # iterating over all even indices
if input_list[i] > input_list[i + 1]:
a_ , a_ = input_list[i + 1], input_list[i]
# swapping if elements not in order
a_ = False
for i in range(1 , len(UpperCAmelCase ) - 1 , 2 ): # iterating over all odd indices
if input_list[i] > input_list[i + 1]:
a_ , a_ = input_list[i + 1], input_list[i]
# swapping if elements not in order
a_ = False
return input_list
if __name__ == "__main__":
print('Enter list to be sorted')
UpperCamelCase_ = [int(x) for x in input().split()]
# inputing elements of the list in one line
UpperCamelCase_ = odd_even_sort(input_list)
print('The sorted list is')
print(sorted_list) | 210 | 0 |
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
lowerCAmelCase : Dict = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
transformers_logging.set_verbosity_info()
def _lowercase ( __UpperCamelCase : Dict ):
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 _lowercase ( __UpperCamelCase : Optional[int] , __UpperCamelCase : Any , __UpperCamelCase : int ):
return max(metric_fn(__UpperCamelCase , __UpperCamelCase ) for gt in ground_truths )
def _lowercase ( __UpperCamelCase : List[str] , __UpperCamelCase : Optional[Any] , __UpperCamelCase : Union[str, Any] ):
snake_case__ = [line.strip() for line in open(__UpperCamelCase , """r""" ).readlines()]
snake_case__ = []
if args.gold_data_mode == "qa":
snake_case__ = pd.read_csv(__UpperCamelCase , sep="""\t""" , header=__UpperCamelCase )
for answer_list in data[1]:
snake_case__ = ast.literal_eval(__UpperCamelCase )
answers.append(__UpperCamelCase )
else:
snake_case__ = [line.strip() for line in open(__UpperCamelCase , """r""" ).readlines()]
snake_case__ = [[reference] for reference in references]
snake_case__ = snake_case__ = snake_case__ = 0
for prediction, ground_truths in zip(__UpperCamelCase , __UpperCamelCase ):
total += 1
em += metric_max_over_ground_truths(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
fa += metric_max_over_ground_truths(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
snake_case__ = 1_0_0.0 * em / total
snake_case__ = 1_0_0.0 * fa / total
logger.info(F'''F1: {fa:.2f}''' )
logger.info(F'''EM: {em:.2f}''' )
def _lowercase ( __UpperCamelCase : Tuple , __UpperCamelCase : Any , __UpperCamelCase : Union[str, Any] ):
snake_case__ = args.k
snake_case__ = [line.strip() for line in open(__UpperCamelCase , """r""" ).readlines()]
snake_case__ = [line.strip() for line in open(__UpperCamelCase , """r""" ).readlines()]
snake_case__ = snake_case__ = 0
for hypo, reference in zip(__UpperCamelCase , __UpperCamelCase ):
snake_case__ = set(hypo.split("""\t""" )[:k] )
snake_case__ = set(reference.split("""\t""" ) )
total += 1
em += len(hypo_provenance & ref_provenance ) / k
snake_case__ = 1_0_0.0 * em / total
logger.info(F'''Precision@{k}: {em: .2f}''' )
def _lowercase ( __UpperCamelCase : Optional[Any] , __UpperCamelCase : Dict , __UpperCamelCase : Dict ):
def strip_title(__UpperCamelCase : List[Any] ):
if title.startswith("""\"""" ):
snake_case__ = title[1:]
if title.endswith("""\"""" ):
snake_case__ = title[:-1]
return title
snake_case__ = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
__UpperCamelCase , return_tensors="""pt""" , padding=__UpperCamelCase , truncation=__UpperCamelCase , )["""input_ids"""].to(args.device )
snake_case__ = rag_model.rag.question_encoder(__UpperCamelCase )
snake_case__ = question_enc_outputs[0]
snake_case__ = rag_model.retriever(
__UpperCamelCase , 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""" , )
snake_case__ = rag_model.retriever.index.get_doc_dicts(result.doc_ids )
snake_case__ = []
for docs in all_docs:
snake_case__ = [strip_title(__UpperCamelCase ) for title in docs["""title"""]]
provenance_strings.append("""\t""".join(__UpperCamelCase ) )
return provenance_strings
def _lowercase ( __UpperCamelCase : Union[str, Any] , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : List[Any] ):
with torch.no_grad():
snake_case__ = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
__UpperCamelCase , return_tensors="""pt""" , padding=__UpperCamelCase , truncation=__UpperCamelCase )
snake_case__ = inputs_dict.input_ids.to(args.device )
snake_case__ = inputs_dict.attention_mask.to(args.device )
snake_case__ = rag_model.generate( # rag_model overwrites generate
__UpperCamelCase , attention_mask=__UpperCamelCase , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=__UpperCamelCase , num_return_sequences=1 , bad_words_ids=[[0, 0]] , )
snake_case__ = rag_model.retriever.generator_tokenizer.batch_decode(__UpperCamelCase , skip_special_tokens=__UpperCamelCase )
if args.print_predictions:
for q, a in zip(__UpperCamelCase , __UpperCamelCase ):
logger.info("""Q: {} - A: {}""".format(__UpperCamelCase , __UpperCamelCase ) )
return answers
def _lowercase ( ):
snake_case__ = argparse.ArgumentParser()
parser.add_argument(
"""--model_type""" , choices=["""rag_sequence""", """rag_token""", """bart"""] , type=__UpperCamelCase , 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=__UpperCamelCase , choices=["""exact""", """compressed""", """legacy"""] , type=__UpperCamelCase , help="""RAG model retriever type""" , )
parser.add_argument(
"""--index_path""" , default=__UpperCamelCase , type=__UpperCamelCase , help="""Path to the retrieval index""" , )
parser.add_argument("""--n_docs""" , default=5 , type=__UpperCamelCase , help="""Number of retrieved docs""" )
parser.add_argument(
"""--model_name_or_path""" , default=__UpperCamelCase , type=__UpperCamelCase , required=__UpperCamelCase , help="""Path to pretrained checkpoints or model identifier from huggingface.co/models""" , )
parser.add_argument(
"""--eval_mode""" , choices=["""e2e""", """retrieval"""] , default="""e2e""" , type=__UpperCamelCase , help=(
"""Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates"""
""" precision@k."""
) , )
parser.add_argument("""--k""" , default=1 , type=__UpperCamelCase , help="""k for the precision@k calculation""" )
parser.add_argument(
"""--evaluation_set""" , default=__UpperCamelCase , type=__UpperCamelCase , required=__UpperCamelCase , help="""Path to a file containing evaluation samples""" , )
parser.add_argument(
"""--gold_data_path""" , default=__UpperCamelCase , type=__UpperCamelCase , required=__UpperCamelCase , help="""Path to a tab-separated file with gold samples""" , )
parser.add_argument(
"""--gold_data_mode""" , default="""qa""" , type=__UpperCamelCase , 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=__UpperCamelCase , 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=__UpperCamelCase , 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=__UpperCamelCase , help="""Number of beams to be used when generating answers""" , )
parser.add_argument("""--min_length""" , default=1 , type=__UpperCamelCase , help="""Min length of the generated answers""" )
parser.add_argument("""--max_length""" , default=50 , type=__UpperCamelCase , 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.""" , )
snake_case__ = parser.parse_args()
snake_case__ = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" )
return args
def _lowercase ( __UpperCamelCase : Union[str, Any] ):
snake_case__ = {}
if args.model_type is None:
snake_case__ = infer_model_type(args.model_name_or_path )
assert args.model_type is not None
if args.model_type.startswith("""rag""" ):
snake_case__ = RagTokenForGeneration if args.model_type == """rag_token""" else RagSequenceForGeneration
snake_case__ = args.n_docs
if args.index_name is not None:
snake_case__ = args.index_name
if args.index_path is not None:
snake_case__ = args.index_path
else:
snake_case__ = BartForConditionalGeneration
snake_case__ = (
[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""" , __UpperCamelCase )
snake_case__ = get_scores if args.eval_mode == """e2e""" else get_precision_at_k
snake_case__ = 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(__UpperCamelCase , args.predictions_path , args.gold_data_path )
continue
logger.info("""***** Running evaluation for {} *****""".format(__UpperCamelCase ) )
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""" ):
snake_case__ = RagRetriever.from_pretrained(__UpperCamelCase , **__UpperCamelCase )
snake_case__ = model_class.from_pretrained(__UpperCamelCase , retriever=__UpperCamelCase , **__UpperCamelCase )
model.retriever.init_retrieval()
else:
snake_case__ = model_class.from_pretrained(__UpperCamelCase , **__UpperCamelCase )
model.to(args.device )
with open(args.evaluation_set , """r""" ) as eval_file, open(args.predictions_path , """w""" ) as preds_file:
snake_case__ = []
for line in tqdm(__UpperCamelCase ):
questions.append(line.strip() )
if len(__UpperCamelCase ) == args.eval_batch_size:
snake_case__ = evaluate_batch_fn(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
preds_file.write("""\n""".join(__UpperCamelCase ) + """\n""" )
preds_file.flush()
snake_case__ = []
if len(__UpperCamelCase ) > 0:
snake_case__ = evaluate_batch_fn(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
preds_file.write("""\n""".join(__UpperCamelCase ) )
preds_file.flush()
score_fn(__UpperCamelCase , args.predictions_path , args.gold_data_path )
if __name__ == "__main__":
lowerCAmelCase : int = get_args()
main(args)
| 214 |
import warnings
from ...utils import logging
from .image_processing_beit import BeitImageProcessor
lowerCAmelCase : int = logging.get_logger(__name__)
class SCREAMING_SNAKE_CASE__ ( __a ):
'''simple docstring'''
def __init__( self : Tuple , *lowerCAmelCase__ : str , **lowerCAmelCase__ : List[Any] ) -> None:
warnings.warn(
"""The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"""
""" use BeitImageProcessor instead.""" , lowerCAmelCase__ , )
super().__init__(*lowerCAmelCase__ , **lowerCAmelCase__ )
| 214 | 1 |
"""simple docstring"""
def A_ ( UpperCAmelCase__ = 50 ) -> int:
a : str = [1] * (length + 1)
for row_length in range(3 , length + 1 ):
for block_length in range(3 , row_length + 1 ):
for block_start in range(row_length - block_length ):
ways_number[row_length] += ways_number[
row_length - block_start - block_length - 1
]
ways_number[row_length] += 1
return ways_number[length]
if __name__ == "__main__":
print(F'{solution() = }')
| 702 |
"""simple docstring"""
import os
from shutil import copyfile
from typing import List, Optional, Tuple
from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging
if is_sentencepiece_available():
from .tokenization_camembert import CamembertTokenizer
else:
SCREAMING_SNAKE_CASE__ : str = None
SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE__ : str = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"}
SCREAMING_SNAKE_CASE__ : Optional[int] = {
"vocab_file": {
"camembert-base": "https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model",
},
"tokenizer_file": {
"camembert-base": "https://huggingface.co/camembert-base/resolve/main/tokenizer.json",
},
}
SCREAMING_SNAKE_CASE__ : Dict = {
"camembert-base": 512,
}
SCREAMING_SNAKE_CASE__ : int = "▁"
class A_ ( _UpperCAmelCase ):
"""simple docstring"""
lowercase : Optional[Any] = VOCAB_FILES_NAMES
lowercase : int = PRETRAINED_VOCAB_FILES_MAP
lowercase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowercase : List[str] = ["input_ids", "attention_mask"]
lowercase : Union[str, Any] = CamembertTokenizer
def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase="<s>" , __UpperCAmelCase="</s>" , __UpperCAmelCase="</s>" , __UpperCAmelCase="<s>" , __UpperCAmelCase="<unk>" , __UpperCAmelCase="<pad>" , __UpperCAmelCase="<mask>" , __UpperCAmelCase=["<s>NOTUSED", "</s>NOTUSED"] , **__UpperCAmelCase , ) -> Dict:
# Mask token behave like a normal word, i.e. include the space before it
a : List[Any] = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else mask_token
super().__init__(
__UpperCAmelCase , tokenizer_file=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , additional_special_tokens=__UpperCAmelCase , **__UpperCAmelCase , )
a : Optional[int] = vocab_file
a : Union[str, Any] = False if not self.vocab_file else True
def lowercase_ ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> List[int]:
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
a : Optional[Any] = [self.cls_token_id]
a : Any = [self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def lowercase_ ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> List[int]:
a : Tuple = [self.sep_token_id]
a : Any = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
def lowercase_ ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> Tuple[str]:
if not self.can_save_slow_tokenizer:
raise ValueError(
'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow '
'tokenizer.' )
if not os.path.isdir(__UpperCAmelCase ):
logger.error(f'Vocabulary path ({save_directory}) should be a directory' )
return
a : Optional[Any] = os.path.join(
__UpperCAmelCase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ):
copyfile(self.vocab_file , __UpperCAmelCase )
return (out_vocab_file,)
| 509 | 0 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase_ : Any = logging.get_logger(__name__)
UpperCamelCase_ : List[str] = {
'''vinvino02/glpn-kitti''': '''https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json''',
# See all GLPN models at https://huggingface.co/models?filter=glpn
}
class __lowerCAmelCase ( _lowercase ):
"""simple docstring"""
snake_case = "glpn"
def __init__( self : Dict , _snake_case : Any=3 , _snake_case : Union[str, Any]=4 , _snake_case : int=[2, 2, 2, 2] , _snake_case : str=[8, 4, 2, 1] , _snake_case : Tuple=[32, 64, 160, 256] , _snake_case : List[str]=[7, 3, 3, 3] , _snake_case : Union[str, Any]=[4, 2, 2, 2] , _snake_case : List[str]=[1, 2, 5, 8] , _snake_case : List[str]=[4, 4, 4, 4] , _snake_case : int="gelu" , _snake_case : str=0.0 , _snake_case : str=0.0 , _snake_case : int=0.0_2 , _snake_case : Tuple=0.1 , _snake_case : Tuple=1e-6 , _snake_case : Tuple=64 , _snake_case : Tuple=10 , _snake_case : Dict=-1 , **_snake_case : Any , ) -> List[Any]:
"""simple docstring"""
super().__init__(**_snake_case )
A_ = num_channels
A_ = num_encoder_blocks
A_ = depths
A_ = sr_ratios
A_ = hidden_sizes
A_ = patch_sizes
A_ = strides
A_ = mlp_ratios
A_ = num_attention_heads
A_ = hidden_act
A_ = hidden_dropout_prob
A_ = attention_probs_dropout_prob
A_ = initializer_range
A_ = drop_path_rate
A_ = layer_norm_eps
A_ = decoder_hidden_size
A_ = max_depth
A_ = head_in_index
| 115 |
"""simple docstring"""
import math
from typing import Any, Callable, List, Optional, Tuple, Union
import numpy as np
import torch
from ...models import TaFilmDecoder
from ...schedulers import DDPMScheduler
from ...utils import is_onnx_available, logging, randn_tensor
if is_onnx_available():
from ..onnx_utils import OnnxRuntimeModel
from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline
from .continous_encoder import SpectrogramContEncoder
from .notes_encoder import SpectrogramNotesEncoder
UpperCamelCase_ : Any = logging.get_logger(__name__) # pylint: disable=invalid-name
UpperCamelCase_ : List[Any] = 256
class __lowerCAmelCase ( _lowercase ):
"""simple docstring"""
snake_case = ["melgan"]
def __init__( self : Dict , _snake_case : SpectrogramNotesEncoder , _snake_case : SpectrogramContEncoder , _snake_case : TaFilmDecoder , _snake_case : DDPMScheduler , _snake_case : OnnxRuntimeModel if is_onnx_available() else Any , ) -> None:
"""simple docstring"""
super().__init__()
# From MELGAN
A_ = math.log(1e-5 ) # Matches MelGAN training.
A_ = 4.0 # Largest value for most examples
A_ = 128
self.register_modules(
notes_encoder=_snake_case , continuous_encoder=_snake_case , decoder=_snake_case , scheduler=_snake_case , melgan=_snake_case , )
def lowerCamelCase__ ( self : Union[str, Any] , _snake_case : Tuple , _snake_case : str=(-1.0, 1.0) , _snake_case : int=False ) -> str:
"""simple docstring"""
A_ , A_ = output_range
if clip:
A_ = torch.clip(_snake_case , self.min_value , self.max_value )
# Scale to [0, 1].
A_ = (features - self.min_value) / (self.max_value - self.min_value)
# Scale to [min_out, max_out].
return zero_one * (max_out - min_out) + min_out
def lowerCamelCase__ ( self : Dict , _snake_case : Tuple , _snake_case : Optional[Any]=(-1.0, 1.0) , _snake_case : List[str]=False ) -> List[str]:
"""simple docstring"""
A_ , A_ = input_range
A_ = torch.clip(_snake_case , _snake_case , _snake_case ) if clip else outputs
# Scale to [0, 1].
A_ = (outputs - min_out) / (max_out - min_out)
# Scale to [self.min_value, self.max_value].
return zero_one * (self.max_value - self.min_value) + self.min_value
def lowerCamelCase__ ( self : Union[str, Any] , _snake_case : str , _snake_case : List[Any] , _snake_case : Union[str, Any] ) -> List[str]:
"""simple docstring"""
A_ = input_tokens > 0
A_ , A_ = self.notes_encoder(
encoder_input_tokens=_snake_case , encoder_inputs_mask=_snake_case )
A_ , A_ = self.continuous_encoder(
encoder_inputs=_snake_case , encoder_inputs_mask=_snake_case )
return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)]
def lowerCamelCase__ ( self : List[Any] , _snake_case : List[Any] , _snake_case : int , _snake_case : Tuple ) -> Optional[int]:
"""simple docstring"""
A_ = noise_time
if not torch.is_tensor(_snake_case ):
A_ = torch.tensor([timesteps] , dtype=torch.long , device=input_tokens.device )
elif torch.is_tensor(_snake_case ) and len(timesteps.shape ) == 0:
A_ = timesteps[None].to(input_tokens.device )
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
A_ = timesteps * torch.ones(input_tokens.shape[0] , dtype=timesteps.dtype , device=timesteps.device )
A_ = self.decoder(
encodings_and_masks=_snake_case , decoder_input_tokens=_snake_case , decoder_noise_time=_snake_case )
return logits
@torch.no_grad()
def __call__( self : List[Any] , _snake_case : List[List[int]] , _snake_case : Optional[torch.Generator] = None , _snake_case : int = 100 , _snake_case : bool = True , _snake_case : str = "numpy" , _snake_case : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , _snake_case : int = 1 , ) -> Union[AudioPipelineOutput, Tuple]:
"""simple docstring"""
if (callback_steps is None) or (
callback_steps is not None and (not isinstance(_snake_case , _snake_case ) or callback_steps <= 0)
):
raise ValueError(
F'`callback_steps` has to be a positive integer but is {callback_steps} of type'
F' {type(_snake_case )}.' )
A_ = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] , dtype=np.floataa )
A_ = np.zeros([1, 0, self.n_dims] , np.floataa )
A_ = torch.ones((1, TARGET_FEATURE_LENGTH) , dtype=_snake_case , device=self.device )
for i, encoder_input_tokens in enumerate(_snake_case ):
if i == 0:
A_ = torch.from_numpy(pred_mel[:1].copy() ).to(
device=self.device , dtype=self.decoder.dtype )
# The first chunk has no previous context.
A_ = torch.zeros((1, TARGET_FEATURE_LENGTH) , dtype=_snake_case , device=self.device )
else:
# The full song pipeline does not feed in a context feature, so the mask
# will be all 0s after the feature converter. Because we know we're
# feeding in a full context chunk from the previous prediction, set it
# to all 1s.
A_ = ones
A_ = self.scale_features(
_snake_case , output_range=[-1.0, 1.0] , clip=_snake_case )
A_ = self.encode(
input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device ) , continuous_inputs=_snake_case , continuous_mask=_snake_case , )
# Sample encoder_continuous_inputs shaped gaussian noise to begin loop
A_ = randn_tensor(
shape=encoder_continuous_inputs.shape , generator=_snake_case , device=self.device , dtype=self.decoder.dtype , )
# set step values
self.scheduler.set_timesteps(_snake_case )
# Denoising diffusion loop
for j, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ):
A_ = self.decode(
encodings_and_masks=_snake_case , input_tokens=_snake_case , noise_time=t / self.scheduler.config.num_train_timesteps , )
# Compute previous output: x_t -> x_t-1
A_ = self.scheduler.step(_snake_case , _snake_case , _snake_case , generator=_snake_case ).prev_sample
A_ = self.scale_to_features(_snake_case , input_range=[-1.0, 1.0] )
A_ = mel[:1]
A_ = mel.cpu().float().numpy()
A_ = np.concatenate([full_pred_mel, pred_mel[:1]] , axis=1 )
# call the callback, if provided
if callback is not None and i % callback_steps == 0:
callback(_snake_case , _snake_case )
logger.info("Generated segment" , _snake_case )
if output_type == "numpy" and not is_onnx_available():
raise ValueError(
"Cannot return output in 'np' format if ONNX is not available. Make sure to have ONNX installed or set 'output_type' to 'mel'." )
elif output_type == "numpy" and self.melgan is None:
raise ValueError(
"Cannot return output in 'np' format if melgan component is not defined. Make sure to define `self.melgan` or set 'output_type' to 'mel'." )
if output_type == "numpy":
A_ = self.melgan(input_features=full_pred_mel.astype(np.floataa ) )
else:
A_ = full_pred_mel
if not return_dict:
return (output,)
return AudioPipelineOutput(audios=_snake_case )
| 115 | 1 |
"""simple docstring"""
from collections import defaultdict
from math import ceil, sqrt
def lowerCAmelCase_( SCREAMING_SNAKE_CASE = 1_00_00_00 , SCREAMING_SNAKE_CASE = 10 ) -> int:
"""simple docstring"""
UpperCamelCase__ = defaultdict(SCREAMING_SNAKE_CASE )
for outer_width in range(3 , (t_limit // 4) + 2 ):
if outer_width * outer_width > t_limit:
UpperCamelCase__ = max(
ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 )
else:
UpperCamelCase__ = 1
hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2
for hole_width in range(SCREAMING_SNAKE_CASE , outer_width - 1 , 2 ):
count[outer_width * outer_width - hole_width * hole_width] += 1
return sum(1 for n in count.values() if 1 <= n <= 10 )
if __name__ == "__main__":
print(F"""{solution() = }""")
| 711 |
"""simple docstring"""
from __future__ import annotations
import os
import tempfile
import unittest
from transformers import ConvBertConfig, 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 import (
TFConvBertForMaskedLM,
TFConvBertForMultipleChoice,
TFConvBertForQuestionAnswering,
TFConvBertForSequenceClassification,
TFConvBertForTokenClassification,
TFConvBertModel,
)
class __lowerCamelCase :
def __init__( self , snake_case_ , snake_case_=13 , snake_case_=7 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=99 , snake_case_=32 , snake_case_=2 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=16 , snake_case_=2 , snake_case_=0.02 , snake_case_=3 , snake_case_=4 , snake_case_=None , ) -> Tuple:
UpperCamelCase__ = parent
UpperCamelCase__ = 13
UpperCamelCase__ = 7
UpperCamelCase__ = True
UpperCamelCase__ = True
UpperCamelCase__ = True
UpperCamelCase__ = True
UpperCamelCase__ = 99
UpperCamelCase__ = 384
UpperCamelCase__ = 2
UpperCamelCase__ = 4
UpperCamelCase__ = 37
UpperCamelCase__ = 'gelu'
UpperCamelCase__ = 0.1
UpperCamelCase__ = 0.1
UpperCamelCase__ = 512
UpperCamelCase__ = 16
UpperCamelCase__ = 2
UpperCamelCase__ = 0.02
UpperCamelCase__ = 3
UpperCamelCase__ = 4
UpperCamelCase__ = 128
UpperCamelCase__ = 2
UpperCamelCase__ = 9
UpperCamelCase__ = 1
UpperCamelCase__ = None
def SCREAMING_SNAKE_CASE__ ( self ) -> int:
UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
UpperCamelCase__ = None
if self.use_input_mask:
UpperCamelCase__ = random_attention_mask([self.batch_size, self.seq_length] )
UpperCamelCase__ = None
if self.use_token_type_ids:
UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
UpperCamelCase__ = None
UpperCamelCase__ = None
UpperCamelCase__ = None
if self.use_labels:
UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size )
UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices )
UpperCamelCase__ = ConvBertConfig(
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 , return_dict=snake_case_ , )
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int:
UpperCamelCase__ = TFConvBertModel(config=snake_case_ )
UpperCamelCase__ = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
UpperCamelCase__ = [input_ids, input_mask]
UpperCamelCase__ = model(snake_case_ )
UpperCamelCase__ = model(snake_case_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int:
UpperCamelCase__ = TFConvBertForMaskedLM(config=snake_case_ )
UpperCamelCase__ = {
'input_ids': input_ids,
'attention_mask': input_mask,
'token_type_ids': token_type_ids,
}
UpperCamelCase__ = model(snake_case_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[str]:
UpperCamelCase__ = self.num_labels
UpperCamelCase__ = TFConvBertForSequenceClassification(config=snake_case_ )
UpperCamelCase__ = {
'input_ids': input_ids,
'attention_mask': input_mask,
'token_type_ids': token_type_ids,
}
UpperCamelCase__ = model(snake_case_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Tuple:
UpperCamelCase__ = self.num_choices
UpperCamelCase__ = TFConvBertForMultipleChoice(config=snake_case_ )
UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) )
UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) )
UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) )
UpperCamelCase__ = {
'input_ids': multiple_choice_inputs_ids,
'attention_mask': multiple_choice_input_mask,
'token_type_ids': multiple_choice_token_type_ids,
}
UpperCamelCase__ = model(snake_case_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[str]:
UpperCamelCase__ = self.num_labels
UpperCamelCase__ = TFConvBertForTokenClassification(config=snake_case_ )
UpperCamelCase__ = {
'input_ids': input_ids,
'attention_mask': input_mask,
'token_type_ids': token_type_ids,
}
UpperCamelCase__ = model(snake_case_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]:
UpperCamelCase__ = TFConvBertForQuestionAnswering(config=snake_case_ )
UpperCamelCase__ = {
'input_ids': input_ids,
'attention_mask': input_mask,
'token_type_ids': token_type_ids,
}
UpperCamelCase__ = model(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 SCREAMING_SNAKE_CASE__ ( self ) -> Tuple:
UpperCamelCase__ = self.prepare_config_and_inputs()
(
(
UpperCamelCase__
) , (
UpperCamelCase__
) , (
UpperCamelCase__
) , (
UpperCamelCase__
) , (
UpperCamelCase__
) , (
UpperCamelCase__
) , (
UpperCamelCase__
) ,
) = config_and_inputs
UpperCamelCase__ = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
return config, inputs_dict
@require_tf
class __lowerCamelCase ( _a , _a , unittest.TestCase ):
a : Any =(
(
TFConvBertModel,
TFConvBertForMaskedLM,
TFConvBertForQuestionAnswering,
TFConvBertForSequenceClassification,
TFConvBertForTokenClassification,
TFConvBertForMultipleChoice,
)
if is_tf_available()
else ()
)
a : str =(
{
"""feature-extraction""": TFConvBertModel,
"""fill-mask""": TFConvBertForMaskedLM,
"""question-answering""": TFConvBertForQuestionAnswering,
"""text-classification""": TFConvBertForSequenceClassification,
"""token-classification""": TFConvBertForTokenClassification,
"""zero-shot""": TFConvBertForSequenceClassification,
}
if is_tf_available()
else {}
)
a : Any =False
a : Dict =False
a : str =False
def SCREAMING_SNAKE_CASE__ ( self ) -> Dict:
UpperCamelCase__ = TFConvBertModelTester(self )
UpperCamelCase__ = ConfigTester(self , config_class=snake_case_ , hidden_size=37 )
def SCREAMING_SNAKE_CASE__ ( self ) -> int:
self.config_tester.run_common_tests()
def SCREAMING_SNAKE_CASE__ ( self ) -> int:
UpperCamelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*snake_case_ )
def SCREAMING_SNAKE_CASE__ ( self ) -> Dict:
UpperCamelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*snake_case_ )
def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]:
UpperCamelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*snake_case_ )
def SCREAMING_SNAKE_CASE__ ( self ) -> Dict:
UpperCamelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*snake_case_ )
def SCREAMING_SNAKE_CASE__ ( self ) -> int:
UpperCamelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*snake_case_ )
def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]:
UpperCamelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*snake_case_ )
@slow
def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]:
UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common()
UpperCamelCase__ = True
UpperCamelCase__ = True
if hasattr(snake_case_ , 'use_cache' ):
UpperCamelCase__ = True
UpperCamelCase__ = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length )
UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ )
for model_class in self.all_model_classes:
UpperCamelCase__ = self._prepare_for_class(snake_case_ , snake_case_ )
UpperCamelCase__ = model_class(snake_case_ )
UpperCamelCase__ = len(model(snake_case_ ) )
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(snake_case_ , saved_model=snake_case_ )
UpperCamelCase__ = os.path.join(snake_case_ , 'saved_model' , '1' )
UpperCamelCase__ = tf.keras.models.load_model(snake_case_ )
UpperCamelCase__ = model(snake_case_ )
if self.is_encoder_decoder:
UpperCamelCase__ = outputs['encoder_hidden_states']
UpperCamelCase__ = outputs['encoder_attentions']
else:
UpperCamelCase__ = outputs['hidden_states']
UpperCamelCase__ = outputs['attentions']
self.assertEqual(len(snake_case_ ) , snake_case_ )
UpperCamelCase__ = getattr(
self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1 )
self.assertEqual(len(snake_case_ ) , snake_case_ )
self.assertListEqual(
list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , )
self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers )
self.assertListEqual(
list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , )
@slow
def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]:
UpperCamelCase__ = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' )
self.assertIsNotNone(snake_case_ )
def SCREAMING_SNAKE_CASE__ ( self ) -> Dict:
UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common()
UpperCamelCase__ = True
UpperCamelCase__ = getattr(self.model_tester , 'decoder_seq_length' , self.model_tester.seq_length )
UpperCamelCase__ = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length )
UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ )
UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ )
def check_decoder_attentions_output(snake_case_ ):
UpperCamelCase__ = len(snake_case_ )
self.assertEqual(out_len % 2 , 0 )
UpperCamelCase__ = outputs.decoder_attentions
self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers )
self.assertListEqual(
list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , )
def check_encoder_attentions_output(snake_case_ ):
UpperCamelCase__ = [
t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions)
]
self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers )
self.assertListEqual(
list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , )
for model_class in self.all_model_classes:
UpperCamelCase__ = True
UpperCamelCase__ = False
UpperCamelCase__ = model_class(snake_case_ )
UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) )
UpperCamelCase__ = len(snake_case_ )
self.assertEqual(config.output_hidden_states , snake_case_ )
check_encoder_attentions_output(snake_case_ )
if self.is_encoder_decoder:
UpperCamelCase__ = model_class(snake_case_ )
UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) )
self.assertEqual(config.output_hidden_states , snake_case_ )
check_decoder_attentions_output(snake_case_ )
# Check that output attentions can also be changed via the config
del inputs_dict["output_attentions"]
UpperCamelCase__ = True
UpperCamelCase__ = model_class(snake_case_ )
UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) )
self.assertEqual(config.output_hidden_states , snake_case_ )
check_encoder_attentions_output(snake_case_ )
# Check attention is always last and order is fine
UpperCamelCase__ = True
UpperCamelCase__ = True
UpperCamelCase__ = model_class(snake_case_ )
UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) )
self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(snake_case_ ) )
self.assertEqual(model.config.output_hidden_states , snake_case_ )
check_encoder_attentions_output(snake_case_ )
@require_tf
class __lowerCamelCase ( unittest.TestCase ):
@slow
def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]:
UpperCamelCase__ = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' )
UpperCamelCase__ = tf.constant([[0, 1, 2, 3, 4, 5]] )
UpperCamelCase__ = model(snake_case_ )[0]
UpperCamelCase__ = [1, 6, 768]
self.assertEqual(output.shape , snake_case_ )
UpperCamelCase__ = tf.constant(
[
[
[-0.03_475_493, -0.4_686_034, -0.30_638_832],
[0.22_637_248, -0.26_988_646, -0.7_423_424],
[0.10_324_868, -0.45_013_508, -0.58_280_784],
]
] )
tf.debugging.assert_near(output[:, :3, :3] , snake_case_ , atol=1E-4 )
| 20 | 0 |
from __future__ import annotations
def _UpperCamelCase (a__ :float , a__ :float , a__ :float ):
"""simple docstring"""
if days_between_payments <= 0:
raise ValueError("""days_between_payments must be > 0""" )
if daily_interest_rate < 0:
raise ValueError("""daily_interest_rate must be >= 0""" )
if principal <= 0:
raise ValueError("""principal must be > 0""" )
return principal * daily_interest_rate * days_between_payments
def _UpperCamelCase (a__ :float , a__ :float , a__ :float , ):
"""simple docstring"""
if number_of_compounding_periods <= 0:
raise ValueError("""number_of_compounding_periods must be > 0""" )
if nominal_annual_interest_rate_percentage < 0:
raise ValueError("""nominal_annual_interest_rate_percentage must be >= 0""" )
if principal <= 0:
raise ValueError("""principal must be > 0""" )
return principal * (
(1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods
- 1
)
def _UpperCamelCase (a__ :float , a__ :float , a__ :float , ):
"""simple docstring"""
if number_of_years <= 0:
raise ValueError("""number_of_years must be > 0""" )
if nominal_annual_percentage_rate < 0:
raise ValueError("""nominal_annual_percentage_rate must be >= 0""" )
if principal <= 0:
raise ValueError("""principal must be > 0""" )
return compound_interest(
a__ , nominal_annual_percentage_rate / 365 , number_of_years * 365 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 619 |
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_roberta import RobertaTokenizer
UpperCamelCase__ = logging.get_logger(__name__)
UpperCamelCase__ = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
UpperCamelCase__ = {
"vocab_file": {
"roberta-base": "https://huggingface.co/roberta-base/resolve/main/vocab.json",
"roberta-large": "https://huggingface.co/roberta-large/resolve/main/vocab.json",
"roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/vocab.json",
"distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/vocab.json",
"roberta-base-openai-detector": "https://huggingface.co/roberta-base-openai-detector/resolve/main/vocab.json",
"roberta-large-openai-detector": (
"https://huggingface.co/roberta-large-openai-detector/resolve/main/vocab.json"
),
},
"merges_file": {
"roberta-base": "https://huggingface.co/roberta-base/resolve/main/merges.txt",
"roberta-large": "https://huggingface.co/roberta-large/resolve/main/merges.txt",
"roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/merges.txt",
"distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/merges.txt",
"roberta-base-openai-detector": "https://huggingface.co/roberta-base-openai-detector/resolve/main/merges.txt",
"roberta-large-openai-detector": (
"https://huggingface.co/roberta-large-openai-detector/resolve/main/merges.txt"
),
},
"tokenizer_file": {
"roberta-base": "https://huggingface.co/roberta-base/resolve/main/tokenizer.json",
"roberta-large": "https://huggingface.co/roberta-large/resolve/main/tokenizer.json",
"roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/tokenizer.json",
"distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/tokenizer.json",
"roberta-base-openai-detector": (
"https://huggingface.co/roberta-base-openai-detector/resolve/main/tokenizer.json"
),
"roberta-large-openai-detector": (
"https://huggingface.co/roberta-large-openai-detector/resolve/main/tokenizer.json"
),
},
}
UpperCamelCase__ = {
"roberta-base": 512,
"roberta-large": 512,
"roberta-large-mnli": 512,
"distilroberta-base": 512,
"roberta-base-openai-detector": 512,
"roberta-large-openai-detector": 512,
}
class __SCREAMING_SNAKE_CASE ( _a ):
snake_case : Optional[Any] = VOCAB_FILES_NAMES
snake_case : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP
snake_case : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
snake_case : Dict = ["""input_ids""", """attention_mask"""]
snake_case : List[Any] = RobertaTokenizer
def __init__( self , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase="replace" , __lowerCAmelCase="<s>" , __lowerCAmelCase="</s>" , __lowerCAmelCase="</s>" , __lowerCAmelCase="<s>" , __lowerCAmelCase="<unk>" , __lowerCAmelCase="<pad>" , __lowerCAmelCase="<mask>" , __lowerCAmelCase=False , __lowerCAmelCase=True , **__lowerCAmelCase , ):
super().__init__(
__lowerCAmelCase , __lowerCAmelCase , tokenizer_file=__lowerCAmelCase , errors=__lowerCAmelCase , bos_token=__lowerCAmelCase , eos_token=__lowerCAmelCase , sep_token=__lowerCAmelCase , cls_token=__lowerCAmelCase , unk_token=__lowerCAmelCase , pad_token=__lowerCAmelCase , mask_token=__lowerCAmelCase , add_prefix_space=__lowerCAmelCase , trim_offsets=__lowerCAmelCase , **__lowerCAmelCase , )
UpperCamelCase__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
if pre_tok_state.get("""add_prefix_space""" , __lowerCAmelCase ) != add_prefix_space:
UpperCamelCase__ = getattr(__lowerCAmelCase , pre_tok_state.pop("""type""" ) )
UpperCamelCase__ = add_prefix_space
UpperCamelCase__ = pre_tok_class(**__lowerCAmelCase )
UpperCamelCase__ = add_prefix_space
UpperCamelCase__ = """post_processor"""
UpperCamelCase__ = getattr(self.backend_tokenizer , __lowerCAmelCase , __lowerCAmelCase )
if tokenizer_component_instance:
UpperCamelCase__ = 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__ = tuple(state["""sep"""] )
if "cls" in state:
UpperCamelCase__ = tuple(state["""cls"""] )
UpperCamelCase__ = False
if state.get("""add_prefix_space""" , __lowerCAmelCase ) != add_prefix_space:
UpperCamelCase__ = add_prefix_space
UpperCamelCase__ = True
if state.get("""trim_offsets""" , __lowerCAmelCase ) != trim_offsets:
UpperCamelCase__ = trim_offsets
UpperCamelCase__ = True
if changes_to_apply:
UpperCamelCase__ = getattr(__lowerCAmelCase , state.pop("""type""" ) )
UpperCamelCase__ = component_class(**__lowerCAmelCase )
setattr(self.backend_tokenizer , __lowerCAmelCase , __lowerCAmelCase )
@property
def _lowerCamelCase ( 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 _lowerCamelCase ( self , __lowerCAmelCase ):
UpperCamelCase__ = AddedToken(__lowerCAmelCase , lstrip=__lowerCAmelCase , rstrip=__lowerCAmelCase ) if isinstance(__lowerCAmelCase , __lowerCAmelCase ) else value
UpperCamelCase__ = value
def _lowerCamelCase ( self , *__lowerCAmelCase , **__lowerCAmelCase ):
UpperCamelCase__ = kwargs.get("""is_split_into_words""" , __lowerCAmelCase )
assert self.add_prefix_space or not is_split_into_words, (
f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
"to use it with pretokenized inputs."
)
return super()._batch_encode_plus(*__lowerCAmelCase , **__lowerCAmelCase )
def _lowerCamelCase ( self , *__lowerCAmelCase , **__lowerCAmelCase ):
UpperCamelCase__ = kwargs.get("""is_split_into_words""" , __lowerCAmelCase )
assert self.add_prefix_space or not is_split_into_words, (
f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
"to use it with pretokenized inputs."
)
return super()._encode_plus(*__lowerCAmelCase , **__lowerCAmelCase )
def _lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase = None ):
UpperCamelCase__ = self._tokenizer.model.save(__lowerCAmelCase , name=__lowerCAmelCase )
return tuple(__lowerCAmelCase )
def _lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase=None ):
UpperCamelCase__ = [self.bos_token_id] + token_ids_a + [self.eos_token_id]
if token_ids_a is None:
return output
return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]
def _lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase = None ):
UpperCamelCase__ = [self.sep_token_id]
UpperCamelCase__ = [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]
| 619 | 1 |
import math
def __A ( _lowercase ):
'''simple docstring'''
_A = []
_A = 2
_A = int(math.sqrt(_lowercase ) ) # Size of every segment
_A = [True] * (end + 1)
_A = []
while start <= end:
if temp[start] is True:
in_prime.append(_lowercase )
for i in range(start * start , end + 1 , _lowercase ):
_A = False
start += 1
prime += in_prime
_A = end + 1
_A = min(2 * end , _lowercase )
while low <= n:
_A = [True] * (high - low + 1)
for each in in_prime:
_A = math.floor(low / each ) * each
if t < low:
t += each
for j in range(_lowercase , high + 1 , _lowercase ):
_A = False
for j in range(len(_lowercase ) ):
if temp[j] is True:
prime.append(j + low )
_A = high + 1
_A = min(high + end , _lowercase )
return prime
print(sieve(10**6))
| 62 |
import dataclasses
import json
import sys
import types
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError
from copy import copy
from enum import Enum
from inspect import isclass
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints
import yaml
__A = NewType('DataClass', Any)
__A = NewType('DataClassType', Any)
def __A ( _lowercase ):
'''simple docstring'''
if isinstance(_lowercase , _lowercase ):
return v
if v.lower() in ("yes", "true", "t", "y", "1"):
return True
elif v.lower() in ("no", "false", "f", "n", "0"):
return False
else:
raise ArgumentTypeError(
f"""Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).""" )
def __A ( _lowercase ):
'''simple docstring'''
_A = {str(_lowercase ): choice for choice in choices}
return lambda _lowercase : str_to_choice.get(_lowercase , _lowercase )
def __A ( *,
_lowercase = None , _lowercase = None , _lowercase = dataclasses.MISSING , _lowercase = dataclasses.MISSING , _lowercase = None , **_lowercase , ):
'''simple docstring'''
if metadata is None:
# Important, don't use as default param in function signature because dict is mutable and shared across function calls
_A = {}
if aliases is not None:
_A = aliases
if help is not None:
_A = help
return dataclasses.field(metadata=_lowercase , default=_lowercase , default_factory=_lowercase , **_lowercase )
class SCREAMING_SNAKE_CASE ( snake_case ):
"""simple docstring"""
A_ = 42
def __init__( self: Optional[Any] , __A: Union[DataClassType, Iterable[DataClassType]] , **__A: List[Any] ) -> str:
# To make the default appear when using --help
if "formatter_class" not in kwargs:
_A = ArgumentDefaultsHelpFormatter
super().__init__(**__A )
if dataclasses.is_dataclass(__A ):
_A = [dataclass_types]
_A = list(__A )
for dtype in self.dataclass_types:
self._add_dataclass_arguments(__A )
@staticmethod
def __A ( __A: ArgumentParser , __A: dataclasses.Field ) -> str:
_A = f"""--{field.name}"""
_A = field.metadata.copy()
# field.metadata is not used at all by Data Classes,
# it is provided as a third-party extension mechanism.
if isinstance(field.type , __A ):
raise RuntimeError(
'''Unresolved type detected, which should have been done with the help of '''
'''`typing.get_type_hints` method by default''' )
_A = kwargs.pop('''aliases''' , [] )
if isinstance(__A , __A ):
_A = [aliases]
_A = getattr(field.type , '''__origin__''' , field.type )
if origin_type is Union or (hasattr(__A , '''UnionType''' ) and isinstance(__A , types.UnionType )):
if str not in field.type.__args__ and (
len(field.type.__args__ ) != 2 or type(__A ) not in field.type.__args__
):
raise ValueError(
'''Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because'''
''' the argument parser only supports one type per argument.'''
f""" Problem encountered in field '{field.name}'.""" )
if type(__A ) not in field.type.__args__:
# filter `str` in Union
_A = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1]
_A = getattr(field.type , '''__origin__''' , field.type )
elif bool not in field.type.__args__:
# filter `NoneType` in Union (except for `Union[bool, NoneType]`)
_A = (
field.type.__args__[0] if isinstance(__A , field.type.__args__[1] ) else field.type.__args__[1]
)
_A = getattr(field.type , '''__origin__''' , field.type )
# A variable to store kwargs for a boolean field, if needed
# so that we can init a `no_*` complement argument (see below)
_A = {}
if origin_type is Literal or (isinstance(field.type , __A ) and issubclass(field.type , __A )):
if origin_type is Literal:
_A = field.type.__args__
else:
_A = [x.value for x in field.type]
_A = make_choice_type_function(kwargs['''choices'''] )
if field.default is not dataclasses.MISSING:
_A = field.default
else:
_A = True
elif field.type is bool or field.type == Optional[bool]:
# Copy the currect kwargs to use to instantiate a `no_*` complement argument below.
# We do not initialize it here because the `no_*` alternative must be instantiated after the real argument
_A = copy(__A )
# Hack because type=bool in argparse does not behave as we want.
_A = string_to_bool
if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING):
# Default value is False if we have no default when of type bool.
_A = False if field.default is dataclasses.MISSING else field.default
# This is the value that will get picked if we don't include --field_name in any way
_A = default
# This tells argparse we accept 0 or 1 value after --field_name
_A = '''?'''
# This is the value that will get picked if we do --field_name (without value)
_A = True
elif isclass(__A ) and issubclass(__A , __A ):
_A = field.type.__args__[0]
_A = '''+'''
if field.default_factory is not dataclasses.MISSING:
_A = field.default_factory()
elif field.default is dataclasses.MISSING:
_A = True
else:
_A = field.type
if field.default is not dataclasses.MISSING:
_A = field.default
elif field.default_factory is not dataclasses.MISSING:
_A = field.default_factory()
else:
_A = True
parser.add_argument(__A , *__A , **__A )
# Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added.
# Order is important for arguments with the same destination!
# We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down
# here and we do not need those changes/additional keys.
if field.default is True and (field.type is bool or field.type == Optional[bool]):
_A = False
parser.add_argument(f"""--no_{field.name}""" , action='''store_false''' , dest=field.name , **__A )
def __A ( self: Dict , __A: DataClassType ) -> List[Any]:
if hasattr(__A , '''_argument_group_name''' ):
_A = self.add_argument_group(dtype._argument_group_name )
else:
_A = self
try:
_A = get_type_hints(__A )
except NameError:
raise RuntimeError(
f"""Type resolution failed for {dtype}. Try declaring the class in global scope or """
'''removing line of `from __future__ import annotations` which opts in Postponed '''
'''Evaluation of Annotations (PEP 563)''' )
except TypeError as ex:
# Remove this block when we drop Python 3.9 support
if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(__A ):
_A = '''.'''.join(map(__A , sys.version_info[:3] ) )
raise RuntimeError(
f"""Type resolution failed for {dtype} on Python {python_version}. Try removing """
'''line of `from __future__ import annotations` which opts in union types as '''
'''`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To '''
'''support Python versions that lower than 3.10, you need to use '''
'''`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of '''
'''`X | None`.''' ) from ex
raise
for field in dataclasses.fields(__A ):
if not field.init:
continue
_A = type_hints[field.name]
self._parse_dataclass_field(__A , __A )
def __A ( self: int , __A: Any=None , __A: int=False , __A: Any=True , __A: Optional[Any]=None , __A: Any=None , ) -> Tuple[DataClass, ...]:
if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )):
_A = []
if args_filename:
args_files.append(Path(__A ) )
elif look_for_args_file and len(sys.argv ):
args_files.append(Path(sys.argv[0] ).with_suffix('''.args''' ) )
# args files specified via command line flag should overwrite default args files so we add them last
if args_file_flag:
# Create special parser just to extract the args_file_flag values
_A = ArgumentParser()
args_file_parser.add_argument(__A , type=__A , action='''append''' )
# Use only remaining args for further parsing (remove the args_file_flag)
_A ,_A = args_file_parser.parse_known_args(args=__A )
_A = vars(__A ).get(args_file_flag.lstrip('''-''' ) , __A )
if cmd_args_file_paths:
args_files.extend([Path(__A ) for p in cmd_args_file_paths] )
_A = []
for args_file in args_files:
if args_file.exists():
file_args += args_file.read_text().split()
# in case of duplicate arguments the last one has precedence
# args specified via the command line should overwrite args from files, so we add them last
_A = file_args + args if args is not None else file_args + sys.argv[1:]
_A ,_A = self.parse_known_args(args=__A )
_A = []
for dtype in self.dataclass_types:
_A = {f.name for f in dataclasses.fields(__A ) if f.init}
_A = {k: v for k, v in vars(__A ).items() if k in keys}
for k in keys:
delattr(__A , __A )
_A = dtype(**__A )
outputs.append(__A )
if len(namespace.__dict__ ) > 0:
# additional namespace.
outputs.append(__A )
if return_remaining_strings:
return (*outputs, remaining_args)
else:
if remaining_args:
raise ValueError(f"""Some specified arguments are not used by the HfArgumentParser: {remaining_args}""" )
return (*outputs,)
def __A ( self: Tuple , __A: Dict[str, Any] , __A: bool = False ) -> Tuple[DataClass, ...]:
_A = set(args.keys() )
_A = []
for dtype in self.dataclass_types:
_A = {f.name for f in dataclasses.fields(__A ) if f.init}
_A = {k: v for k, v in args.items() if k in keys}
unused_keys.difference_update(inputs.keys() )
_A = dtype(**__A )
outputs.append(__A )
if not allow_extra_keys and unused_keys:
raise ValueError(f"""Some keys are not used by the HfArgumentParser: {sorted(__A )}""" )
return tuple(__A )
def __A ( self: Tuple , __A: str , __A: bool = False ) -> Tuple[DataClass, ...]:
with open(Path(__A ) , encoding='''utf-8''' ) as open_json_file:
_A = json.loads(open_json_file.read() )
_A = self.parse_dict(__A , allow_extra_keys=__A )
return tuple(__A )
def __A ( self: List[Any] , __A: str , __A: bool = False ) -> Tuple[DataClass, ...]:
_A = self.parse_dict(yaml.safe_load(Path(__A ).read_text() ) , allow_extra_keys=__A )
return tuple(__A )
| 62 | 1 |
_lowercase = [
'DownloadConfig',
'DownloadManager',
'DownloadMode',
'StreamingDownloadManager',
]
from .download_config import DownloadConfig
from .download_manager import DownloadManager, DownloadMode
from .streaming_download_manager import StreamingDownloadManager
| 306 |
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
import torch.nn as nn
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer
@dataclass
class lowerCamelCase__ ( A__ ):
__lowerCamelCase = 42
class lowerCamelCase__ ( A__ , A__ ):
@register_to_config
def __init__( self : Any , __a : int = 3 , __a : int = 3 , __a : Tuple[str] = ("DownEncoderBlock2D",) , __a : Tuple[str] = ("UpDecoderBlock2D",) , __a : Tuple[int] = (64,) , __a : int = 1 , __a : str = "silu" , __a : int = 3 , __a : int = 32 , __a : int = 256 , __a : int = 32 , __a : Optional[int] = None , __a : float = 0.18_215 , __a : str = "group" , ):
'''simple docstring'''
super().__init__()
# pass init params to Encoder
lowerCamelCase__: Tuple = Encoder(
in_channels=__a , out_channels=__a , down_block_types=__a , block_out_channels=__a , layers_per_block=__a , act_fn=__a , norm_num_groups=__a , double_z=__a , )
lowerCamelCase__: Optional[int] = vq_embed_dim if vq_embed_dim is not None else latent_channels
lowerCamelCase__: Optional[int] = nn.Convad(__a , __a , 1 )
lowerCamelCase__: List[str] = VectorQuantizer(__a , __a , beta=0.25 , remap=__a , sane_index_shape=__a )
lowerCamelCase__: str = nn.Convad(__a , __a , 1 )
# pass init params to Decoder
lowerCamelCase__: Dict = Decoder(
in_channels=__a , out_channels=__a , up_block_types=__a , block_out_channels=__a , layers_per_block=__a , act_fn=__a , norm_num_groups=__a , norm_type=__a , )
@apply_forward_hook
def lowerCamelCase_ ( self : List[Any] , __a : torch.FloatTensor , __a : bool = True ):
'''simple docstring'''
lowerCamelCase__: Union[str, Any] = self.encoder(__a )
lowerCamelCase__: Union[str, Any] = self.quant_conv(__a )
if not return_dict:
return (h,)
return VQEncoderOutput(latents=__a )
@apply_forward_hook
def lowerCamelCase_ ( self : Tuple , __a : torch.FloatTensor , __a : bool = False , __a : bool = True ):
'''simple docstring'''
if not force_not_quantize:
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[Any] = self.quantize(__a )
else:
lowerCamelCase__: Optional[Any] = h
lowerCamelCase__: List[str] = self.post_quant_conv(__a )
lowerCamelCase__: Optional[int] = self.decoder(__a , quant if self.config.norm_type == """spatial""" else None )
if not return_dict:
return (dec,)
return DecoderOutput(sample=__a )
def lowerCamelCase_ ( self : List[Any] , __a : torch.FloatTensor , __a : bool = True ):
'''simple docstring'''
lowerCamelCase__: Tuple = sample
lowerCamelCase__: List[str] = self.encode(__a ).latents
lowerCamelCase__: Any = self.decode(__a ).sample
if not return_dict:
return (dec,)
return DecoderOutput(sample=__a )
| 306 | 1 |
from abc import ABC, abstractmethod
from argparse import ArgumentParser
class lowerCamelCase_ ( lowerCamelCase ):
@staticmethod
@abstractmethod
def A ( __lowerCAmelCase ):
"""simple docstring"""
raise NotImplementedError()
@abstractmethod
def A ( self ):
"""simple docstring"""
raise NotImplementedError()
| 180 |
import inspect
import unittest
from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import RegNetForImageClassification, RegNetModel
from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class lowerCamelCase_ :
def __init__( self , __lowerCAmelCase , __lowerCAmelCase=3 , __lowerCAmelCase=3_2 , __lowerCAmelCase=3 , __lowerCAmelCase=1_0 , __lowerCAmelCase=[1_0, 2_0, 3_0, 4_0] , __lowerCAmelCase=[1, 1, 2, 1] , __lowerCAmelCase=True , __lowerCAmelCase=True , __lowerCAmelCase="relu" , __lowerCAmelCase=3 , __lowerCAmelCase=None , ):
"""simple docstring"""
__magic_name__ :Union[str, Any] = parent
__magic_name__ :str = batch_size
__magic_name__ :Union[str, Any] = image_size
__magic_name__ :Optional[Any] = num_channels
__magic_name__ :str = embeddings_size
__magic_name__ :List[Any] = hidden_sizes
__magic_name__ :List[str] = depths
__magic_name__ :str = is_training
__magic_name__ :List[Any] = use_labels
__magic_name__ :int = hidden_act
__magic_name__ :Dict = num_labels
__magic_name__ :Any = scope
__magic_name__ :Optional[int] = len(__lowerCAmelCase )
def A ( self ):
"""simple docstring"""
__magic_name__ :Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
__magic_name__ :int = None
if self.use_labels:
__magic_name__ :int = ids_tensor([self.batch_size] , self.num_labels )
__magic_name__ :List[str] = self.get_config()
return config, pixel_values, labels
def A ( self ):
"""simple docstring"""
return RegNetConfig(
num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , )
def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ):
"""simple docstring"""
__magic_name__ :Optional[int] = RegNetModel(config=__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
__magic_name__ :Dict = model(__lowerCAmelCase )
# expected last hidden states: B, C, H // 32, W // 32
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , )
def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ):
"""simple docstring"""
__magic_name__ :Union[str, Any] = self.num_labels
__magic_name__ :str = RegNetForImageClassification(__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
__magic_name__ :str = model(__lowerCAmelCase , labels=__lowerCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def A ( self ):
"""simple docstring"""
__magic_name__ :int = self.prepare_config_and_inputs()
__magic_name__ , __magic_name__ , __magic_name__ :str = config_and_inputs
__magic_name__ :Optional[int] = {'''pixel_values''': pixel_values}
return config, inputs_dict
@require_torch
class lowerCamelCase_ ( lowerCamelCase , lowerCamelCase , unittest.TestCase ):
a__ = (RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
a__ = (
{'''feature-extraction''': RegNetModel, '''image-classification''': RegNetForImageClassification}
if is_torch_available()
else {}
)
a__ = False
a__ = False
a__ = False
a__ = False
def A ( self ):
"""simple docstring"""
__magic_name__ :Tuple = RegNetModelTester(self )
__magic_name__ :Union[str, Any] = ConfigTester(self , config_class=__lowerCAmelCase , has_text_modality=__lowerCAmelCase )
def A ( self ):
"""simple docstring"""
self.create_and_test_config_common_properties()
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def A ( self ):
"""simple docstring"""
return
@unittest.skip(reason='''RegNet does not use inputs_embeds''' )
def A ( self ):
"""simple docstring"""
pass
@unittest.skip(reason='''RegNet does not support input and output embeddings''' )
def A ( self ):
"""simple docstring"""
pass
def A ( self ):
"""simple docstring"""
__magic_name__ , __magic_name__ :Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__magic_name__ :Dict = model_class(__lowerCAmelCase )
__magic_name__ :Any = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__magic_name__ :Optional[Any] = [*signature.parameters.keys()]
__magic_name__ :Any = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , __lowerCAmelCase )
def A ( self ):
"""simple docstring"""
__magic_name__ :str = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__lowerCAmelCase )
def A ( self ):
"""simple docstring"""
__magic_name__ , __magic_name__ :Any = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__magic_name__ :Tuple = model_class(config=__lowerCAmelCase )
for name, module in model.named_modules():
if isinstance(__lowerCAmelCase , (nn.BatchNormad, nn.GroupNorm) ):
self.assertTrue(
torch.all(module.weight == 1 ) , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , )
self.assertTrue(
torch.all(module.bias == 0 ) , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , )
def A ( self ):
"""simple docstring"""
def check_hidden_states_output(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ):
__magic_name__ :Any = model_class(__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
with torch.no_grad():
__magic_name__ :int = model(**self._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase ) )
__magic_name__ :Optional[int] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
__magic_name__ :List[str] = self.model_tester.num_stages
self.assertEqual(len(__lowerCAmelCase ) , expected_num_stages + 1 )
# RegNet's feature maps are of shape (batch_size, num_channels, height, width)
self.assertListEqual(
list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , )
__magic_name__ , __magic_name__ :str = self.model_tester.prepare_config_and_inputs_for_common()
__magic_name__ :List[Any] = ['''basic''', '''bottleneck''']
for model_class in self.all_model_classes:
for layer_type in layers_type:
__magic_name__ :Optional[Any] = layer_type
__magic_name__ :List[str] = True
check_hidden_states_output(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
__magic_name__ :List[str] = True
check_hidden_states_output(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
def A ( self ):
"""simple docstring"""
__magic_name__ :str = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase )
@slow
def A ( self ):
"""simple docstring"""
for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__magic_name__ :Optional[int] = RegNetModel.from_pretrained(__lowerCAmelCase )
self.assertIsNotNone(__lowerCAmelCase )
def __lowercase ( ):
"""simple docstring"""
__magic_name__ :List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_torch
@require_vision
class lowerCamelCase_ ( unittest.TestCase ):
@cached_property
def A ( self ):
"""simple docstring"""
return (
AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
if is_vision_available()
else None
)
@slow
def A ( self ):
"""simple docstring"""
__magic_name__ :Optional[int] = RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(__lowerCAmelCase )
__magic_name__ :List[str] = self.default_image_processor
__magic_name__ :Any = prepare_img()
__magic_name__ :Optional[Any] = image_processor(images=__lowerCAmelCase , return_tensors='''pt''' ).to(__lowerCAmelCase )
# forward pass
with torch.no_grad():
__magic_name__ :int = model(**__lowerCAmelCase )
# verify the logits
__magic_name__ :List[Any] = torch.Size((1, 1_0_0_0) )
self.assertEqual(outputs.logits.shape , __lowerCAmelCase )
__magic_name__ :Any = torch.tensor([-0.4180, -1.5051, -3.4836] ).to(__lowerCAmelCase )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCAmelCase , atol=1E-4 ) )
| 180 | 1 |
'''simple docstring'''
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
convert_to_rgb,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
OPENAI_CLIP_MEAN,
OPENAI_CLIP_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
snake_case_ = logging.get_logger(__name__)
if is_vision_available():
import PIL
class a__ ( _lowercase ):
__magic_name__ : Any = ["pixel_values"]
def __init__(self : Union[str, Any], __UpperCAmelCase : bool = True, __UpperCAmelCase : Dict[str, int] = None, __UpperCAmelCase : PILImageResampling = PILImageResampling.BICUBIC, __UpperCAmelCase : bool = True, __UpperCAmelCase : Dict[str, int] = None, __UpperCAmelCase : bool = True, __UpperCAmelCase : Union[int, float] = 1 / 255, __UpperCAmelCase : bool = True, __UpperCAmelCase : Optional[Union[float, List[float]]] = None, __UpperCAmelCase : Optional[Union[float, List[float]]] = None, __UpperCAmelCase : bool = True, **__UpperCAmelCase : Optional[int], ) -> None:
"""simple docstring"""
super().__init__(**__UpperCAmelCase )
SCREAMING_SNAKE_CASE : int = size if size is not None else {'''shortest_edge''': 224}
SCREAMING_SNAKE_CASE : Dict = get_size_dict(__UpperCAmelCase, default_to_square=__UpperCAmelCase )
SCREAMING_SNAKE_CASE : Any = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
SCREAMING_SNAKE_CASE : int = get_size_dict(__UpperCAmelCase, default_to_square=__UpperCAmelCase, param_name='''crop_size''' )
SCREAMING_SNAKE_CASE : Any = do_resize
SCREAMING_SNAKE_CASE : Any = size
SCREAMING_SNAKE_CASE : List[str] = resample
SCREAMING_SNAKE_CASE : Union[str, Any] = do_center_crop
SCREAMING_SNAKE_CASE : Optional[int] = crop_size
SCREAMING_SNAKE_CASE : int = do_rescale
SCREAMING_SNAKE_CASE : Union[str, Any] = rescale_factor
SCREAMING_SNAKE_CASE : Dict = do_normalize
SCREAMING_SNAKE_CASE : Dict = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
SCREAMING_SNAKE_CASE : Optional[int] = image_std if image_std is not None else OPENAI_CLIP_STD
SCREAMING_SNAKE_CASE : Optional[Any] = do_convert_rgb
def lowercase__ (self : List[str], __UpperCAmelCase : np.ndarray, __UpperCAmelCase : Dict[str, int], __UpperCAmelCase : PILImageResampling = PILImageResampling.BICUBIC, __UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None, **__UpperCAmelCase : Optional[int], ) -> np.ndarray:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Tuple = get_size_dict(__UpperCAmelCase, default_to_square=__UpperCAmelCase )
if "shortest_edge" not in size:
raise ValueError(F'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' )
SCREAMING_SNAKE_CASE : Optional[Any] = get_resize_output_image_size(__UpperCAmelCase, size=size['''shortest_edge'''], default_to_square=__UpperCAmelCase )
return resize(__UpperCAmelCase, size=__UpperCAmelCase, resample=__UpperCAmelCase, data_format=__UpperCAmelCase, **__UpperCAmelCase )
def lowercase__ (self : str, __UpperCAmelCase : np.ndarray, __UpperCAmelCase : Dict[str, int], __UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None, **__UpperCAmelCase : Any, ) -> np.ndarray:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Any = get_size_dict(__UpperCAmelCase )
if "height" not in size or "width" not in size:
raise ValueError(F'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' )
return center_crop(__UpperCAmelCase, size=(size['''height'''], size['''width''']), data_format=__UpperCAmelCase, **__UpperCAmelCase )
def lowercase__ (self : List[Any], __UpperCAmelCase : np.ndarray, __UpperCAmelCase : Union[int, float], __UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None, **__UpperCAmelCase : Tuple, ) -> str:
"""simple docstring"""
return rescale(__UpperCAmelCase, scale=__UpperCAmelCase, data_format=__UpperCAmelCase, **__UpperCAmelCase )
def lowercase__ (self : Any, __UpperCAmelCase : np.ndarray, __UpperCAmelCase : Union[float, List[float]], __UpperCAmelCase : Union[float, List[float]], __UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None, **__UpperCAmelCase : str, ) -> np.ndarray:
"""simple docstring"""
return normalize(__UpperCAmelCase, mean=__UpperCAmelCase, std=__UpperCAmelCase, data_format=__UpperCAmelCase, **__UpperCAmelCase )
def lowercase__ (self : List[str], __UpperCAmelCase : ImageInput, __UpperCAmelCase : bool = None, __UpperCAmelCase : Dict[str, int] = None, __UpperCAmelCase : PILImageResampling = None, __UpperCAmelCase : bool = None, __UpperCAmelCase : int = None, __UpperCAmelCase : bool = None, __UpperCAmelCase : float = None, __UpperCAmelCase : bool = None, __UpperCAmelCase : Optional[Union[float, List[float]]] = None, __UpperCAmelCase : Optional[Union[float, List[float]]] = None, __UpperCAmelCase : bool = None, __UpperCAmelCase : Optional[Union[str, TensorType]] = None, __UpperCAmelCase : Optional[ChannelDimension] = ChannelDimension.FIRST, **__UpperCAmelCase : Union[str, Any], ) -> PIL.Image.Image:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Any = do_resize if do_resize is not None else self.do_resize
SCREAMING_SNAKE_CASE : Dict = size if size is not None else self.size
SCREAMING_SNAKE_CASE : Optional[int] = get_size_dict(__UpperCAmelCase, param_name='''size''', default_to_square=__UpperCAmelCase )
SCREAMING_SNAKE_CASE : Optional[Any] = resample if resample is not None else self.resample
SCREAMING_SNAKE_CASE : List[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop
SCREAMING_SNAKE_CASE : List[Any] = crop_size if crop_size is not None else self.crop_size
SCREAMING_SNAKE_CASE : Tuple = get_size_dict(__UpperCAmelCase, param_name='''crop_size''', default_to_square=__UpperCAmelCase )
SCREAMING_SNAKE_CASE : Any = do_rescale if do_rescale is not None else self.do_rescale
SCREAMING_SNAKE_CASE : Union[str, Any] = rescale_factor if rescale_factor is not None else self.rescale_factor
SCREAMING_SNAKE_CASE : Tuple = do_normalize if do_normalize is not None else self.do_normalize
SCREAMING_SNAKE_CASE : Any = image_mean if image_mean is not None else self.image_mean
SCREAMING_SNAKE_CASE : List[str] = image_std if image_std is not None else self.image_std
SCREAMING_SNAKE_CASE : List[Any] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
SCREAMING_SNAKE_CASE : str = make_list_of_images(__UpperCAmelCase )
if not valid_images(__UpperCAmelCase ):
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:
raise ValueError('''Size must be specified if do_resize is True.''' )
if do_center_crop and crop_size is None:
raise ValueError('''Crop size must be specified if do_center_crop is True.''' )
if do_rescale and rescale_factor is None:
raise ValueError('''Rescale factor must be specified if do_rescale is True.''' )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError('''Image mean and std must be specified if do_normalize is True.''' )
# PIL RGBA images are converted to RGB
if do_convert_rgb:
SCREAMING_SNAKE_CASE : List[Any] = [convert_to_rgb(__UpperCAmelCase ) for image in images]
# All transformations expect numpy arrays.
SCREAMING_SNAKE_CASE : Dict = [to_numpy_array(__UpperCAmelCase ) for image in images]
if do_resize:
SCREAMING_SNAKE_CASE : Optional[Any] = [self.resize(image=__UpperCAmelCase, size=__UpperCAmelCase, resample=__UpperCAmelCase ) for image in images]
if do_center_crop:
SCREAMING_SNAKE_CASE : Optional[Any] = [self.center_crop(image=__UpperCAmelCase, size=__UpperCAmelCase ) for image in images]
if do_rescale:
SCREAMING_SNAKE_CASE : List[str] = [self.rescale(image=__UpperCAmelCase, scale=__UpperCAmelCase ) for image in images]
if do_normalize:
SCREAMING_SNAKE_CASE : Optional[Any] = [self.normalize(image=__UpperCAmelCase, mean=__UpperCAmelCase, std=__UpperCAmelCase ) for image in images]
SCREAMING_SNAKE_CASE : str = [to_channel_dimension_format(__UpperCAmelCase, __UpperCAmelCase ) for image in images]
SCREAMING_SNAKE_CASE : List[str] = {'''pixel_values''': images}
return BatchFeature(data=__UpperCAmelCase, tensor_type=__UpperCAmelCase )
| 507 |
'''simple docstring'''
snake_case_ = {}
def __lowercase (_SCREAMING_SNAKE_CASE :int , _SCREAMING_SNAKE_CASE :int , _SCREAMING_SNAKE_CASE :int ):
# 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
SCREAMING_SNAKE_CASE : Optional[int] = (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
SCREAMING_SNAKE_CASE : str = _calculate(days - 1 , _SCREAMING_SNAKE_CASE , late + 1 )
# 2) if we are absent, the "absent" counter increases by 1, and the
# "late" counter resets to 0
SCREAMING_SNAKE_CASE : Union[str, Any] = _calculate(days - 1 , absent + 1 , 0 )
# 3) if we are on time, this resets the "late" counter and keeps the
# absent counter
SCREAMING_SNAKE_CASE : int = _calculate(days - 1 , _SCREAMING_SNAKE_CASE , 0 )
SCREAMING_SNAKE_CASE : Tuple = state_late + state_absent + state_ontime
SCREAMING_SNAKE_CASE : List[Any] = prizestrings
return prizestrings
def __lowercase (_SCREAMING_SNAKE_CASE :int = 30 ):
return _calculate(_SCREAMING_SNAKE_CASE , absent=0 , late=0 )
if __name__ == "__main__":
print(solution())
| 507 | 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 timm import create_model
from timm.data import resolve_data_config
from timm.data.transforms_factory import create_transform
from transformers import BitConfig, BitForImageClassification, BitImageProcessor
from transformers.image_utils import PILImageResampling
from transformers.utils import logging
logging.set_verbosity_info()
__snake_case : Union[str, Any] = logging.get_logger(__name__)
def _lowercase ( lowerCamelCase__ : str ):
_a = "huggingface/label-files"
_a = "imagenet-1k-id2label.json"
_a = json.load(open(hf_hub_download(lowerCamelCase__, lowerCamelCase__, repo_type="dataset" ), "r" ) )
_a = {int(lowerCamelCase__ ): v for k, v in idalabel.items()}
_a = {v: k for k, v in idalabel.items()}
_a = "std_conv" if "bit" in model_name else False
# note that when using BiT as backbone for ViT-hybrid checkpoints,
# one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same",
# config.conv_layer = "std_conv_same"
_a = BitConfig(
conv_layer=lowerCamelCase__, num_labels=1_000, idalabel=lowerCamelCase__, labelaid=lowerCamelCase__, )
return config
def _lowercase ( lowerCamelCase__ : Tuple ):
if "stem.conv" in name:
_a = name.replace("stem.conv", "bit.embedder.convolution" )
if "blocks" in name:
_a = name.replace("blocks", "layers" )
if "head.fc" in name:
_a = name.replace("head.fc", "classifier.1" )
if name.startswith("norm" ):
_a = "bit." + name
if "bit" not in name and "classifier" not in name:
_a = "bit.encoder." + name
return name
def _lowercase ( ):
_a = "http://images.cocodataset.org/val2017/000000039769.jpg"
_a = Image.open(requests.get(lowerCamelCase__, stream=lowerCamelCase__ ).raw )
return im
@torch.no_grad()
def _lowercase ( lowerCamelCase__ : Optional[Any], lowerCamelCase__ : Tuple, lowerCamelCase__ : int=False ):
_a = get_config(lowerCamelCase__ )
# load original model from timm
_a = create_model(lowerCamelCase__, pretrained=lowerCamelCase__ )
timm_model.eval()
# load state_dict of original model
_a = timm_model.state_dict()
for key in state_dict.copy().keys():
_a = state_dict.pop(lowerCamelCase__ )
_a = val.squeeze() if "head" in key else val
# load HuggingFace model
_a = BitForImageClassification(lowerCamelCase__ )
model.eval()
model.load_state_dict(lowerCamelCase__ )
# create image processor
_a = create_transform(**resolve_data_config({}, model=lowerCamelCase__ ) )
_a = transform.transforms
_a = {
"bilinear": PILImageResampling.BILINEAR,
"bicubic": PILImageResampling.BICUBIC,
"nearest": PILImageResampling.NEAREST,
}
_a = BitImageProcessor(
do_resize=lowerCamelCase__, size={"shortest_edge": timm_transforms[0].size}, resample=pillow_resamplings[timm_transforms[0].interpolation.value], do_center_crop=lowerCamelCase__, crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]}, do_normalize=lowerCamelCase__, image_mean=timm_transforms[-1].mean.tolist(), image_std=timm_transforms[-1].std.tolist(), )
_a = prepare_img()
_a = transform(lowerCamelCase__ ).unsqueeze(0 )
_a = processor(lowerCamelCase__, return_tensors="pt" ).pixel_values
# verify pixel values
assert torch.allclose(lowerCamelCase__, lowerCamelCase__ )
# verify logits
with torch.no_grad():
_a = model(lowerCamelCase__ )
_a = outputs.logits
print("Logits:", logits[0, :3] )
print("Predicted class:", model.config.idalabel[logits.argmax(-1 ).item()] )
_a = timm_model(lowerCamelCase__ )
assert timm_logits.shape == outputs.logits.shape
assert torch.allclose(lowerCamelCase__, outputs.logits, atol=1e-3 )
print("Looks ok!" )
if pytorch_dump_folder_path is not None:
Path(lowerCamelCase__ ).mkdir(exist_ok=lowerCamelCase__ )
print(F'''Saving model {model_name} and processor to {pytorch_dump_folder_path}''' )
model.save_pretrained(lowerCamelCase__ )
processor.save_pretrained(lowerCamelCase__ )
if push_to_hub:
print(F'''Pushing model {model_name} and processor to the hub''' )
model.push_to_hub(F'''ybelkada/{model_name}''' )
processor.push_to_hub(F'''ybelkada/{model_name}''' )
if __name__ == "__main__":
__snake_case : Optional[Any] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--model_name",
default="resnetv2_50x1_bitm",
type=str,
help="Name of the BiT timm model you'd like to convert.",
)
parser.add_argument(
"--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
)
parser.add_argument(
"--push_to_hub",
action="store_true",
help="Whether to push the model to the hub.",
)
__snake_case : str = parser.parse_args()
convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 691 |
'''simple docstring'''
from ..utils import DummyObject, requires_backends
class A ( metaclass=a ):
__UpperCAmelCase : int = ["""torch""", """scipy"""]
def __init__( self , *snake_case_ , **snake_case_ ) -> Tuple:
requires_backends(self , ["torch", "scipy"] )
@classmethod
def __lowerCAmelCase ( cls , *snake_case_ , **snake_case_ ) -> Union[str, Any]:
requires_backends(cls , ["torch", "scipy"] )
@classmethod
def __lowerCAmelCase ( cls , *snake_case_ , **snake_case_ ) -> Any:
requires_backends(cls , ["torch", "scipy"] )
| 691 | 1 |
'''simple docstring'''
import argparse
import glob
import logging
import os
import time
from argparse import Namespace
import numpy as np
import torch
from lightning_base import BaseTransformer, add_generic_args, generic_train
from torch.utils.data import DataLoader, TensorDataset
from transformers import glue_compute_metrics as compute_metrics
from transformers import glue_convert_examples_to_features as convert_examples_to_features
from transformers import glue_output_modes, glue_tasks_num_labels
from transformers import glue_processors as processors
UpperCAmelCase : str = logging.getLogger(__name__)
class lowerCAmelCase__ ( a ):
"""simple docstring"""
lowerCAmelCase__ = "sequence-classification"
def __init__( self : str , __SCREAMING_SNAKE_CASE : str ) -> Optional[Any]:
"""simple docstring"""
if type(lowerCamelCase__ ) == dict:
__SCREAMING_SNAKE_CASE = Namespace(**lowerCamelCase__ )
__SCREAMING_SNAKE_CASE = glue_output_modes[hparams.task]
__SCREAMING_SNAKE_CASE = glue_tasks_num_labels[hparams.task]
super().__init__(lowerCamelCase__ , lowerCamelCase__ , self.mode )
def UpperCAmelCase__ ( self : Tuple , **__SCREAMING_SNAKE_CASE : List[Any] ) -> Dict:
"""simple docstring"""
return self.model(**lowerCamelCase__ )
def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> Optional[Any]:
"""simple docstring"""
__SCREAMING_SNAKE_CASE = {'input_ids': batch[0], 'attention_mask': batch[1], 'labels': batch[3]}
if self.config.model_type not in ["distilbert", "bart"]:
__SCREAMING_SNAKE_CASE = batch[2] if self.config.model_type in ['bert', 'xlnet', 'albert'] else None
__SCREAMING_SNAKE_CASE = self(**lowerCamelCase__ )
__SCREAMING_SNAKE_CASE = outputs[0]
__SCREAMING_SNAKE_CASE = self.trainer.lr_schedulers[0]['scheduler']
__SCREAMING_SNAKE_CASE = {'loss': loss, 'rate': lr_scheduler.get_last_lr()[-1]}
return {"loss": loss, "log": tensorboard_logs}
def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]:
"""simple docstring"""
__SCREAMING_SNAKE_CASE = self.hparams
__SCREAMING_SNAKE_CASE = processors[args.task]()
__SCREAMING_SNAKE_CASE = processor.get_labels()
for mode in ["train", "dev"]:
__SCREAMING_SNAKE_CASE = self._feature_file(lowerCamelCase__ )
if os.path.exists(lowerCamelCase__ ) and not args.overwrite_cache:
logger.info("""Loading features from cached file %s""" , lowerCamelCase__ )
else:
logger.info("""Creating features from dataset file at %s""" , args.data_dir )
__SCREAMING_SNAKE_CASE = (
processor.get_dev_examples(args.data_dir )
if mode == 'dev'
else processor.get_train_examples(args.data_dir )
)
__SCREAMING_SNAKE_CASE = convert_examples_to_features(
lowerCamelCase__ , self.tokenizer , max_length=args.max_seq_length , label_list=self.labels , output_mode=args.glue_output_mode , )
logger.info("""Saving features into cached file %s""" , lowerCamelCase__ )
torch.save(lowerCamelCase__ , lowerCamelCase__ )
def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : bool = False ) -> Optional[Any]:
"""simple docstring"""
__SCREAMING_SNAKE_CASE = 'dev' if mode == 'test' else mode
__SCREAMING_SNAKE_CASE = self._feature_file(lowerCamelCase__ )
logger.info("""Loading features from cached file %s""" , lowerCamelCase__ )
__SCREAMING_SNAKE_CASE = torch.load(lowerCamelCase__ )
__SCREAMING_SNAKE_CASE = torch.tensor([f.input_ids for f in features] , dtype=torch.long )
__SCREAMING_SNAKE_CASE = torch.tensor([f.attention_mask for f in features] , dtype=torch.long )
__SCREAMING_SNAKE_CASE = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long )
if self.hparams.glue_output_mode == "classification":
__SCREAMING_SNAKE_CASE = torch.tensor([f.label for f in features] , dtype=torch.long )
elif self.hparams.glue_output_mode == "regression":
__SCREAMING_SNAKE_CASE = torch.tensor([f.label for f in features] , dtype=torch.float )
return DataLoader(
TensorDataset(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) , batch_size=lowerCamelCase__ , shuffle=lowerCamelCase__ , )
def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[str] ) -> Optional[Any]:
"""simple docstring"""
__SCREAMING_SNAKE_CASE = {'input_ids': batch[0], 'attention_mask': batch[1], 'labels': batch[3]}
if self.config.model_type not in ["distilbert", "bart"]:
__SCREAMING_SNAKE_CASE = batch[2] if self.config.model_type in ['bert', 'xlnet', 'albert'] else None
__SCREAMING_SNAKE_CASE = self(**lowerCamelCase__ )
__SCREAMING_SNAKE_CASE = outputs[:2]
__SCREAMING_SNAKE_CASE = logits.detach().cpu().numpy()
__SCREAMING_SNAKE_CASE = inputs['labels'].detach().cpu().numpy()
return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids}
def UpperCAmelCase__ ( self : int , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> str:
"""simple docstring"""
__SCREAMING_SNAKE_CASE = torch.stack([x["""val_loss"""] for x in outputs] ).mean().detach().cpu().item()
__SCREAMING_SNAKE_CASE = np.concatenate([x["""pred"""] for x in outputs] , axis=0 )
if self.hparams.glue_output_mode == "classification":
__SCREAMING_SNAKE_CASE = np.argmax(lowerCamelCase__ , axis=1 )
elif self.hparams.glue_output_mode == "regression":
__SCREAMING_SNAKE_CASE = np.squeeze(lowerCamelCase__ )
__SCREAMING_SNAKE_CASE = np.concatenate([x["""target"""] for x in outputs] , axis=0 )
__SCREAMING_SNAKE_CASE = [[] for _ in range(out_label_ids.shape[0] )]
__SCREAMING_SNAKE_CASE = [[] for _ in range(out_label_ids.shape[0] )]
__SCREAMING_SNAKE_CASE = {**{'val_loss': val_loss_mean}, **compute_metrics(self.hparams.task , lowerCamelCase__ , lowerCamelCase__ )}
__SCREAMING_SNAKE_CASE = dict(results.items() )
__SCREAMING_SNAKE_CASE = results
return ret, preds_list, out_label_list
def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : list ) -> str:
"""simple docstring"""
__SCREAMING_SNAKE_CASE = self._eval_end(lowerCamelCase__ )
__SCREAMING_SNAKE_CASE = ret['log']
return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs}
def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Any ) -> Optional[int]:
"""simple docstring"""
__SCREAMING_SNAKE_CASE = self._eval_end(lowerCamelCase__ )
__SCREAMING_SNAKE_CASE = ret['log']
# `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss`
return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs}
@staticmethod
def UpperCAmelCase__ ( __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : List[str] ) -> int:
"""simple docstring"""
BaseTransformer.add_model_specific_args(lowerCamelCase__ , lowerCamelCase__ )
parser.add_argument(
"""--max_seq_length""" , default=128 , type=lowerCamelCase__ , help=(
"""The maximum total input sequence length after tokenization. Sequences longer """
"""than this will be truncated, sequences shorter will be padded."""
) , )
parser.add_argument(
"""--task""" , default="""""" , type=lowerCamelCase__ , required=lowerCamelCase__ , help="""The GLUE task to run""" , )
parser.add_argument(
"""--gpus""" , default=0 , type=lowerCamelCase__ , help="""The number of GPUs allocated for this, it is by default 0 meaning none""" , )
parser.add_argument(
"""--overwrite_cache""" , action="""store_true""" , help="""Overwrite the cached training and evaluation sets""" )
return parser
def a__ ( ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE = argparse.ArgumentParser()
add_generic_args(UpperCAmelCase_ , os.getcwd() )
__SCREAMING_SNAKE_CASE = GLUETransformer.add_model_specific_args(UpperCAmelCase_ , os.getcwd() )
__SCREAMING_SNAKE_CASE = parser.parse_args()
# If output_dir not provided, a folder will be generated in pwd
if args.output_dir is None:
__SCREAMING_SNAKE_CASE = os.path.join(
"""./results""" , F'{args.task}_{time.strftime("%Y%m%d_%H%M%S" )}' , )
os.makedirs(args.output_dir )
__SCREAMING_SNAKE_CASE = GLUETransformer(UpperCAmelCase_ )
__SCREAMING_SNAKE_CASE = generic_train(UpperCAmelCase_ , UpperCAmelCase_ )
# Optionally, predict on dev set and write to output_dir
if args.do_predict:
__SCREAMING_SNAKE_CASE = sorted(glob.glob(os.path.join(args.output_dir , """checkpoint-epoch=*.ckpt""" ) , recursive=UpperCAmelCase_ ) )
__SCREAMING_SNAKE_CASE = model.load_from_checkpoint(checkpoints[-1] )
return trainer.test(UpperCAmelCase_ )
if __name__ == "__main__":
main()
| 627 |
'''simple docstring'''
import collections
import inspect
import unittest
from typing import Dict, List, Tuple
from transformers import MaskFormerSwinConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device
from transformers.utils import is_torch_available
from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import MaskFormerSwinBackbone
from transformers.models.maskformer import MaskFormerSwinModel
class lowercase__ :
def __init__( self : Tuple ,lowerCamelCase__ : str ,lowerCamelCase__ : str=13 ,lowerCamelCase__ : List[Any]=32 ,lowerCamelCase__ : Optional[int]=2 ,lowerCamelCase__ : str=3 ,lowerCamelCase__ : Optional[int]=16 ,lowerCamelCase__ : Union[str, Any]=[1, 2, 1] ,lowerCamelCase__ : Optional[int]=[2, 2, 4] ,lowerCamelCase__ : int=2 ,lowerCamelCase__ : Any=2.0 ,lowerCamelCase__ : Dict=True ,lowerCamelCase__ : List[Any]=0.0 ,lowerCamelCase__ : List[str]=0.0 ,lowerCamelCase__ : Union[str, Any]=0.1 ,lowerCamelCase__ : List[Any]="gelu" ,lowerCamelCase__ : int=False ,lowerCamelCase__ : Any=True ,lowerCamelCase__ : List[Any]=0.0_2 ,lowerCamelCase__ : Dict=1E-5 ,lowerCamelCase__ : Optional[int]=True ,lowerCamelCase__ : int=None ,lowerCamelCase__ : int=True ,lowerCamelCase__ : List[Any]=10 ,lowerCamelCase__ : int=8 ,lowerCamelCase__ : Any=["stage1", "stage2", "stage3"] ,lowerCamelCase__ : List[str]=[1, 2, 3] ,):
'''simple docstring'''
_UpperCamelCase : str = parent
_UpperCamelCase : str = batch_size
_UpperCamelCase : Union[str, Any] = image_size
_UpperCamelCase : str = patch_size
_UpperCamelCase : Dict = num_channels
_UpperCamelCase : Union[str, Any] = embed_dim
_UpperCamelCase : Union[str, Any] = depths
_UpperCamelCase : Optional[int] = num_heads
_UpperCamelCase : Union[str, Any] = window_size
_UpperCamelCase : int = mlp_ratio
_UpperCamelCase : Optional[int] = qkv_bias
_UpperCamelCase : List[Any] = hidden_dropout_prob
_UpperCamelCase : Optional[int] = attention_probs_dropout_prob
_UpperCamelCase : Union[str, Any] = drop_path_rate
_UpperCamelCase : Union[str, Any] = hidden_act
_UpperCamelCase : str = use_absolute_embeddings
_UpperCamelCase : Any = patch_norm
_UpperCamelCase : Dict = layer_norm_eps
_UpperCamelCase : Optional[Any] = initializer_range
_UpperCamelCase : str = is_training
_UpperCamelCase : int = scope
_UpperCamelCase : Dict = use_labels
_UpperCamelCase : str = type_sequence_label_size
_UpperCamelCase : Optional[int] = encoder_stride
_UpperCamelCase : str = out_features
_UpperCamelCase : Optional[Any] = out_indices
def UpperCamelCase_ ( self : Any ):
'''simple docstring'''
_UpperCamelCase : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
_UpperCamelCase : Optional[Any] = None
if self.use_labels:
_UpperCamelCase : str = ids_tensor([self.batch_size] ,self.type_sequence_label_size )
_UpperCamelCase : Dict = self.get_config()
return config, pixel_values, labels
def UpperCamelCase_ ( self : List[str] ):
'''simple docstring'''
return MaskFormerSwinConfig(
image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,embed_dim=self.embed_dim ,depths=self.depths ,num_heads=self.num_heads ,window_size=self.window_size ,mlp_ratio=self.mlp_ratio ,qkv_bias=self.qkv_bias ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,drop_path_rate=self.drop_path_rate ,hidden_act=self.hidden_act ,use_absolute_embeddings=self.use_absolute_embeddings ,path_norm=self.patch_norm ,layer_norm_eps=self.layer_norm_eps ,initializer_range=self.initializer_range ,encoder_stride=self.encoder_stride ,out_features=self.out_features ,out_indices=self.out_indices ,)
def UpperCamelCase_ ( self : Optional[int] ,lowerCamelCase__ : Any ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : Any ):
'''simple docstring'''
_UpperCamelCase : Tuple = MaskFormerSwinModel(config=lowerCamelCase__ )
model.to(lowerCamelCase__ )
model.eval()
_UpperCamelCase : Dict = model(lowerCamelCase__ )
_UpperCamelCase : Tuple = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1))
_UpperCamelCase : Optional[Any] = int(config.embed_dim * 2 ** (len(config.depths ) - 1) )
self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, expected_seq_len, expected_dim) )
def UpperCamelCase_ ( self : int ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : Union[str, Any] ):
'''simple docstring'''
_UpperCamelCase : Dict = MaskFormerSwinBackbone(config=lowerCamelCase__ )
model.to(lowerCamelCase__ )
model.eval()
_UpperCamelCase : List[Any] = model(lowerCamelCase__ )
# verify feature maps
self.parent.assertEqual(len(result.feature_maps ) ,len(config.out_features ) )
self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[13, 16, 16, 16] )
# verify channels
self.parent.assertEqual(len(model.channels ) ,len(config.out_features ) )
self.parent.assertListEqual(model.channels ,[16, 32, 64] )
# verify ValueError
with self.parent.assertRaises(lowerCamelCase__ ):
_UpperCamelCase : Union[str, Any] = ['stem']
_UpperCamelCase : int = MaskFormerSwinBackbone(config=lowerCamelCase__ )
def UpperCamelCase_ ( self : Dict ):
'''simple docstring'''
_UpperCamelCase : Dict = self.prepare_config_and_inputs()
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase : str = config_and_inputs
_UpperCamelCase : int = {'pixel_values': pixel_values}
return config, inputs_dict
@require_torch
class lowercase__ ( lowercase , lowercase , unittest.TestCase ):
lowercase__ = (
(
MaskFormerSwinModel,
MaskFormerSwinBackbone,
)
if is_torch_available()
else ()
)
lowercase__ = {"""feature-extraction""": MaskFormerSwinModel} if is_torch_available() else {}
lowercase__ = False
lowercase__ = False
lowercase__ = False
lowercase__ = False
lowercase__ = False
def UpperCamelCase_ ( self : Tuple ):
'''simple docstring'''
_UpperCamelCase : Dict = MaskFormerSwinModelTester(self )
_UpperCamelCase : Union[str, Any] = ConfigTester(self ,config_class=lowerCamelCase__ ,embed_dim=37 )
@require_torch_multi_gpu
@unittest.skip(
reason=(
'`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn\'t work well with'
' `nn.DataParallel`'
) )
def UpperCamelCase_ ( self : Optional[Any] ):
'''simple docstring'''
pass
def UpperCamelCase_ ( self : Optional[int] ):
'''simple docstring'''
self.create_and_test_config_common_properties()
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def UpperCamelCase_ ( self : List[Any] ):
'''simple docstring'''
return
def UpperCamelCase_ ( self : Optional[int] ):
'''simple docstring'''
_UpperCamelCase : str = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCamelCase__ )
def UpperCamelCase_ ( self : Optional[Any] ):
'''simple docstring'''
_UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_backbone(*lowerCamelCase__ )
@unittest.skip('Swin does not use inputs_embeds' )
def UpperCamelCase_ ( self : Dict ):
'''simple docstring'''
pass
@unittest.skip('Swin does not support feedforward chunking' )
def UpperCamelCase_ ( self : Tuple ):
'''simple docstring'''
pass
def UpperCamelCase_ ( self : List[str] ):
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase : Any = model_class(lowerCamelCase__ )
self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) )
_UpperCamelCase : str = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(lowerCamelCase__ ,nn.Linear ) )
def UpperCamelCase_ ( self : int ):
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase : List[str] = model_class(lowerCamelCase__ )
_UpperCamelCase : Optional[Any] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_UpperCamelCase : Union[str, Any] = [*signature.parameters.keys()]
_UpperCamelCase : Union[str, Any] = ['pixel_values']
self.assertListEqual(arg_names[:1] ,lowerCamelCase__ )
@unittest.skip(reason='MaskFormerSwin is only used as backbone and doesn\'t support output_attentions' )
def UpperCamelCase_ ( self : Optional[int] ):
'''simple docstring'''
pass
@unittest.skip(reason='MaskFormerSwin is only used as an internal backbone' )
def UpperCamelCase_ ( self : Optional[int] ):
'''simple docstring'''
pass
def UpperCamelCase_ ( self : Optional[Any] ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : Tuple ):
'''simple docstring'''
_UpperCamelCase : Tuple = model_class(lowerCamelCase__ )
model.to(lowerCamelCase__ )
model.eval()
with torch.no_grad():
_UpperCamelCase : List[Any] = model(**self._prepare_for_class(lowerCamelCase__ ,lowerCamelCase__ ) )
_UpperCamelCase : List[Any] = outputs.hidden_states
_UpperCamelCase : Any = getattr(
self.model_tester ,'expected_num_hidden_layers' ,len(self.model_tester.depths ) + 1 )
self.assertEqual(len(lowerCamelCase__ ) ,lowerCamelCase__ )
# Swin has a different seq_length
_UpperCamelCase : Tuple = (
config.patch_size
if isinstance(config.patch_size ,collections.abc.Iterable )
else (config.patch_size, config.patch_size)
)
_UpperCamelCase : Optional[int] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
self.assertListEqual(
list(hidden_states[0].shape[-2:] ) ,[num_patches, self.model_tester.embed_dim] ,)
def UpperCamelCase_ ( self : Optional[Any] ):
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
_UpperCamelCase : str = (
self.model_tester.image_size
if isinstance(self.model_tester.image_size ,collections.abc.Iterable )
else (self.model_tester.image_size, self.model_tester.image_size)
)
for model_class in self.all_model_classes:
_UpperCamelCase : Union[str, Any] = True
self.check_hidden_states_output(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
_UpperCamelCase : Dict = True
self.check_hidden_states_output(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ )
def UpperCamelCase_ ( self : Dict ):
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common()
_UpperCamelCase : List[Any] = 3
_UpperCamelCase : str = (
self.model_tester.image_size
if isinstance(self.model_tester.image_size ,collections.abc.Iterable )
else (self.model_tester.image_size, self.model_tester.image_size)
)
_UpperCamelCase : Tuple = (
config.patch_size
if isinstance(config.patch_size ,collections.abc.Iterable )
else (config.patch_size, config.patch_size)
)
_UpperCamelCase : List[Any] = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
_UpperCamelCase : Optional[Any] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])
for model_class in self.all_model_classes:
_UpperCamelCase : Dict = True
self.check_hidden_states_output(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,(padded_height, padded_width) )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
_UpperCamelCase : Tuple = True
self.check_hidden_states_output(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,(padded_height, padded_width) )
@unittest.skip(reason='MaskFormerSwin doesn\'t have pretrained checkpoints' )
def UpperCamelCase_ ( self : Tuple ):
'''simple docstring'''
pass
@unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin' )
def UpperCamelCase_ ( self : int ):
'''simple docstring'''
pass
@unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin' )
def UpperCamelCase_ ( self : Optional[int] ):
'''simple docstring'''
pass
def UpperCamelCase_ ( self : Any ):
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase : str = self.model_tester.prepare_config_and_inputs_for_common()
def set_nan_tensor_to_zero(lowerCamelCase__ : str ):
_UpperCamelCase : List[str] = 0
return t
def check_equivalence(lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : Optional[int]={} ):
with torch.no_grad():
_UpperCamelCase : List[str] = model(**lowerCamelCase__ ,return_dict=lowerCamelCase__ ,**lowerCamelCase__ )
_UpperCamelCase : Optional[Any] = model(**lowerCamelCase__ ,return_dict=lowerCamelCase__ ,**lowerCamelCase__ ).to_tuple()
def recursive_check(lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : int ):
if isinstance(lowerCamelCase__ ,(List, Tuple) ):
for tuple_iterable_value, dict_iterable_value in zip(lowerCamelCase__ ,lowerCamelCase__ ):
recursive_check(lowerCamelCase__ ,lowerCamelCase__ )
elif isinstance(lowerCamelCase__ ,lowerCamelCase__ ):
for tuple_iterable_value, dict_iterable_value in zip(
tuple_object.values() ,dict_object.values() ):
recursive_check(lowerCamelCase__ ,lowerCamelCase__ )
elif tuple_object is None:
return
else:
self.assertTrue(
torch.allclose(
set_nan_tensor_to_zero(lowerCamelCase__ ) ,set_nan_tensor_to_zero(lowerCamelCase__ ) ,atol=1E-5 ) ,msg=(
'Tuple and dict output are not equal. Difference:'
F' {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:'
F' {torch.isnan(lowerCamelCase__ ).any()} and `inf`: {torch.isinf(lowerCamelCase__ )}. Dict has'
F' `nan`: {torch.isnan(lowerCamelCase__ ).any()} and `inf`: {torch.isinf(lowerCamelCase__ )}.'
) ,)
recursive_check(lowerCamelCase__ ,lowerCamelCase__ )
for model_class in self.all_model_classes:
_UpperCamelCase : List[str] = model_class(lowerCamelCase__ )
model.to(lowerCamelCase__ )
model.eval()
_UpperCamelCase : Optional[Any] = self._prepare_for_class(lowerCamelCase__ ,lowerCamelCase__ )
_UpperCamelCase : Dict = self._prepare_for_class(lowerCamelCase__ ,lowerCamelCase__ )
check_equivalence(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ )
_UpperCamelCase : int = self._prepare_for_class(lowerCamelCase__ ,lowerCamelCase__ ,return_labels=lowerCamelCase__ )
_UpperCamelCase : Optional[Any] = self._prepare_for_class(lowerCamelCase__ ,lowerCamelCase__ ,return_labels=lowerCamelCase__ )
check_equivalence(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ )
_UpperCamelCase : Optional[Any] = self._prepare_for_class(lowerCamelCase__ ,lowerCamelCase__ )
_UpperCamelCase : Any = self._prepare_for_class(lowerCamelCase__ ,lowerCamelCase__ )
check_equivalence(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,{'output_hidden_states': True} )
_UpperCamelCase : Union[str, Any] = self._prepare_for_class(lowerCamelCase__ ,lowerCamelCase__ ,return_labels=lowerCamelCase__ )
_UpperCamelCase : str = self._prepare_for_class(lowerCamelCase__ ,lowerCamelCase__ ,return_labels=lowerCamelCase__ )
check_equivalence(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,{'output_hidden_states': True} )
@require_torch
class lowercase__ ( unittest.TestCase , lowercase ):
lowercase__ = (MaskFormerSwinBackbone,) if is_torch_available() else ()
lowercase__ = MaskFormerSwinConfig
def UpperCamelCase_ ( self : Dict ):
'''simple docstring'''
_UpperCamelCase : Union[str, Any] = MaskFormerSwinModelTester(self )
def UpperCamelCase_ ( self : List[Any] ):
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common()
_UpperCamelCase : str = inputs_dict['pixel_values'].shape[0]
for backbone_class in self.all_model_classes:
_UpperCamelCase : List[Any] = backbone_class(lowerCamelCase__ )
backbone.to(lowerCamelCase__ )
backbone.eval()
_UpperCamelCase : Optional[Any] = backbone(**lowerCamelCase__ )
# Test default outputs and verify feature maps
self.assertIsInstance(outputs.feature_maps ,lowerCamelCase__ )
self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) )
for feature_map, n_channels in zip(outputs.feature_maps ,backbone.channels ):
self.assertTrue(feature_map.shape[:2] ,(batch_size, n_channels) )
self.assertIsNone(outputs.hidden_states )
self.assertIsNone(outputs.attentions )
# Test output_hidden_states=True
_UpperCamelCase : List[str] = backbone(**lowerCamelCase__ ,output_hidden_states=lowerCamelCase__ )
self.assertIsNotNone(outputs.hidden_states )
self.assertTrue(len(outputs.hidden_states ) ,len(backbone.stage_names ) )
# We skip the stem layer
for hidden_states, n_channels in zip(outputs.hidden_states[1:] ,backbone.channels ):
for hidden_state in hidden_states:
# Hidden states are in the format (batch_size, (height * width), n_channels)
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase : Optional[Any] = hidden_state.shape
self.assertTrue((h_batch_size, h_n_channels) ,(batch_size, n_channels) )
# Test output_attentions=True
if self.has_attentions:
_UpperCamelCase : int = backbone(**lowerCamelCase__ ,output_attentions=lowerCamelCase__ )
self.assertIsNotNone(outputs.attentions )
| 195 | 0 |
from typing import List, Optional, Union
import numpy as np
from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ....feature_extraction_sequence_utils import SequenceFeatureExtractor
from ....feature_extraction_utils import BatchFeature
from ....file_utils import PaddingStrategy, TensorType
from ....utils import logging
lowerCamelCase__ : List[Any] = logging.get_logger(__name__)
class _snake_case ( UpperCAmelCase_ ):
__lowerCAmelCase : Dict = ['input_features', 'attention_mask']
def __init__( self , SCREAMING_SNAKE_CASE_=80 , SCREAMING_SNAKE_CASE_=1_60_00 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=25 , SCREAMING_SNAKE_CASE_="hamming_window" , SCREAMING_SNAKE_CASE_=3_2_7_6_8.0 , SCREAMING_SNAKE_CASE_=0.9_7 , SCREAMING_SNAKE_CASE_=1.0 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ , ):
'''simple docstring'''
super().__init__(feature_size=SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , padding_value=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_)
lowercase__ : str = feature_size
lowercase__ : Dict = sampling_rate
lowercase__ : List[Any] = padding_value
lowercase__ : Dict = hop_length
lowercase__ : List[Any] = win_length
lowercase__ : Any = frame_signal_scale
lowercase__ : Dict = preemphasis_coeff
lowercase__ : str = mel_floor
lowercase__ : Union[str, Any] = normalize_means
lowercase__ : Optional[int] = normalize_vars
lowercase__ : Optional[int] = win_function
lowercase__ : Optional[Any] = return_attention_mask
lowercase__ : List[Any] = win_length * sampling_rate // 10_00
lowercase__ : int = hop_length * sampling_rate // 10_00
lowercase__ : Tuple = optimal_fft_length(self.sample_size)
lowercase__ : Any = (self.n_fft // 2) + 1
def lowercase__ ( self , SCREAMING_SNAKE_CASE_):
'''simple docstring'''
if self.win_function == "hamming_window":
lowercase__ : int = window_function(window_length=self.sample_size , name=self.win_function , periodic=SCREAMING_SNAKE_CASE_)
else:
lowercase__ : Dict = window_function(window_length=self.sample_size , name=self.win_function)
lowercase__ : List[str] = mel_filter_bank(
num_frequency_bins=self.n_freqs , num_mel_filters=self.feature_size , min_frequency=0.0 , max_frequency=self.sampling_rate / 2.0 , sampling_rate=self.sampling_rate , )
lowercase__ : Optional[int] = spectrogram(
one_waveform * self.frame_signal_scale , window=SCREAMING_SNAKE_CASE_ , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , center=SCREAMING_SNAKE_CASE_ , preemphasis=self.preemphasis_coeff , mel_filters=SCREAMING_SNAKE_CASE_ , mel_floor=self.mel_floor , log_mel="""log""" , )
return msfc_features.T
def lowercase__ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_):
'''simple docstring'''
if self.normalize_means:
lowercase__ : List[Any] = x[:input_length].mean(axis=0)
lowercase__ : List[str] = np.subtract(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_)
if self.normalize_vars:
lowercase__ : str = x[:input_length].std(axis=0)
lowercase__ : List[str] = np.divide(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_)
if input_length < x.shape[0]:
lowercase__ : Optional[int] = padding_value
# make sure array is in float32
lowercase__ : List[str] = x.astype(np.floataa)
return x
def lowercase__ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None):
'''simple docstring'''
lowercase__ : Optional[Any] = attention_mask.sum(-1) if attention_mask is not None else [x.shape[0] for x in input_features]
return [self._normalize_one(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.padding_value) for x, n in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_)]
def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ):
'''simple docstring'''
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
f'The model corresponding to this feature extractor: {self} was trained using a sampling rate of'
f' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with'
f' {self.sampling_rate} and not {sampling_rate}.')
else:
logger.warning(
"""It is strongly recommended to pass the ``sampling_rate`` argument to this function. """
"""Failing to do so can result in silent errors that might be hard to debug.""")
lowercase__ : Optional[int] = isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray) and len(raw_speech.shape) > 1
if is_batched_numpy and len(raw_speech.shape) > 2:
raise ValueError(f'Only mono-channel audio is supported for input to {self}')
lowercase__ : Any = is_batched_numpy or (
isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple)) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list)))
)
if is_batched:
lowercase__ : str = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa) for speech in raw_speech]
elif not is_batched and not isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray):
lowercase__ : Any = np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa)
elif isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray) and raw_speech.dtype is np.dtype(np.floataa):
lowercase__ : str = raw_speech.astype(np.floataa)
# always return batch
if not is_batched:
lowercase__ : Any = [raw_speech]
# extract fbank features
lowercase__ : Union[str, Any] = [self._extract_mfsc_features(SCREAMING_SNAKE_CASE_) for one_waveform in raw_speech]
# convert into correct format for padding
lowercase__ : Optional[Any] = BatchFeature({"""input_features""": features})
lowercase__ : Any = self.pad(
SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , )
# make sure list is in array format
lowercase__ : Optional[Any] = padded_inputs.get("""input_features""")
if isinstance(input_features[0] , SCREAMING_SNAKE_CASE_):
lowercase__ : List[str] = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa) for feature in input_features]
lowercase__ : Union[str, Any] = padded_inputs.get("""attention_mask""")
if attention_mask is not None:
lowercase__ : Optional[Any] = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.intaa) for array in attention_mask]
if self.normalize_means or self.normalize_vars:
lowercase__ : Dict = (
np.array(SCREAMING_SNAKE_CASE_ , dtype=np.intaa)
if self._get_padding_strategies(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_) is not PaddingStrategy.DO_NOT_PAD
and padding
else None
)
lowercase__ : Tuple = self.normalize(
padded_inputs["""input_features"""] , attention_mask=SCREAMING_SNAKE_CASE_)
if return_tensors is not None:
lowercase__ : Any = padded_inputs.convert_to_tensors(SCREAMING_SNAKE_CASE_)
return padded_inputs
| 495 |
from typing import Optional, Tuple, Union
import tensorflow as tf
from ...activations_tf import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_tf_outputs import (
TFBaseModelOutputWithNoAttention,
TFBaseModelOutputWithPoolingAndNoAttention,
TFSequenceClassifierOutput,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import logging
from .configuration_regnet import RegNetConfig
lowerCamelCase__ : Union[str, Any] = logging.get_logger(__name__)
# General docstring
lowerCamelCase__ : List[str] = """RegNetConfig"""
# Base docstring
lowerCamelCase__ : str = """facebook/regnet-y-040"""
lowerCamelCase__ : str = [1, 1_0_8_8, 7, 7]
# Image classification docstring
lowerCamelCase__ : Union[str, Any] = """facebook/regnet-y-040"""
lowerCamelCase__ : str = """tabby, tabby cat"""
lowerCamelCase__ : Optional[Any] = [
"""facebook/regnet-y-040""",
# See all regnet models at https://huggingface.co/models?filter=regnet
]
class _snake_case ( tf.keras.layers.Layer ):
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 3 , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = "relu" , **SCREAMING_SNAKE_CASE_ , ):
'''simple docstring'''
super().__init__(**SCREAMING_SNAKE_CASE_)
# The padding and conv has been verified in
# https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb
lowercase__ : str = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2)
lowercase__ : Optional[int] = tf.keras.layers.ConvaD(
filters=SCREAMING_SNAKE_CASE_ , kernel_size=SCREAMING_SNAKE_CASE_ , strides=SCREAMING_SNAKE_CASE_ , padding="""VALID""" , groups=SCREAMING_SNAKE_CASE_ , use_bias=SCREAMING_SNAKE_CASE_ , name="""convolution""" , )
lowercase__ : str = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="""normalization""")
lowercase__ : Any = ACTaFN[activation] if activation is not None else tf.identity
def lowercase__ ( self , SCREAMING_SNAKE_CASE_):
'''simple docstring'''
lowercase__ : Tuple = self.convolution(self.padding(SCREAMING_SNAKE_CASE_))
lowercase__ : List[Any] = self.normalization(SCREAMING_SNAKE_CASE_)
lowercase__ : str = self.activation(SCREAMING_SNAKE_CASE_)
return hidden_state
class _snake_case ( tf.keras.layers.Layer ):
def __init__( self , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_):
'''simple docstring'''
super().__init__(**SCREAMING_SNAKE_CASE_)
lowercase__ : List[str] = config.num_channels
lowercase__ : int = TFRegNetConvLayer(
out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name="""embedder""" , )
def lowercase__ ( self , SCREAMING_SNAKE_CASE_):
'''simple docstring'''
lowercase__ : List[str] = shape_list(SCREAMING_SNAKE_CASE_)[1]
if tf.executing_eagerly() and num_channels != self.num_channels:
raise ValueError(
"""Make sure that the channel dimension of the pixel values match with the one set in the configuration.""")
# When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format.
# So change the input format from `NCHW` to `NHWC`.
# shape = (batch_size, in_height, in_width, in_channels=num_channels)
lowercase__ : Optional[int] = tf.transpose(SCREAMING_SNAKE_CASE_ , perm=(0, 2, 3, 1))
lowercase__ : Optional[int] = self.embedder(SCREAMING_SNAKE_CASE_)
return hidden_state
class _snake_case ( tf.keras.layers.Layer ):
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 2 , **SCREAMING_SNAKE_CASE_):
'''simple docstring'''
super().__init__(**SCREAMING_SNAKE_CASE_)
lowercase__ : Any = tf.keras.layers.ConvaD(
filters=SCREAMING_SNAKE_CASE_ , kernel_size=1 , strides=SCREAMING_SNAKE_CASE_ , use_bias=SCREAMING_SNAKE_CASE_ , name="""convolution""")
lowercase__ : str = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="""normalization""")
def lowercase__ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False):
'''simple docstring'''
return self.normalization(self.convolution(SCREAMING_SNAKE_CASE_) , training=SCREAMING_SNAKE_CASE_)
class _snake_case ( tf.keras.layers.Layer ):
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_):
'''simple docstring'''
super().__init__(**SCREAMING_SNAKE_CASE_)
lowercase__ : str = tf.keras.layers.GlobalAveragePoolingaD(keepdims=SCREAMING_SNAKE_CASE_ , name="""pooler""")
lowercase__ : Tuple = [
tf.keras.layers.ConvaD(filters=SCREAMING_SNAKE_CASE_ , kernel_size=1 , activation="""relu""" , name="""attention.0"""),
tf.keras.layers.ConvaD(filters=SCREAMING_SNAKE_CASE_ , kernel_size=1 , activation="""sigmoid""" , name="""attention.2"""),
]
def lowercase__ ( self , SCREAMING_SNAKE_CASE_):
'''simple docstring'''
lowercase__ : Optional[Any] = self.pooler(SCREAMING_SNAKE_CASE_)
for layer_module in self.attention:
lowercase__ : Optional[Any] = layer_module(SCREAMING_SNAKE_CASE_)
lowercase__ : Any = hidden_state * pooled
return hidden_state
class _snake_case ( tf.keras.layers.Layer ):
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 1 , **SCREAMING_SNAKE_CASE_):
'''simple docstring'''
super().__init__(**SCREAMING_SNAKE_CASE_)
lowercase__ : int = in_channels != out_channels or stride != 1
lowercase__ : Any = max(1 , out_channels // config.groups_width)
lowercase__ : List[Any] = (
TFRegNetShortCut(SCREAMING_SNAKE_CASE_ , stride=SCREAMING_SNAKE_CASE_ , name="""shortcut""")
if should_apply_shortcut
else tf.keras.layers.Activation("""linear""" , name="""shortcut""")
)
# `self.layers` instead of `self.layer` because that is a reserved argument.
lowercase__ : Optional[int] = [
TFRegNetConvLayer(SCREAMING_SNAKE_CASE_ , kernel_size=1 , activation=config.hidden_act , name="""layer.0"""),
TFRegNetConvLayer(
SCREAMING_SNAKE_CASE_ , stride=SCREAMING_SNAKE_CASE_ , groups=SCREAMING_SNAKE_CASE_ , activation=config.hidden_act , name="""layer.1"""),
TFRegNetConvLayer(SCREAMING_SNAKE_CASE_ , kernel_size=1 , activation=SCREAMING_SNAKE_CASE_ , name="""layer.2"""),
]
lowercase__ : Tuple = ACTaFN[config.hidden_act]
def lowercase__ ( self , SCREAMING_SNAKE_CASE_):
'''simple docstring'''
lowercase__ : Tuple = hidden_state
for layer_module in self.layers:
lowercase__ : Any = layer_module(SCREAMING_SNAKE_CASE_)
lowercase__ : Union[str, Any] = self.shortcut(SCREAMING_SNAKE_CASE_)
hidden_state += residual
lowercase__ : Any = self.activation(SCREAMING_SNAKE_CASE_)
return hidden_state
class _snake_case ( tf.keras.layers.Layer ):
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 1 , **SCREAMING_SNAKE_CASE_):
'''simple docstring'''
super().__init__(**SCREAMING_SNAKE_CASE_)
lowercase__ : Any = in_channels != out_channels or stride != 1
lowercase__ : str = max(1 , out_channels // config.groups_width)
lowercase__ : int = (
TFRegNetShortCut(SCREAMING_SNAKE_CASE_ , stride=SCREAMING_SNAKE_CASE_ , name="""shortcut""")
if should_apply_shortcut
else tf.keras.layers.Activation("""linear""" , name="""shortcut""")
)
lowercase__ : Any = [
TFRegNetConvLayer(SCREAMING_SNAKE_CASE_ , kernel_size=1 , activation=config.hidden_act , name="""layer.0"""),
TFRegNetConvLayer(
SCREAMING_SNAKE_CASE_ , stride=SCREAMING_SNAKE_CASE_ , groups=SCREAMING_SNAKE_CASE_ , activation=config.hidden_act , name="""layer.1"""),
TFRegNetSELayer(SCREAMING_SNAKE_CASE_ , reduced_channels=int(round(in_channels / 4)) , name="""layer.2"""),
TFRegNetConvLayer(SCREAMING_SNAKE_CASE_ , kernel_size=1 , activation=SCREAMING_SNAKE_CASE_ , name="""layer.3"""),
]
lowercase__ : Union[str, Any] = ACTaFN[config.hidden_act]
def lowercase__ ( self , SCREAMING_SNAKE_CASE_):
'''simple docstring'''
lowercase__ : Union[str, Any] = hidden_state
for layer_module in self.layers:
lowercase__ : Optional[Any] = layer_module(SCREAMING_SNAKE_CASE_)
lowercase__ : Optional[int] = self.shortcut(SCREAMING_SNAKE_CASE_)
hidden_state += residual
lowercase__ : Optional[int] = self.activation(SCREAMING_SNAKE_CASE_)
return hidden_state
class _snake_case ( tf.keras.layers.Layer ):
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 2 , SCREAMING_SNAKE_CASE_ = 2 , **SCREAMING_SNAKE_CASE_):
'''simple docstring'''
super().__init__(**SCREAMING_SNAKE_CASE_)
lowercase__ : Any = TFRegNetXLayer if config.layer_type == """x""" else TFRegNetYLayer
lowercase__ : Dict = [
# downsampling is done in the first layer with stride of 2
layer(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , stride=SCREAMING_SNAKE_CASE_ , name="""layers.0"""),
*[layer(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , name=f'layers.{i+1}') for i in range(depth - 1)],
]
def lowercase__ ( self , SCREAMING_SNAKE_CASE_):
'''simple docstring'''
for layer_module in self.layers:
lowercase__ : Tuple = layer_module(SCREAMING_SNAKE_CASE_)
return hidden_state
class _snake_case ( tf.keras.layers.Layer ):
def __init__( self , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_):
'''simple docstring'''
super().__init__(**SCREAMING_SNAKE_CASE_)
lowercase__ : Tuple = []
# based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
self.stages.append(
TFRegNetStage(
SCREAMING_SNAKE_CASE_ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name="""stages.0""" , ))
lowercase__ : List[Any] = zip(config.hidden_sizes , config.hidden_sizes[1:])
for i, ((in_channels, out_channels), depth) in enumerate(zip(SCREAMING_SNAKE_CASE_ , config.depths[1:])):
self.stages.append(TFRegNetStage(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , depth=SCREAMING_SNAKE_CASE_ , name=f'stages.{i+1}'))
def lowercase__ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = True):
'''simple docstring'''
lowercase__ : Any = () if output_hidden_states else None
for stage_module in self.stages:
if output_hidden_states:
lowercase__ : List[Any] = hidden_states + (hidden_state,)
lowercase__ : str = stage_module(SCREAMING_SNAKE_CASE_)
if output_hidden_states:
lowercase__ : Optional[int] = hidden_states + (hidden_state,)
if not return_dict:
return tuple(v for v in [hidden_state, hidden_states] if v is not None)
return TFBaseModelOutputWithNoAttention(last_hidden_state=SCREAMING_SNAKE_CASE_ , hidden_states=SCREAMING_SNAKE_CASE_)
@keras_serializable
class _snake_case ( tf.keras.layers.Layer ):
__lowerCAmelCase : List[Any] = RegNetConfig
def __init__( self , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_):
'''simple docstring'''
super().__init__(**SCREAMING_SNAKE_CASE_)
lowercase__ : Dict = config
lowercase__ : List[Any] = TFRegNetEmbeddings(SCREAMING_SNAKE_CASE_ , name="""embedder""")
lowercase__ : Any = TFRegNetEncoder(SCREAMING_SNAKE_CASE_ , name="""encoder""")
lowercase__ : Optional[int] = tf.keras.layers.GlobalAveragePoolingaD(keepdims=SCREAMING_SNAKE_CASE_ , name="""pooler""")
@unpack_inputs
def lowercase__ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , ):
'''simple docstring'''
lowercase__ : str = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
lowercase__ : str = return_dict if return_dict is not None else self.config.use_return_dict
lowercase__ : Any = self.embedder(SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_)
lowercase__ : Any = self.encoder(
SCREAMING_SNAKE_CASE_ , output_hidden_states=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_)
lowercase__ : Optional[int] = encoder_outputs[0]
lowercase__ : Tuple = self.pooler(SCREAMING_SNAKE_CASE_)
# Change to NCHW output format have uniformity in the modules
lowercase__ : Dict = tf.transpose(SCREAMING_SNAKE_CASE_ , perm=(0, 3, 1, 2))
lowercase__ : Optional[Any] = tf.transpose(SCREAMING_SNAKE_CASE_ , perm=(0, 3, 1, 2))
# Change the other hidden state outputs to NCHW as well
if output_hidden_states:
lowercase__ : Optional[int] = tuple([tf.transpose(SCREAMING_SNAKE_CASE_ , perm=(0, 3, 1, 2)) for h in encoder_outputs[1]])
if not return_dict:
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
return TFBaseModelOutputWithPoolingAndNoAttention(
last_hidden_state=SCREAMING_SNAKE_CASE_ , pooler_output=SCREAMING_SNAKE_CASE_ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , )
class _snake_case ( UpperCAmelCase_ ):
__lowerCAmelCase : Dict = RegNetConfig
__lowerCAmelCase : Any = 'regnet'
__lowerCAmelCase : List[str] = 'pixel_values'
@property
def lowercase__ ( self):
'''simple docstring'''
return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24) , dtype=tf.floataa)}
lowerCamelCase__ : str = R"""
Parameters:
This model is a Tensorflow
[tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a
regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and
behavior.
config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
"""
lowerCamelCase__ : Dict = R"""
Args:
pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
[`ConveNextImageProcessor.__call__`] for details.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
@add_start_docstrings(
'The bare RegNet model outputting raw features without any specific head on top.' , UpperCAmelCase_ , )
class _snake_case ( UpperCAmelCase_ ):
def __init__( self , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_):
'''simple docstring'''
super().__init__(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_)
lowercase__ : Any = TFRegNetMainLayer(SCREAMING_SNAKE_CASE_ , name="""regnet""")
@unpack_inputs
@add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE_)
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC , output_type=SCREAMING_SNAKE_CASE_ , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , )
def lowercase__ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_=False , ):
'''simple docstring'''
lowercase__ : int = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
lowercase__ : List[str] = return_dict if return_dict is not None else self.config.use_return_dict
lowercase__ : Dict = self.regnet(
pixel_values=SCREAMING_SNAKE_CASE_ , output_hidden_states=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_ , )
if not return_dict:
return (outputs[0],) + outputs[1:]
return TFBaseModelOutputWithPoolingAndNoAttention(
last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , )
@add_start_docstrings(
'\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , UpperCAmelCase_ , )
class _snake_case ( UpperCAmelCase_ , UpperCAmelCase_ ):
def __init__( self , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_):
'''simple docstring'''
super().__init__(SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_)
lowercase__ : int = config.num_labels
lowercase__ : Optional[int] = TFRegNetMainLayer(SCREAMING_SNAKE_CASE_ , name="""regnet""")
# classification head
lowercase__ : Any = [
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(config.num_labels , name="""classifier.1""") if config.num_labels > 0 else tf.identity,
]
@unpack_inputs
@add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE_)
@add_code_sample_docstrings(
checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=SCREAMING_SNAKE_CASE_ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , )
def lowercase__ ( self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_=False , ):
'''simple docstring'''
lowercase__ : List[Any] = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
lowercase__ : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict
lowercase__ : List[str] = self.regnet(
SCREAMING_SNAKE_CASE_ , output_hidden_states=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_)
lowercase__ : Dict = outputs.pooler_output if return_dict else outputs[1]
lowercase__ : Optional[int] = self.classifier[0](SCREAMING_SNAKE_CASE_)
lowercase__ : List[str] = self.classifier[1](SCREAMING_SNAKE_CASE_)
lowercase__ : str = None if labels is None else self.hf_compute_loss(labels=SCREAMING_SNAKE_CASE_ , logits=SCREAMING_SNAKE_CASE_)
if not return_dict:
lowercase__ : Optional[int] = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return TFSequenceClassifierOutput(loss=SCREAMING_SNAKE_CASE_ , logits=SCREAMING_SNAKE_CASE_ , hidden_states=outputs.hidden_states)
| 495 | 1 |
'''simple docstring'''
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
_a : Optional[Any] = logging.get_logger(__name__)
_a : Dict = {
"andreasmadsen/efficient_mlm_m0.40": (
"https://huggingface.co/andreasmadsen/efficient_mlm_m0.40/resolve/main/config.json"
),
}
class _lowercase ( __lowercase ):
_SCREAMING_SNAKE_CASE : List[Any] = "roberta-prelayernorm"
def __init__( self : List[str] , SCREAMING_SNAKE_CASE_ : List[Any]=5_0265 , SCREAMING_SNAKE_CASE_ : str=768 , SCREAMING_SNAKE_CASE_ : Optional[Any]=12 , SCREAMING_SNAKE_CASE_ : Any=12 , SCREAMING_SNAKE_CASE_ : Dict=3072 , SCREAMING_SNAKE_CASE_ : Union[str, Any]="gelu" , SCREAMING_SNAKE_CASE_ : int=0.1 , SCREAMING_SNAKE_CASE_ : str=0.1 , SCREAMING_SNAKE_CASE_ : List[str]=512 , SCREAMING_SNAKE_CASE_ : str=2 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0.0_2 , SCREAMING_SNAKE_CASE_ : List[str]=1e-12 , SCREAMING_SNAKE_CASE_ : Dict=1 , SCREAMING_SNAKE_CASE_ : int=0 , SCREAMING_SNAKE_CASE_ : Any=2 , SCREAMING_SNAKE_CASE_ : Tuple="absolute" , SCREAMING_SNAKE_CASE_ : Tuple=True , SCREAMING_SNAKE_CASE_ : Any=None , **SCREAMING_SNAKE_CASE_ : int , ) -> Tuple:
super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
__snake_case = vocab_size
__snake_case = hidden_size
__snake_case = num_hidden_layers
__snake_case = num_attention_heads
__snake_case = hidden_act
__snake_case = intermediate_size
__snake_case = hidden_dropout_prob
__snake_case = attention_probs_dropout_prob
__snake_case = max_position_embeddings
__snake_case = type_vocab_size
__snake_case = initializer_range
__snake_case = layer_norm_eps
__snake_case = position_embedding_type
__snake_case = use_cache
__snake_case = classifier_dropout
class _lowercase ( __lowercase ):
@property
def a ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]:
if self.task == "multiple-choice":
__snake_case = {0: 'batch', 1: 'choice', 2: 'sequence'}
else:
__snake_case = {0: 'batch', 1: 'sequence'}
return OrderedDict(
[
('input_ids', dynamic_axis),
('attention_mask', dynamic_axis),
] )
| 56 |
'''simple docstring'''
# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import os
from accelerate.utils import ComputeEnvironment
from .cluster import get_cluster_input
from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401
from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401
from .sagemaker import get_sagemaker_input
_a : str = "Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine"
def _a () -> Dict:
"""simple docstring"""
__snake_case = _ask_options(
'In which compute environment are you running?' , ['This machine', 'AWS (Amazon SageMaker)'] , _convert_compute_environment , )
if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
__snake_case = get_sagemaker_input()
else:
__snake_case = get_cluster_input()
return config
def _a (lowercase__ : Union[str, Any]=None ) -> int:
"""simple docstring"""
if subparsers is not None:
__snake_case = subparsers.add_parser('config' , description=lowercase__ )
else:
__snake_case = argparse.ArgumentParser('Accelerate config command' , description=lowercase__ )
parser.add_argument(
'--config_file' , default=lowercase__ , help=(
'The path to use to store the config file. Will default to a file named default_config.yaml in the cache '
'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '
'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '
'with \'huggingface\'.'
) , )
if subparsers is not None:
parser.set_defaults(func=lowercase__ )
return parser
def _a (lowercase__ : List[str] ) -> Union[str, Any]:
"""simple docstring"""
__snake_case = get_user_input()
if args.config_file is not None:
__snake_case = args.config_file
else:
if not os.path.isdir(lowercase__ ):
os.makedirs(lowercase__ )
__snake_case = default_yaml_config_file
if config_file.endswith('.json' ):
config.to_json_file(lowercase__ )
else:
config.to_yaml_file(lowercase__ )
print(f'accelerate configuration saved at {config_file}' )
def _a () -> int:
"""simple docstring"""
__snake_case = config_command_parser()
__snake_case = parser.parse_args()
config_command(lowercase__ )
if __name__ == "__main__":
main()
| 56 | 1 |
"""simple docstring"""
from typing import Dict, List, Optional, Tuple, Union
import torch
from ...models import AutoencoderKL, TransformeraDModel
from ...schedulers import KarrasDiffusionSchedulers
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class lowerCAmelCase__ ( lowercase__ ):
'''simple docstring'''
def __init__( self : Tuple , lowercase_ : TransformeraDModel , lowercase_ : AutoencoderKL , lowercase_ : KarrasDiffusionSchedulers , lowercase_ : Optional[Dict[int, str]] = None , ):
'''simple docstring'''
super().__init__()
self.register_modules(transformer=__lowerCamelCase , vae=__lowerCamelCase , scheduler=__lowerCamelCase)
# create a imagenet -> id dictionary for easier use
SCREAMING_SNAKE_CASE_ : Dict = {}
if idalabel is not None:
for key, value in idalabel.items():
for label in value.split(''','''):
SCREAMING_SNAKE_CASE_ : Dict = int(__lowerCamelCase)
SCREAMING_SNAKE_CASE_ : str = dict(sorted(self.labels.items()))
def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : Union[str, List[str]]):
'''simple docstring'''
if not isinstance(__lowerCamelCase , __lowerCamelCase):
SCREAMING_SNAKE_CASE_ : Optional[int] = list(__lowerCamelCase)
for l in label:
if l not in self.labels:
raise ValueError(
F'{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}.')
return [self.labels[l] for l in label]
@torch.no_grad()
def __call__( self : List[Any] , lowercase_ : List[int] , lowercase_ : float = 4.0 , lowercase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowercase_ : int = 50 , lowercase_ : Optional[str] = "pil" , lowercase_ : bool = True , ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ : str = len(__lowerCamelCase)
SCREAMING_SNAKE_CASE_ : Dict = self.transformer.config.sample_size
SCREAMING_SNAKE_CASE_ : Tuple = self.transformer.config.in_channels
SCREAMING_SNAKE_CASE_ : Union[str, Any] = randn_tensor(
shape=(batch_size, latent_channels, latent_size, latent_size) , generator=__lowerCamelCase , device=self.device , dtype=self.transformer.dtype , )
SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.cat([latents] * 2) if guidance_scale > 1 else latents
SCREAMING_SNAKE_CASE_ : List[Any] = torch.tensor(__lowerCamelCase , device=self.device).reshape(-1)
SCREAMING_SNAKE_CASE_ : str = torch.tensor([1000] * batch_size , device=self.device)
SCREAMING_SNAKE_CASE_ : List[Any] = torch.cat([class_labels, class_null] , 0) if guidance_scale > 1 else class_labels
# set step values
self.scheduler.set_timesteps(__lowerCamelCase)
for t in self.progress_bar(self.scheduler.timesteps):
if guidance_scale > 1:
SCREAMING_SNAKE_CASE_ : int = latent_model_input[: len(__lowerCamelCase) // 2]
SCREAMING_SNAKE_CASE_ : Tuple = torch.cat([half, half] , dim=0)
SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.scheduler.scale_model_input(__lowerCamelCase , __lowerCamelCase)
SCREAMING_SNAKE_CASE_ : Optional[int] = t
if not torch.is_tensor(__lowerCamelCase):
# TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
# This would be a good case for the `match` statement (Python 3.10+)
SCREAMING_SNAKE_CASE_ : List[Any] = latent_model_input.device.type == "mps"
if isinstance(__lowerCamelCase , __lowerCamelCase):
SCREAMING_SNAKE_CASE_ : List[str] = torch.floataa if is_mps else torch.floataa
else:
SCREAMING_SNAKE_CASE_ : Any = torch.intaa if is_mps else torch.intaa
SCREAMING_SNAKE_CASE_ : Dict = torch.tensor([timesteps] , dtype=__lowerCamelCase , device=latent_model_input.device)
elif len(timesteps.shape) == 0:
SCREAMING_SNAKE_CASE_ : Any = timesteps[None].to(latent_model_input.device)
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
SCREAMING_SNAKE_CASE_ : Any = timesteps.expand(latent_model_input.shape[0])
# predict noise model_output
SCREAMING_SNAKE_CASE_ : List[str] = self.transformer(
__lowerCamelCase , timestep=__lowerCamelCase , class_labels=__lowerCamelCase).sample
# perform guidance
if guidance_scale > 1:
SCREAMING_SNAKE_CASE_ : Optional[int] = noise_pred[:, :latent_channels], noise_pred[:, latent_channels:]
SCREAMING_SNAKE_CASE_ : Dict = torch.split(__lowerCamelCase , len(__lowerCamelCase) // 2 , dim=0)
SCREAMING_SNAKE_CASE_ : Any = uncond_eps + guidance_scale * (cond_eps - uncond_eps)
SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.cat([half_eps, half_eps] , dim=0)
SCREAMING_SNAKE_CASE_ : Tuple = torch.cat([eps, rest] , dim=1)
# learned sigma
if self.transformer.config.out_channels // 2 == latent_channels:
SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.split(__lowerCamelCase , __lowerCamelCase , dim=1)
else:
SCREAMING_SNAKE_CASE_ : str = noise_pred
# compute previous image: x_t -> x_t-1
SCREAMING_SNAKE_CASE_ : Dict = self.scheduler.step(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase).prev_sample
if guidance_scale > 1:
SCREAMING_SNAKE_CASE_ : int = latent_model_input.chunk(2 , dim=0)
else:
SCREAMING_SNAKE_CASE_ : str = latent_model_input
SCREAMING_SNAKE_CASE_ : Optional[int] = 1 / self.vae.config.scaling_factor * latents
SCREAMING_SNAKE_CASE_ : Optional[int] = self.vae.decode(__lowerCamelCase).sample
SCREAMING_SNAKE_CASE_ : List[str] = (samples / 2 + 0.5).clamp(0 , 1)
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
SCREAMING_SNAKE_CASE_ : Dict = samples.cpu().permute(0 , 2 , 3 , 1).float().numpy()
if output_type == "pil":
SCREAMING_SNAKE_CASE_ : List[Any] = self.numpy_to_pil(__lowerCamelCase)
if not return_dict:
return (samples,)
return ImagePipelineOutput(images=__lowerCamelCase)
| 705 |
"""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
UpperCAmelCase_ : 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 (__a , __a , __a , __a=None ) -> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : str = XLNetConfig.from_json_file(__a )
SCREAMING_SNAKE_CASE_ : List[Any] = 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}' )
SCREAMING_SNAKE_CASE_ : List[Any] = finetuning_task
SCREAMING_SNAKE_CASE_ : Optional[Any] = GLUE_TASKS_NUM_LABELS[finetuning_task]
SCREAMING_SNAKE_CASE_ : Dict = XLNetForSequenceClassification(__a )
elif "squad" in finetuning_task:
SCREAMING_SNAKE_CASE_ : str = finetuning_task
SCREAMING_SNAKE_CASE_ : Dict = XLNetForQuestionAnswering(__a )
else:
SCREAMING_SNAKE_CASE_ : List[str] = XLNetLMHeadModel(__a )
# Load weights from tf checkpoint
load_tf_weights_in_xlnet(__a , __a , __a )
# Save pytorch-model
SCREAMING_SNAKE_CASE_ : Optional[Any] = os.path.join(__a , __a )
SCREAMING_SNAKE_CASE_ : Union[str, Any] = os.path.join(__a , __a )
print(f'Save PyTorch model to {os.path.abspath(__a )}' )
torch.save(model.state_dict() , __a )
print(f'Save configuration file to {os.path.abspath(__a )}' )
with open(__a , '''w''' , encoding='''utf-8''' ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
UpperCAmelCase_ : str = 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""",
)
UpperCAmelCase_ : int = 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
)
| 176 | 0 |
def UpperCamelCase ( ) -> list[list[int]]:
'''simple docstring'''
return [list(range(10_00 - i , -10_00 - i , -1 ) ) for i in range(10_00 )]
lowerCamelCase__ : str = generate_large_matrix()
lowerCamelCase__ : Dict = (
[[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]],
[[3, 2], [1, 0]],
[[7, 7, 6]],
[[7, 7, 6], [-1, -2, -3]],
grid,
)
def UpperCamelCase ( lowercase_ ) -> None:
'''simple docstring'''
assert all(row == sorted(lowercase_ , reverse=lowercase_ ) for row in grid )
assert all(list(lowercase_ ) == sorted(lowercase_ , reverse=lowercase_ ) for col in zip(*lowercase_ ) )
def UpperCamelCase ( lowercase_ ) -> int:
'''simple docstring'''
lowercase__ : Optional[int] = 0
lowercase__ : Optional[int] = len(lowercase_ ) - 1
# Edge cases such as no values or all numbers are negative.
if not array or array[0] < 0:
return 0
while right + 1 > left:
lowercase__ : Optional[int] = (left + right) // 2
lowercase__ : Union[str, Any] = array[mid]
# Num must be negative and the index must be greater than or equal to 0.
if num < 0 and array[mid - 1] >= 0:
return mid
if num >= 0:
lowercase__ : int = mid + 1
else:
lowercase__ : Any = mid - 1
# No negative numbers so return the last index of the array + 1 which is the length.
return len(lowercase_ )
def UpperCamelCase ( lowercase_ ) -> int:
'''simple docstring'''
lowercase__ : List[Any] = 0
lowercase__ : int = len(grid[0] )
for i in range(len(lowercase_ ) ):
lowercase__ : Tuple = find_negative_index(grid[i][:bound] )
total += bound
return (len(lowercase_ ) * len(grid[0] )) - total
def UpperCamelCase ( lowercase_ ) -> int:
'''simple docstring'''
return len([number for row in grid for number in row if number < 0] )
def UpperCamelCase ( lowercase_ ) -> int:
'''simple docstring'''
lowercase__ : Tuple = 0
for row in grid:
for i, number in enumerate(lowercase_ ):
if number < 0:
total += len(lowercase_ ) - i
break
return total
def UpperCamelCase ( ) -> None:
'''simple docstring'''
from timeit import timeit
print("""Running benchmarks""" )
lowercase__ : Optional[int] = (
"""from __main__ import count_negatives_binary_search, """
"""count_negatives_brute_force, count_negatives_brute_force_with_break, grid"""
)
for func in (
"count_negatives_binary_search", # took 0.7727 seconds
"count_negatives_brute_force_with_break", # took 4.6505 seconds
"count_negatives_brute_force", # took 12.8160 seconds
):
lowercase__ : Tuple = timeit(F'{func}(grid=grid)' , setup=lowercase_ , number=5_00 )
print(F'{func}() took {time:0.4f} seconds' )
if __name__ == "__main__":
import doctest
doctest.testmod()
benchmark()
| 12 |
from __future__ import annotations
import bisect
def a_ ( __magic_name__ , __magic_name__ , __magic_name__ = 0 , __magic_name__ = -1 ) -> int:
"""simple docstring"""
if hi < 0:
snake_case : Optional[int] = len(__magic_name__ )
while lo < hi:
snake_case : List[Any] = lo + (hi - lo) // 2
if sorted_collection[mid] < item:
snake_case : List[str] = mid + 1
else:
snake_case : Tuple = mid
return lo
def a_ ( __magic_name__ , __magic_name__ , __magic_name__ = 0 , __magic_name__ = -1 ) -> int:
"""simple docstring"""
if hi < 0:
snake_case : Any = len(__magic_name__ )
while lo < hi:
snake_case : List[Any] = lo + (hi - lo) // 2
if sorted_collection[mid] <= item:
snake_case : Optional[Any] = mid + 1
else:
snake_case : List[Any] = mid
return lo
def a_ ( __magic_name__ , __magic_name__ , __magic_name__ = 0 , __magic_name__ = -1 ) -> None:
"""simple docstring"""
sorted_collection.insert(bisect_left(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) , __magic_name__ )
def a_ ( __magic_name__ , __magic_name__ , __magic_name__ = 0 , __magic_name__ = -1 ) -> None:
"""simple docstring"""
sorted_collection.insert(bisect_right(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) , __magic_name__ )
def a_ ( __magic_name__ , __magic_name__ ) -> int | None:
"""simple docstring"""
snake_case : List[str] = 0
snake_case : Optional[Any] = len(__magic_name__ ) - 1
while left <= right:
snake_case : Optional[int] = left + (right - left) // 2
snake_case : Any = sorted_collection[midpoint]
if current_item == item:
return midpoint
elif item < current_item:
snake_case : Optional[Any] = midpoint - 1
else:
snake_case : List[str] = midpoint + 1
return None
def a_ ( __magic_name__ , __magic_name__ ) -> int | None:
"""simple docstring"""
snake_case : Tuple = bisect.bisect_left(__magic_name__ , __magic_name__ )
if index != len(__magic_name__ ) and sorted_collection[index] == item:
return index
return None
def a_ ( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) -> int | None:
"""simple docstring"""
if right < left:
return None
snake_case : Tuple = left + (right - left) // 2
if sorted_collection[midpoint] == item:
return midpoint
elif sorted_collection[midpoint] > item:
return binary_search_by_recursion(__magic_name__ , __magic_name__ , __magic_name__ , midpoint - 1 )
else:
return binary_search_by_recursion(__magic_name__ , __magic_name__ , midpoint + 1 , __magic_name__ )
if __name__ == "__main__":
_a : Optional[Any] = input('Enter numbers separated by comma:\n').strip()
_a : List[str] = sorted(int(item) for item in user_input.split(','))
_a : str = int(input('Enter a single number to be found in the list:\n'))
_a : Tuple = binary_search(collection, target)
if result is None:
print(f"{target} was not found in {collection}.")
else:
print(f"{target} was found at position {result} in {collection}.")
| 598 | 0 |
import gc
import random
import tempfile
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import require_torch_gpu
class a_ ( unittest.TestCase ):
"""simple docstring"""
def _lowerCAmelCase ( self : Tuple ) -> Union[str, Any]:
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
@property
def _lowerCAmelCase ( self : int ) -> Optional[Any]:
SCREAMING_SNAKE_CASE =1
SCREAMING_SNAKE_CASE =3
SCREAMING_SNAKE_CASE =(32, 32)
SCREAMING_SNAKE_CASE =floats_tensor((batch_size, num_channels) + sizes ,rng=random.Random(0 ) ).to(snake_case )
return image
@property
def _lowerCAmelCase ( self : Any ) -> str:
torch.manual_seed(0 )
SCREAMING_SNAKE_CASE =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 ,)
return model
@property
def _lowerCAmelCase ( self : Any ) -> Tuple:
torch.manual_seed(0 )
SCREAMING_SNAKE_CASE =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 ,)
return model
@property
def _lowerCAmelCase ( self : str ) -> str:
torch.manual_seed(0 )
SCREAMING_SNAKE_CASE =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 ,)
return CLIPTextModel(snake_case )
@property
def _lowerCAmelCase ( self : Tuple ) -> Union[str, Any]:
def extract(*snake_case : List[Any] ,**snake_case : Optional[Any] ):
class a_ :
"""simple docstring"""
def __init__( self : Optional[Any] ) -> Dict:
SCREAMING_SNAKE_CASE =torch.ones([0] )
def _lowerCAmelCase ( self : Any ,snake_case : Dict ) -> Tuple:
self.pixel_values.to(snake_case )
return self
return Out()
return extract
def _lowerCAmelCase ( self : Union[str, Any] ) -> Union[str, Any]:
SCREAMING_SNAKE_CASE ='cpu' # ensure determinism for the device-dependent torch.Generator
SCREAMING_SNAKE_CASE =self.dummy_cond_unet
SCREAMING_SNAKE_CASE =DDIMScheduler(
beta_start=0.00_085 ,beta_end=0.012 ,beta_schedule='scaled_linear' ,clip_sample=snake_case ,set_alpha_to_one=snake_case ,)
SCREAMING_SNAKE_CASE =self.dummy_vae
SCREAMING_SNAKE_CASE =self.dummy_text_encoder
SCREAMING_SNAKE_CASE =CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )
# make sure here that pndm scheduler skips prk
SCREAMING_SNAKE_CASE =StableDiffusionPipeline(
unet=snake_case ,scheduler=snake_case ,vae=snake_case ,text_encoder=snake_case ,tokenizer=snake_case ,safety_checker=snake_case ,feature_extractor=self.dummy_extractor ,)
SCREAMING_SNAKE_CASE =sd_pipe.to(snake_case )
sd_pipe.set_progress_bar_config(disable=snake_case )
SCREAMING_SNAKE_CASE ='A painting of a squirrel eating a burger'
SCREAMING_SNAKE_CASE =torch.Generator(device=snake_case ).manual_seed(0 )
SCREAMING_SNAKE_CASE =sd_pipe([prompt] ,generator=snake_case ,guidance_scale=6.0 ,num_inference_steps=2 ,output_type='np' )
SCREAMING_SNAKE_CASE =output.images
SCREAMING_SNAKE_CASE =torch.Generator(device=snake_case ).manual_seed(0 )
SCREAMING_SNAKE_CASE =sd_pipe(
[prompt] ,generator=snake_case ,guidance_scale=6.0 ,num_inference_steps=2 ,output_type='np' ,return_dict=snake_case ,)[0]
SCREAMING_SNAKE_CASE =image[0, -3:, -3:, -1]
SCREAMING_SNAKE_CASE =image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
SCREAMING_SNAKE_CASE =np.array([0.5_756, 0.6_118, 0.5_005, 0.5_041, 0.5_471, 0.4_726, 0.4_976, 0.4_865, 0.4_864] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
def _lowerCAmelCase ( self : Union[str, Any] ) -> int:
SCREAMING_SNAKE_CASE ='cpu' # ensure determinism for the device-dependent torch.Generator
SCREAMING_SNAKE_CASE =self.dummy_cond_unet
SCREAMING_SNAKE_CASE =PNDMScheduler(skip_prk_steps=snake_case )
SCREAMING_SNAKE_CASE =self.dummy_vae
SCREAMING_SNAKE_CASE =self.dummy_text_encoder
SCREAMING_SNAKE_CASE =CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )
# make sure here that pndm scheduler skips prk
SCREAMING_SNAKE_CASE =StableDiffusionPipeline(
unet=snake_case ,scheduler=snake_case ,vae=snake_case ,text_encoder=snake_case ,tokenizer=snake_case ,safety_checker=snake_case ,feature_extractor=self.dummy_extractor ,)
SCREAMING_SNAKE_CASE =sd_pipe.to(snake_case )
sd_pipe.set_progress_bar_config(disable=snake_case )
SCREAMING_SNAKE_CASE ='A painting of a squirrel eating a burger'
SCREAMING_SNAKE_CASE =torch.Generator(device=snake_case ).manual_seed(0 )
SCREAMING_SNAKE_CASE =sd_pipe([prompt] ,generator=snake_case ,guidance_scale=6.0 ,num_inference_steps=2 ,output_type='np' )
SCREAMING_SNAKE_CASE =output.images
SCREAMING_SNAKE_CASE =torch.Generator(device=snake_case ).manual_seed(0 )
SCREAMING_SNAKE_CASE =sd_pipe(
[prompt] ,generator=snake_case ,guidance_scale=6.0 ,num_inference_steps=2 ,output_type='np' ,return_dict=snake_case ,)[0]
SCREAMING_SNAKE_CASE =image[0, -3:, -3:, -1]
SCREAMING_SNAKE_CASE =image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
SCREAMING_SNAKE_CASE =np.array([0.5_125, 0.5_716, 0.4_828, 0.5_060, 0.5_650, 0.4_768, 0.5_185, 0.4_895, 0.4_993] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
def _lowerCAmelCase ( self : Any ) -> List[str]:
SCREAMING_SNAKE_CASE =StableDiffusionPipeline.from_pretrained(
'hf-internal-testing/tiny-stable-diffusion-lms-pipe' ,safety_checker=snake_case )
assert isinstance(snake_case ,snake_case )
assert isinstance(pipe.scheduler ,snake_case )
assert pipe.safety_checker is None
SCREAMING_SNAKE_CASE =pipe('example prompt' ,num_inference_steps=2 ).images[0]
assert image is not None
# check that there's no error when saving a pipeline with one of the models being None
with tempfile.TemporaryDirectory() as tmpdirname:
pipe.save_pretrained(snake_case )
SCREAMING_SNAKE_CASE =StableDiffusionPipeline.from_pretrained(snake_case )
# sanity check that the pipeline still works
assert pipe.safety_checker is None
SCREAMING_SNAKE_CASE =pipe('example prompt' ,num_inference_steps=2 ).images[0]
assert image is not None
@unittest.skipIf(torch_device != 'cuda' ,'This test requires a GPU' )
def _lowerCAmelCase ( self : List[str] ) -> Tuple:
SCREAMING_SNAKE_CASE =self.dummy_cond_unet
SCREAMING_SNAKE_CASE =PNDMScheduler(skip_prk_steps=snake_case )
SCREAMING_SNAKE_CASE =self.dummy_vae
SCREAMING_SNAKE_CASE =self.dummy_text_encoder
SCREAMING_SNAKE_CASE =CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )
# put models in fp16
SCREAMING_SNAKE_CASE =unet.half()
SCREAMING_SNAKE_CASE =vae.half()
SCREAMING_SNAKE_CASE =bert.half()
# make sure here that pndm scheduler skips prk
SCREAMING_SNAKE_CASE =StableDiffusionPipeline(
unet=snake_case ,scheduler=snake_case ,vae=snake_case ,text_encoder=snake_case ,tokenizer=snake_case ,safety_checker=snake_case ,feature_extractor=self.dummy_extractor ,)
SCREAMING_SNAKE_CASE =sd_pipe.to(snake_case )
sd_pipe.set_progress_bar_config(disable=snake_case )
SCREAMING_SNAKE_CASE ='A painting of a squirrel eating a burger'
SCREAMING_SNAKE_CASE =sd_pipe([prompt] ,num_inference_steps=2 ,output_type='np' ).images
assert image.shape == (1, 64, 64, 3)
@nightly
@require_torch_gpu
class a_ ( unittest.TestCase ):
"""simple docstring"""
def _lowerCAmelCase ( self : Any ) -> str:
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def _lowerCAmelCase ( self : List[Any] ) -> List[str]:
SCREAMING_SNAKE_CASE =StableDiffusionPipeline.from_pretrained('runwayml/stable-diffusion-v1-5' ,safety_checker=snake_case )
SCREAMING_SNAKE_CASE =LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config )
SCREAMING_SNAKE_CASE =sd_pipe.to(snake_case )
sd_pipe.set_progress_bar_config(disable=snake_case )
SCREAMING_SNAKE_CASE =(
'portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle'
' coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with'
' anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and'
' children from bahnhof zoo, detailed '
)
SCREAMING_SNAKE_CASE =4003660346
SCREAMING_SNAKE_CASE =7
# without safety guidance (sld_guidance_scale = 0)
SCREAMING_SNAKE_CASE =torch.manual_seed(snake_case )
SCREAMING_SNAKE_CASE =sd_pipe(
[prompt] ,generator=snake_case ,guidance_scale=snake_case ,num_inference_steps=50 ,output_type='np' ,width=512 ,height=512 ,sld_guidance_scale=0 ,)
SCREAMING_SNAKE_CASE =output.images
SCREAMING_SNAKE_CASE =image[0, -3:, -3:, -1]
SCREAMING_SNAKE_CASE =[0.2_278, 0.2_231, 0.2_249, 0.2_333, 0.2_303, 0.1_885, 0.2_273, 0.2_144, 0.2_176]
assert image.shape == (1, 512, 512, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
# without safety guidance (strong configuration)
SCREAMING_SNAKE_CASE =torch.manual_seed(snake_case )
SCREAMING_SNAKE_CASE =sd_pipe(
[prompt] ,generator=snake_case ,guidance_scale=snake_case ,num_inference_steps=50 ,output_type='np' ,width=512 ,height=512 ,sld_guidance_scale=2000 ,sld_warmup_steps=7 ,sld_threshold=0.025 ,sld_momentum_scale=0.5 ,sld_mom_beta=0.7 ,)
SCREAMING_SNAKE_CASE =output.images
SCREAMING_SNAKE_CASE =image[0, -3:, -3:, -1]
SCREAMING_SNAKE_CASE =[0.2_383, 0.2_276, 0.236, 0.2_192, 0.2_186, 0.2_053, 0.1_971, 0.1_901, 0.1_719]
assert image.shape == (1, 512, 512, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def _lowerCAmelCase ( self : List[str] ) -> Optional[int]:
SCREAMING_SNAKE_CASE =StableDiffusionPipeline.from_pretrained('runwayml/stable-diffusion-v1-5' ,safety_checker=snake_case )
SCREAMING_SNAKE_CASE =LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config )
SCREAMING_SNAKE_CASE =sd_pipe.to(snake_case )
sd_pipe.set_progress_bar_config(disable=snake_case )
SCREAMING_SNAKE_CASE ='padme amidala taking a bath artwork, safe for work, no nudity'
SCREAMING_SNAKE_CASE =2734971755
SCREAMING_SNAKE_CASE =7
SCREAMING_SNAKE_CASE =torch.manual_seed(snake_case )
SCREAMING_SNAKE_CASE =sd_pipe(
[prompt] ,generator=snake_case ,guidance_scale=snake_case ,num_inference_steps=50 ,output_type='np' ,width=512 ,height=512 ,sld_guidance_scale=0 ,)
SCREAMING_SNAKE_CASE =output.images
SCREAMING_SNAKE_CASE =image[0, -3:, -3:, -1]
SCREAMING_SNAKE_CASE =[0.3_502, 0.3_622, 0.3_396, 0.3_642, 0.3_478, 0.3_318, 0.35, 0.3_348, 0.3_297]
assert image.shape == (1, 512, 512, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
SCREAMING_SNAKE_CASE =torch.manual_seed(snake_case )
SCREAMING_SNAKE_CASE =sd_pipe(
[prompt] ,generator=snake_case ,guidance_scale=snake_case ,num_inference_steps=50 ,output_type='np' ,width=512 ,height=512 ,sld_guidance_scale=2000 ,sld_warmup_steps=7 ,sld_threshold=0.025 ,sld_momentum_scale=0.5 ,sld_mom_beta=0.7 ,)
SCREAMING_SNAKE_CASE =output.images
SCREAMING_SNAKE_CASE =image[0, -3:, -3:, -1]
SCREAMING_SNAKE_CASE =[0.5_531, 0.5_206, 0.4_895, 0.5_156, 0.5_182, 0.4_751, 0.4_802, 0.4_803, 0.4_443]
assert image.shape == (1, 512, 512, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def _lowerCAmelCase ( self : Optional[int] ) -> Union[str, Any]:
SCREAMING_SNAKE_CASE =StableDiffusionPipeline.from_pretrained('runwayml/stable-diffusion-v1-5' )
SCREAMING_SNAKE_CASE =sd_pipe.to(snake_case )
sd_pipe.set_progress_bar_config(disable=snake_case )
SCREAMING_SNAKE_CASE =(
'the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.'
' leyendecker'
)
SCREAMING_SNAKE_CASE =1044355234
SCREAMING_SNAKE_CASE =12
SCREAMING_SNAKE_CASE =torch.manual_seed(snake_case )
SCREAMING_SNAKE_CASE =sd_pipe(
[prompt] ,generator=snake_case ,guidance_scale=snake_case ,num_inference_steps=50 ,output_type='np' ,width=512 ,height=512 ,sld_guidance_scale=0 ,)
SCREAMING_SNAKE_CASE =output.images
SCREAMING_SNAKE_CASE =image[0, -3:, -3:, -1]
SCREAMING_SNAKE_CASE =np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] )
assert image.shape == (1, 512, 512, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-7
SCREAMING_SNAKE_CASE =torch.manual_seed(snake_case )
SCREAMING_SNAKE_CASE =sd_pipe(
[prompt] ,generator=snake_case ,guidance_scale=snake_case ,num_inference_steps=50 ,output_type='np' ,width=512 ,height=512 ,sld_guidance_scale=2000 ,sld_warmup_steps=7 ,sld_threshold=0.025 ,sld_momentum_scale=0.5 ,sld_mom_beta=0.7 ,)
SCREAMING_SNAKE_CASE =output.images
SCREAMING_SNAKE_CASE =image[0, -3:, -3:, -1]
SCREAMING_SNAKE_CASE =np.array([0.5_818, 0.6_285, 0.6_835, 0.6_019, 0.625, 0.6_754, 0.6_096, 0.6_334, 0.6_561] )
assert image.shape == (1, 512, 512, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
| 702 |
from manim import *
class a_ ( lowerCamelCase_ ):
"""simple docstring"""
def _lowerCAmelCase ( self : Optional[int] ):
SCREAMING_SNAKE_CASE =Rectangle(height=0.5 ,width=0.5 )
SCREAMING_SNAKE_CASE =Rectangle(height=0.46 ,width=0.46 ).set_stroke(width=0 )
SCREAMING_SNAKE_CASE =[mem.copy() for i in range(6 )]
SCREAMING_SNAKE_CASE =[mem.copy() for i in range(6 )]
SCREAMING_SNAKE_CASE =VGroup(*snake_case ).arrange(snake_case ,buff=0 )
SCREAMING_SNAKE_CASE =VGroup(*snake_case ).arrange(snake_case ,buff=0 )
SCREAMING_SNAKE_CASE =VGroup(snake_case ,snake_case ).arrange(snake_case ,buff=0 )
SCREAMING_SNAKE_CASE =Text('CPU' ,font_size=24 )
SCREAMING_SNAKE_CASE =Group(snake_case ,snake_case ).arrange(snake_case ,buff=0.5 ,aligned_edge=snake_case )
cpu.move_to([-2.5, -0.5, 0] )
self.add(snake_case )
SCREAMING_SNAKE_CASE =[mem.copy() for i in range(1 )]
SCREAMING_SNAKE_CASE =VGroup(*snake_case ).arrange(snake_case ,buff=0 )
SCREAMING_SNAKE_CASE =Text('GPU' ,font_size=24 )
SCREAMING_SNAKE_CASE =Group(snake_case ,snake_case ).arrange(snake_case ,buff=0.5 ,aligned_edge=snake_case )
gpu.align_to(snake_case ,snake_case )
gpu.set_x(gpu.get_x() - 1 )
self.add(snake_case )
SCREAMING_SNAKE_CASE =[mem.copy() for i in range(6 )]
SCREAMING_SNAKE_CASE =VGroup(*snake_case ).arrange(snake_case ,buff=0 )
SCREAMING_SNAKE_CASE =Text('Model' ,font_size=24 )
SCREAMING_SNAKE_CASE =Group(snake_case ,snake_case ).arrange(snake_case ,buff=0.5 ,aligned_edge=snake_case )
model.move_to([3, -1.0, 0] )
self.play(
Create(snake_case ,run_time=1 ) ,Create(snake_case ,run_time=1 ) ,Create(snake_case ,run_time=1 ) ,)
SCREAMING_SNAKE_CASE =MarkupText(
f'First, an empty model skeleton is loaded\ninto <span fgcolor=\'{YELLOW}\'>memory</span> without using much RAM.' ,font_size=24 ,)
SCREAMING_SNAKE_CASE =Square(side_length=2.2 )
key.move_to([-5, 2, 0] )
SCREAMING_SNAKE_CASE =MarkupText(
f'<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model' ,font_size=18 ,)
key_text.move_to([-5, 2.4, 0] )
step_a.move_to([2, 2, 0] )
self.play(Write(snake_case ,run_time=2.5 ) ,Write(snake_case ) ,Write(snake_case ) )
self.add(snake_case )
SCREAMING_SNAKE_CASE =[]
SCREAMING_SNAKE_CASE =[]
SCREAMING_SNAKE_CASE =[]
for i, rect in enumerate(snake_case ):
SCREAMING_SNAKE_CASE =Rectangle(height=0.46 ,width=0.46 ).set_stroke(width=0.0 ).set_fill(snake_case ,opacity=0.7 )
cpu_target.move_to(snake_case )
cpu_target.generate_target()
SCREAMING_SNAKE_CASE =0.46 / 4
SCREAMING_SNAKE_CASE =0.46 / 3
if i == 0:
cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) ,buff=0.02 ,direction=snake_case )
cpu_target.target.set_x(cpu_target.target.get_x() + 0.1 )
elif i == 3:
cpu_target.target.next_to(cpu_targs[0].target ,direction=snake_case ,buff=0.0 )
else:
cpu_target.target.next_to(cpu_targs[i - 1].target ,direction=snake_case ,buff=0.0 )
cpu_targs.append(snake_case )
first_animations.append(rect.animate(run_time=0.5 ).set_stroke(snake_case ) )
second_animations.append(MoveToTarget(snake_case ,run_time=1.5 ) )
self.play(*snake_case )
self.play(*snake_case )
self.wait()
| 252 | 0 |
'''simple docstring'''
import argparse
import json
from pathlib import Path
import requests
import timm
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification
def snake_case_ (UpperCamelCase : Union[str, Any] ):
'''simple docstring'''
_a = SwinvaConfig()
_a = swinva_name.split('''_''' )
_a = name_split[1]
if "to" in name_split[3]:
_a = int(name_split[3][-3:] )
else:
_a = int(name_split[3] )
if "to" in name_split[2]:
_a = int(name_split[2][-2:] )
else:
_a = int(name_split[2][6:] )
if model_size == "tiny":
_a = 96
_a = (2, 2, 6, 2)
_a = (3, 6, 12, 24)
elif model_size == "small":
_a = 96
_a = (2, 2, 18, 2)
_a = (3, 6, 12, 24)
elif model_size == "base":
_a = 128
_a = (2, 2, 18, 2)
_a = (4, 8, 16, 32)
else:
_a = 192
_a = (2, 2, 18, 2)
_a = (6, 12, 24, 48)
if "to" in swinva_name:
_a = (12, 12, 12, 6)
if ("22k" in swinva_name) and ("to" not in swinva_name):
_a = 2_1841
_a = '''huggingface/label-files'''
_a = '''imagenet-22k-id2label.json'''
_a = json.load(open(hf_hub_download(UpperCamelCase , UpperCamelCase , repo_type='''dataset''' ) , '''r''' ) )
_a = {int(UpperCamelCase ): v for k, v in idalabel.items()}
_a = idalabel
_a = {v: k for k, v in idalabel.items()}
else:
_a = 1000
_a = '''huggingface/label-files'''
_a = '''imagenet-1k-id2label.json'''
_a = json.load(open(hf_hub_download(UpperCamelCase , UpperCamelCase , repo_type='''dataset''' ) , '''r''' ) )
_a = {int(UpperCamelCase ): v for k, v in idalabel.items()}
_a = idalabel
_a = {v: k for k, v in idalabel.items()}
_a = img_size
_a = num_classes
_a = embed_dim
_a = depths
_a = num_heads
_a = window_size
return config
def snake_case_ (UpperCamelCase : str ):
'''simple docstring'''
if "patch_embed.proj" in name:
_a = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' )
if "patch_embed.norm" in name:
_a = name.replace('''patch_embed.norm''' , '''embeddings.norm''' )
if "layers" in name:
_a = '''encoder.''' + name
if "attn.proj" in name:
_a = name.replace('''attn.proj''' , '''attention.output.dense''' )
if "attn" in name:
_a = name.replace('''attn''' , '''attention.self''' )
if "norm1" in name:
_a = name.replace('''norm1''' , '''layernorm_before''' )
if "norm2" in name:
_a = name.replace('''norm2''' , '''layernorm_after''' )
if "mlp.fc1" in name:
_a = name.replace('''mlp.fc1''' , '''intermediate.dense''' )
if "mlp.fc2" in name:
_a = name.replace('''mlp.fc2''' , '''output.dense''' )
if "q_bias" in name:
_a = name.replace('''q_bias''' , '''query.bias''' )
if "k_bias" in name:
_a = name.replace('''k_bias''' , '''key.bias''' )
if "v_bias" in name:
_a = name.replace('''v_bias''' , '''value.bias''' )
if "cpb_mlp" in name:
_a = name.replace('''cpb_mlp''' , '''continuous_position_bias_mlp''' )
if name == "norm.weight":
_a = '''layernorm.weight'''
if name == "norm.bias":
_a = '''layernorm.bias'''
if "head" in name:
_a = name.replace('''head''' , '''classifier''' )
else:
_a = '''swinv2.''' + name
return name
def snake_case_ (UpperCamelCase : int , UpperCamelCase : Optional[Any] ):
'''simple docstring'''
for key in orig_state_dict.copy().keys():
_a = orig_state_dict.pop(UpperCamelCase )
if "mask" in key:
continue
elif "qkv" in key:
_a = key.split('''.''' )
_a = int(key_split[1] )
_a = int(key_split[3] )
_a = model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size
if "weight" in key:
_a = val[:dim, :]
_a = val[dim : dim * 2, :]
_a = val[-dim:, :]
else:
_a = val[:dim]
_a = val[
dim : dim * 2
]
_a = val[-dim:]
else:
_a = val
return orig_state_dict
def snake_case_ (UpperCamelCase : Dict , UpperCamelCase : List[Any] ):
'''simple docstring'''
_a = timm.create_model(UpperCamelCase , pretrained=UpperCamelCase )
timm_model.eval()
_a = get_swinva_config(UpperCamelCase )
_a = SwinvaForImageClassification(UpperCamelCase )
model.eval()
_a = convert_state_dict(timm_model.state_dict() , UpperCamelCase )
model.load_state_dict(UpperCamelCase )
_a = '''http://images.cocodataset.org/val2017/000000039769.jpg'''
_a = AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swinva_name.replace('''_''' , '''-''' ) ) )
_a = Image.open(requests.get(UpperCamelCase , stream=UpperCamelCase ).raw )
_a = image_processor(images=UpperCamelCase , return_tensors='''pt''' )
_a = timm_model(inputs['''pixel_values'''] )
_a = model(**UpperCamelCase ).logits
assert torch.allclose(UpperCamelCase , UpperCamelCase , atol=1e-3 )
print(f'Saving model {swinva_name} to {pytorch_dump_folder_path}' )
model.save_pretrained(UpperCamelCase )
print(f'Saving image processor to {pytorch_dump_folder_path}' )
image_processor.save_pretrained(UpperCamelCase )
model.push_to_hub(
repo_path_or_name=Path(UpperCamelCase , UpperCamelCase ) , organization='''nandwalritik''' , commit_message='''Add model''' , )
if __name__ == "__main__":
_snake_case : List[str] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--swinv2_name',
default='swinv2_tiny_patch4_window8_256',
type=str,
help='Name of the Swinv2 timm model you\'d like to convert.',
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.'
)
_snake_case : int = parser.parse_args()
convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
| 22 |
import inspect
import unittest
from transformers import ConvNextConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class lowerCamelCase :
'''simple docstring'''
def __init__( self , _UpperCamelCase , _UpperCamelCase=1_3 , _UpperCamelCase=3_2 , _UpperCamelCase=3 , _UpperCamelCase=4 , _UpperCamelCase=[1_0, 2_0, 3_0, 4_0] , _UpperCamelCase=[2, 2, 3, 2] , _UpperCamelCase=True , _UpperCamelCase=True , _UpperCamelCase=3_7 , _UpperCamelCase="gelu" , _UpperCamelCase=1_0 , _UpperCamelCase=0.02 , _UpperCamelCase=["stage2", "stage3", "stage4"] , _UpperCamelCase=[2, 3, 4] , _UpperCamelCase=None , ) -> str:
UpperCAmelCase_ : Union[str, Any] = parent
UpperCAmelCase_ : int = batch_size
UpperCAmelCase_ : List[Any] = image_size
UpperCAmelCase_ : List[str] = num_channels
UpperCAmelCase_ : List[Any] = num_stages
UpperCAmelCase_ : str = hidden_sizes
UpperCAmelCase_ : Any = depths
UpperCAmelCase_ : str = is_training
UpperCAmelCase_ : Tuple = use_labels
UpperCAmelCase_ : List[str] = intermediate_size
UpperCAmelCase_ : List[Any] = hidden_act
UpperCAmelCase_ : Union[str, Any] = num_labels
UpperCAmelCase_ : Union[str, Any] = initializer_range
UpperCAmelCase_ : List[str] = out_features
UpperCAmelCase_ : Optional[int] = out_indices
UpperCAmelCase_ : List[Any] = scope
def __UpperCAmelCase ( self ) -> Optional[Any]:
UpperCAmelCase_ : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
UpperCAmelCase_ : List[str] = None
if self.use_labels:
UpperCAmelCase_ : Dict = ids_tensor([self.batch_size] , self.num_labels )
UpperCAmelCase_ : Optional[Any] = self.get_config()
return config, pixel_values, labels
def __UpperCAmelCase ( self ) -> List[str]:
return ConvNextConfig(
num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=_UpperCamelCase , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , )
def __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Union[str, Any]:
UpperCAmelCase_ : Any = ConvNextModel(config=_UpperCamelCase )
model.to(_UpperCamelCase )
model.eval()
UpperCAmelCase_ : Optional[Any] = model(_UpperCamelCase )
# expected last hidden states: B, C, H // 32, W // 32
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , )
def __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> List[Any]:
UpperCAmelCase_ : List[str] = ConvNextForImageClassification(_UpperCamelCase )
model.to(_UpperCamelCase )
model.eval()
UpperCAmelCase_ : Any = model(_UpperCamelCase , labels=_UpperCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> List[Any]:
UpperCAmelCase_ : List[str] = ConvNextBackbone(config=_UpperCamelCase )
model.to(_UpperCamelCase )
model.eval()
UpperCAmelCase_ : int = model(_UpperCamelCase )
# verify hidden states
self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) )
self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] )
# verify channels
self.parent.assertEqual(len(model.channels ) , len(config.out_features ) )
self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] )
# verify backbone works with out_features=None
UpperCAmelCase_ : Optional[Any] = None
UpperCAmelCase_ : Tuple = ConvNextBackbone(config=_UpperCamelCase )
model.to(_UpperCamelCase )
model.eval()
UpperCAmelCase_ : Tuple = model(_UpperCamelCase )
# verify feature maps
self.parent.assertEqual(len(result.feature_maps ) , 1 )
self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] )
# verify channels
self.parent.assertEqual(len(model.channels ) , 1 )
self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] )
def __UpperCAmelCase ( self ) -> Dict:
UpperCAmelCase_ : List[Any] = self.prepare_config_and_inputs()
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = config_and_inputs
UpperCAmelCase_ : List[Any] = {'pixel_values': pixel_values}
return config, inputs_dict
@require_torch
class lowerCamelCase (_snake_case , _snake_case , unittest.TestCase ):
'''simple docstring'''
_snake_case : str = (
(
ConvNextModel,
ConvNextForImageClassification,
ConvNextBackbone,
)
if is_torch_available()
else ()
)
_snake_case : int = (
{'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification}
if is_torch_available()
else {}
)
_snake_case : Any = True
_snake_case : Optional[int] = False
_snake_case : Optional[int] = False
_snake_case : Union[str, Any] = False
_snake_case : List[str] = False
def __UpperCAmelCase ( self ) -> Tuple:
UpperCAmelCase_ : Dict = ConvNextModelTester(self )
UpperCAmelCase_ : Tuple = ConfigTester(self , config_class=_UpperCamelCase , has_text_modality=_UpperCamelCase , hidden_size=3_7 )
def __UpperCAmelCase ( self ) -> Tuple:
self.create_and_test_config_common_properties()
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def __UpperCAmelCase ( self ) -> List[str]:
return
@unittest.skip(reason='ConvNext does not use inputs_embeds' )
def __UpperCAmelCase ( self ) -> Tuple:
pass
@unittest.skip(reason='ConvNext does not support input and output embeddings' )
def __UpperCAmelCase ( self ) -> Optional[Any]:
pass
@unittest.skip(reason='ConvNext does not use feedforward chunking' )
def __UpperCAmelCase ( self ) -> Optional[Any]:
pass
def __UpperCAmelCase ( self ) -> List[Any]:
UpperCAmelCase_ , UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCAmelCase_ : Tuple = model_class(_UpperCamelCase )
UpperCAmelCase_ : int = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
UpperCAmelCase_ : str = [*signature.parameters.keys()]
UpperCAmelCase_ : List[str] = ['pixel_values']
self.assertListEqual(arg_names[:1] , _UpperCamelCase )
def __UpperCAmelCase ( self ) -> List[str]:
UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_UpperCamelCase )
def __UpperCAmelCase ( self ) -> List[Any]:
UpperCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_backbone(*_UpperCamelCase )
def __UpperCAmelCase ( self ) -> Optional[int]:
def check_hidden_states_output(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ):
UpperCAmelCase_ : List[str] = model_class(_UpperCamelCase )
model.to(_UpperCamelCase )
model.eval()
with torch.no_grad():
UpperCAmelCase_ : str = model(**self._prepare_for_class(_UpperCamelCase , _UpperCamelCase ) )
UpperCAmelCase_ : Dict = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
UpperCAmelCase_ : Dict = self.model_tester.num_stages
self.assertEqual(len(_UpperCamelCase ) , expected_num_stages + 1 )
# ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
self.assertListEqual(
list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , )
UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCAmelCase_ : List[Any] = True
check_hidden_states_output(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
UpperCAmelCase_ : int = True
check_hidden_states_output(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase )
def __UpperCAmelCase ( self ) -> Tuple:
UpperCAmelCase_ : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*_UpperCamelCase )
@slow
def __UpperCAmelCase ( self ) -> int:
for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
UpperCAmelCase_ : Any = ConvNextModel.from_pretrained(_UpperCamelCase )
self.assertIsNotNone(_UpperCamelCase )
def lowercase__ ( ):
'''simple docstring'''
UpperCAmelCase_ : Union[str, Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
return image
@require_torch
@require_vision
class lowerCamelCase (unittest.TestCase ):
'''simple docstring'''
@cached_property
def __UpperCAmelCase ( self ) -> int:
return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224' ) if is_vision_available() else None
@slow
def __UpperCAmelCase ( self ) -> List[str]:
UpperCAmelCase_ : Union[str, Any] = ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224' ).to(_UpperCamelCase )
UpperCAmelCase_ : Optional[Any] = self.default_image_processor
UpperCAmelCase_ : Union[str, Any] = prepare_img()
UpperCAmelCase_ : Tuple = image_processor(images=_UpperCamelCase , return_tensors='pt' ).to(_UpperCamelCase )
# forward pass
with torch.no_grad():
UpperCAmelCase_ : Any = model(**_UpperCamelCase )
# verify the logits
UpperCAmelCase_ : int = torch.Size((1, 1_0_0_0) )
self.assertEqual(outputs.logits.shape , _UpperCamelCase )
UpperCAmelCase_ : int = torch.tensor([-0.02_60, -0.47_39, 0.19_11] ).to(_UpperCamelCase )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , _UpperCamelCase , atol=1E-4 ) )
@require_torch
class lowerCamelCase (unittest.TestCase , _snake_case ):
'''simple docstring'''
_snake_case : Optional[int] = (ConvNextBackbone,) if is_torch_available() else ()
_snake_case : Union[str, Any] = ConvNextConfig
_snake_case : Tuple = False
def __UpperCAmelCase ( self ) -> Dict:
UpperCAmelCase_ : Union[str, Any] = ConvNextModelTester(self )
| 406 | 0 |
import math
import numpy as np
import qiskit
from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute
def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : int = 3 ) -> qiskit.result.counts.Counts:
"""simple docstring"""
if isinstance(__UpperCamelCase , __UpperCamelCase ):
raise TypeError("""number of qubits must be a integer.""" )
if number_of_qubits <= 0:
raise ValueError("""number of qubits must be > 0.""" )
if math.floor(__UpperCamelCase ) != number_of_qubits:
raise ValueError("""number of qubits must be exact integer.""" )
if number_of_qubits > 10:
raise ValueError("""number of qubits too large to simulate(>10).""" )
SCREAMING_SNAKE_CASE__ = QuantumRegister(__UpperCamelCase , """qr""" )
SCREAMING_SNAKE_CASE__ = ClassicalRegister(__UpperCamelCase , """cr""" )
SCREAMING_SNAKE_CASE__ = QuantumCircuit(__UpperCamelCase , __UpperCamelCase )
SCREAMING_SNAKE_CASE__ = number_of_qubits
for i in range(__UpperCamelCase ):
quantum_circuit.h(number_of_qubits - i - 1 )
counter -= 1
for j in range(__UpperCamelCase ):
quantum_circuit.cp(np.pi / 2 ** (counter - j) , __UpperCamelCase , __UpperCamelCase )
for k in range(number_of_qubits // 2 ):
quantum_circuit.swap(__UpperCamelCase , number_of_qubits - k - 1 )
# measure all the qubits
quantum_circuit.measure(__UpperCamelCase , __UpperCamelCase )
# simulate with 10000 shots
SCREAMING_SNAKE_CASE__ = Aer.get_backend("""qasm_simulator""" )
SCREAMING_SNAKE_CASE__ = execute(__UpperCamelCase , __UpperCamelCase , shots=1_00_00 )
return job.result().get_counts(__UpperCamelCase )
if __name__ == "__main__":
print(
F"""Total count for quantum fourier transform state is: \
{quantum_fourier_transform(3)}"""
)
| 703 | from math import isqrt
def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : int ) -> bool:
"""simple docstring"""
return all(number % divisor != 0 for divisor in range(2 , isqrt(__UpperCamelCase ) + 1 ) )
def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : int = 10**6 ) -> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = 0
SCREAMING_SNAKE_CASE__ = 1
SCREAMING_SNAKE_CASE__ = 7
while prime_candidate < max_prime:
primes_count += is_prime(__UpperCamelCase )
cube_index += 1
prime_candidate += 6 * cube_index
return primes_count
if __name__ == "__main__":
print(F"""{solution() = }""")
| 379 | 0 |
"""simple docstring"""
import importlib.util
import json
import os
import warnings
from dataclasses import dataclass, field
import torch
from ..training_args import TrainingArguments
from ..utils import cached_property, is_sagemaker_dp_enabled, logging
SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__)
def UpperCAmelCase__ ( ):
'''simple docstring'''
lowerCAmelCase = os.getenv("""SM_HP_MP_PARAMETERS""" , """{}""" )
try:
# Parse it and check the field "partitions" is included, it is required for model parallel.
lowerCAmelCase = json.loads(SCREAMING_SNAKE_CASE )
if "partitions" not in smp_options:
return False
except json.JSONDecodeError:
return False
# Get the sagemaker specific framework parameters from mpi_options variable.
lowerCAmelCase = os.getenv("""SM_FRAMEWORK_PARAMS""" , """{}""" )
try:
# Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
lowerCAmelCase = json.loads(SCREAMING_SNAKE_CASE )
if not mpi_options.get("""sagemaker_mpi_enabled""" , SCREAMING_SNAKE_CASE ):
return False
except json.JSONDecodeError:
return False
# Lastly, check if the `smdistributed` module is present.
return importlib.util.find_spec("""smdistributed""" ) is not None
if is_sagemaker_model_parallel_available():
import smdistributed.modelparallel.torch as smp
smp.init()
@dataclass
class lowercase ( _UpperCAmelCase ):
_SCREAMING_SNAKE_CASE = field(
default='' , metadata={'help': 'Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer'} , )
def _snake_case ( self ) -> Dict:
super().__post_init__()
warnings.warn(
"""`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use """
"""`TrainingArguments` instead.""" , lowercase__ , )
@cached_property
def _snake_case ( self ) -> "torch.device":
logger.info("""PyTorch: setting up devices""" )
if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1:
logger.warning(
"""torch.distributed process group is initialized, but local_rank == -1. """
"""In order to use Torch DDP, launch your script with `python -m torch.distributed.launch""" )
if self.no_cuda:
lowerCAmelCase = torch.device("""cpu""" )
lowerCAmelCase = 0
elif is_sagemaker_model_parallel_available():
lowerCAmelCase = smp.local_rank()
lowerCAmelCase = torch.device("""cuda""" , lowercase__ )
lowerCAmelCase = 1
elif is_sagemaker_dp_enabled():
import smdistributed.dataparallel.torch.torch_smddp # noqa: F401
torch.distributed.init_process_group(backend="""smddp""" , timeout=self.ddp_timeout_delta )
lowerCAmelCase = int(os.getenv("""SMDATAPARALLEL_LOCAL_RANK""" ) )
lowerCAmelCase = torch.device("""cuda""" , self.local_rank )
lowerCAmelCase = 1
elif self.local_rank == -1:
# if n_gpu is > 1 we'll use nn.DataParallel.
# If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
# Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will
# trigger an error that a device index is missing. Index 0 takes into account the
# GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0`
# will use the first GPU in that env, i.e. GPU#1
lowerCAmelCase = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" )
# Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at
# the default value.
lowerCAmelCase = torch.cuda.device_count()
else:
# Here, we'll use torch.distributed.
# Initializes the distributed backend which will take care of synchronizing nodes/GPUs
if not torch.distributed.is_initialized():
torch.distributed.init_process_group(backend="""nccl""" , timeout=self.ddp_timeout_delta )
lowerCAmelCase = torch.device("""cuda""" , self.local_rank )
lowerCAmelCase = 1
if device.type == "cuda":
torch.cuda.set_device(lowercase__ )
return device
@property
def _snake_case ( self ) -> Optional[int]:
if is_sagemaker_model_parallel_available():
return smp.dp_size()
return super().world_size
@property
def _snake_case ( self ) -> Optional[int]:
return not is_sagemaker_model_parallel_available()
@property
def _snake_case ( self ) -> List[Any]:
return False
| 532 | '''simple docstring'''
from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels
from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features
from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor
from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
| 435 | 0 |
import logging
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union
from filelock import FileLock
from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available
__magic_name__ : int = logging.getLogger(__name__)
@dataclass
class A__ :
'''simple docstring'''
snake_case__ = 42
snake_case__ = 42
snake_case__ = 42
@dataclass
class A__ :
'''simple docstring'''
snake_case__ = 42
snake_case__ = 42
snake_case__ = None
snake_case__ = None
class A__ ( __snake_case ):
'''simple docstring'''
snake_case__ = """train"""
snake_case__ = """dev"""
snake_case__ = """test"""
class A__ :
'''simple docstring'''
@staticmethod
def _SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Union[Split, str] ):
"""simple docstring"""
raise NotImplementedError
@staticmethod
def _SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
raise NotImplementedError
@staticmethod
def _SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE : List[InputExample] , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : PreTrainedTokenizer , _SCREAMING_SNAKE_CASE : int=False , _SCREAMING_SNAKE_CASE : int="[CLS]" , _SCREAMING_SNAKE_CASE : Any=1 , _SCREAMING_SNAKE_CASE : Dict="[SEP]" , _SCREAMING_SNAKE_CASE : Dict=False , _SCREAMING_SNAKE_CASE : Dict=False , _SCREAMING_SNAKE_CASE : Union[str, Any]=0 , _SCREAMING_SNAKE_CASE : List[Any]=0 , _SCREAMING_SNAKE_CASE : Any=-100 , _SCREAMING_SNAKE_CASE : Union[str, Any]=0 , _SCREAMING_SNAKE_CASE : str=True , ):
"""simple docstring"""
UpperCamelCase = {label: i for i, label in enumerate(_SCREAMING_SNAKE_CASE )}
UpperCamelCase = []
for ex_index, example in enumerate(_SCREAMING_SNAKE_CASE ):
if ex_index % 1_0000 == 0:
logger.info('Writing example %d of %d' , _SCREAMING_SNAKE_CASE , len(_SCREAMING_SNAKE_CASE ) )
UpperCamelCase = []
UpperCamelCase = []
for word, label in zip(example.words , example.labels ):
UpperCamelCase = tokenizer.tokenize(_SCREAMING_SNAKE_CASE )
# bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space.
if len(_SCREAMING_SNAKE_CASE ) > 0:
tokens.extend(_SCREAMING_SNAKE_CASE )
# Use the real label id for the first token of the word, and padding ids for the remaining tokens
label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(_SCREAMING_SNAKE_CASE ) - 1) )
# Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa.
UpperCamelCase = tokenizer.num_special_tokens_to_add()
if len(_SCREAMING_SNAKE_CASE ) > max_seq_length - special_tokens_count:
UpperCamelCase = tokens[: (max_seq_length - special_tokens_count)]
UpperCamelCase = label_ids[: (max_seq_length - special_tokens_count)]
# The convention in BERT is:
# (a) For sequence pairs:
# tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
# type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
# (b) For single sequences:
# tokens: [CLS] the dog is hairy . [SEP]
# type_ids: 0 0 0 0 0 0 0
#
# Where "type_ids" are used to indicate whether this is the first
# sequence or the second sequence. The embedding vectors for `type=0` and
# `type=1` were learned during pre-training and are added to the wordpiece
# embedding vector (and position vector). This is not *strictly* necessary
# since the [SEP] token unambiguously separates the sequences, but it makes
# it easier for the model to learn the concept of sequences.
#
# For classification tasks, the first vector (corresponding to [CLS]) is
# used as the "sentence vector". Note that this only makes sense because
# the entire model is fine-tuned.
tokens += [sep_token]
label_ids += [pad_token_label_id]
if sep_token_extra:
# roberta uses an extra separator b/w pairs of sentences
tokens += [sep_token]
label_ids += [pad_token_label_id]
UpperCamelCase = [sequence_a_segment_id] * len(_SCREAMING_SNAKE_CASE )
if cls_token_at_end:
tokens += [cls_token]
label_ids += [pad_token_label_id]
segment_ids += [cls_token_segment_id]
else:
UpperCamelCase = [cls_token] + tokens
UpperCamelCase = [pad_token_label_id] + label_ids
UpperCamelCase = [cls_token_segment_id] + segment_ids
UpperCamelCase = tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE )
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
UpperCamelCase = [1 if mask_padding_with_zero else 0] * len(_SCREAMING_SNAKE_CASE )
# Zero-pad up to the sequence length.
UpperCamelCase = max_seq_length - len(_SCREAMING_SNAKE_CASE )
if pad_on_left:
UpperCamelCase = ([pad_token] * padding_length) + input_ids
UpperCamelCase = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
UpperCamelCase = ([pad_token_segment_id] * padding_length) + segment_ids
UpperCamelCase = ([pad_token_label_id] * padding_length) + label_ids
else:
input_ids += [pad_token] * padding_length
input_mask += [0 if mask_padding_with_zero else 1] * padding_length
segment_ids += [pad_token_segment_id] * padding_length
label_ids += [pad_token_label_id] * padding_length
assert len(_SCREAMING_SNAKE_CASE ) == max_seq_length
assert len(_SCREAMING_SNAKE_CASE ) == max_seq_length
assert len(_SCREAMING_SNAKE_CASE ) == max_seq_length
assert len(_SCREAMING_SNAKE_CASE ) == max_seq_length
if ex_index < 5:
logger.info('*** Example ***' )
logger.info('guid: %s' , example.guid )
logger.info('tokens: %s' , ' '.join([str(_SCREAMING_SNAKE_CASE ) for x in tokens] ) )
logger.info('input_ids: %s' , ' '.join([str(_SCREAMING_SNAKE_CASE ) for x in input_ids] ) )
logger.info('input_mask: %s' , ' '.join([str(_SCREAMING_SNAKE_CASE ) for x in input_mask] ) )
logger.info('segment_ids: %s' , ' '.join([str(_SCREAMING_SNAKE_CASE ) for x in segment_ids] ) )
logger.info('label_ids: %s' , ' '.join([str(_SCREAMING_SNAKE_CASE ) for x in label_ids] ) )
if "token_type_ids" not in tokenizer.model_input_names:
UpperCamelCase = None
features.append(
InputFeatures(
input_ids=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , label_ids=_SCREAMING_SNAKE_CASE ) )
return features
if is_torch_available():
import torch
from torch import nn
from torch.utils.data import Dataset
class A__ ( __snake_case ):
'''simple docstring'''
snake_case__ = 42
snake_case__ = nn.CrossEntropyLoss().ignore_index
def __init__( self : Optional[Any] , _SCREAMING_SNAKE_CASE : TokenClassificationTask , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : PreTrainedTokenizer , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[int] = None , _SCREAMING_SNAKE_CASE : str=False , _SCREAMING_SNAKE_CASE : Split = Split.train , ):
"""simple docstring"""
UpperCamelCase = os.path.join(
_SCREAMING_SNAKE_CASE , 'cached_{}_{}_{}'.format(mode.value , tokenizer.__class__.__name__ , str(_SCREAMING_SNAKE_CASE ) ) , )
# Make sure only the first process in distributed training processes the dataset,
# and the others will use the cache.
UpperCamelCase = cached_features_file + '.lock'
with FileLock(_SCREAMING_SNAKE_CASE ):
if os.path.exists(_SCREAMING_SNAKE_CASE ) and not overwrite_cache:
logger.info(f'Loading features from cached file {cached_features_file}' )
UpperCamelCase = torch.load(_SCREAMING_SNAKE_CASE )
else:
logger.info(f'Creating features from dataset file at {data_dir}' )
UpperCamelCase = token_classification_task.read_examples_from_file(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# TODO clean up all this to leverage built-in features of tokenizers
UpperCamelCase = token_classification_task.convert_examples_to_features(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ['xlnet'] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['xlnet'] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=_SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == 'left' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , )
logger.info(f'Saving features into cached file {cached_features_file}' )
torch.save(self.features , _SCREAMING_SNAKE_CASE )
def __len__( self : int ):
"""simple docstring"""
return len(self.features )
def __getitem__( self : List[Any] , _SCREAMING_SNAKE_CASE : Any ):
"""simple docstring"""
return self.features[i]
if is_tf_available():
import tensorflow as tf
class A__ :
'''simple docstring'''
snake_case__ = 42
snake_case__ = -1_00
def __init__( self : List[Any] , _SCREAMING_SNAKE_CASE : TokenClassificationTask , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : PreTrainedTokenizer , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[int] = None , _SCREAMING_SNAKE_CASE : Dict=False , _SCREAMING_SNAKE_CASE : Split = Split.train , ):
"""simple docstring"""
UpperCamelCase = token_classification_task.read_examples_from_file(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# TODO clean up all this to leverage built-in features of tokenizers
UpperCamelCase = token_classification_task.convert_examples_to_features(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ['xlnet'] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['xlnet'] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=_SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == 'left' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , )
def gen():
for ex in self.features:
if ex.token_type_ids is None:
yield (
{"input_ids": ex.input_ids, "attention_mask": ex.attention_mask},
ex.label_ids,
)
else:
yield (
{
"input_ids": ex.input_ids,
"attention_mask": ex.attention_mask,
"token_type_ids": ex.token_type_ids,
},
ex.label_ids,
)
if "token_type_ids" not in tokenizer.model_input_names:
UpperCamelCase = tf.data.Dataset.from_generator(
_SCREAMING_SNAKE_CASE , ({'input_ids': tf.intaa, 'attention_mask': tf.intaa}, tf.intaa) , (
{'input_ids': tf.TensorShape([None] ), 'attention_mask': tf.TensorShape([None] )},
tf.TensorShape([None] ),
) , )
else:
UpperCamelCase = tf.data.Dataset.from_generator(
_SCREAMING_SNAKE_CASE , ({'input_ids': tf.intaa, 'attention_mask': tf.intaa, 'token_type_ids': tf.intaa}, tf.intaa) , (
{
'input_ids': tf.TensorShape([None] ),
'attention_mask': tf.TensorShape([None] ),
'token_type_ids': tf.TensorShape([None] ),
},
tf.TensorShape([None] ),
) , )
def _SCREAMING_SNAKE_CASE ( self : List[Any] ):
"""simple docstring"""
UpperCamelCase = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) )
return self.dataset
def __len__( self : List[Any] ):
"""simple docstring"""
return len(self.features )
def __getitem__( self : Union[str, Any] , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
return self.features[i]
| 410 |
import collections
from typing import List, Optional, Union
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging
from ..bert.tokenization_bert import BertTokenizer
__magic_name__ : Any = logging.get_logger(__name__)
__magic_name__ : str = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}
__magic_name__ : str = {
'''vocab_file''': {
'''facebook/dpr-ctx_encoder-single-nq-base''': (
'''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt'''
),
'''facebook/dpr-ctx_encoder-multiset-base''': (
'''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt'''
),
},
'''tokenizer_file''': {
'''facebook/dpr-ctx_encoder-single-nq-base''': (
'''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json'''
),
'''facebook/dpr-ctx_encoder-multiset-base''': (
'''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json'''
),
},
}
__magic_name__ : int = {
'''vocab_file''': {
'''facebook/dpr-question_encoder-single-nq-base''': (
'''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt'''
),
'''facebook/dpr-question_encoder-multiset-base''': (
'''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt'''
),
},
'''tokenizer_file''': {
'''facebook/dpr-question_encoder-single-nq-base''': (
'''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json'''
),
'''facebook/dpr-question_encoder-multiset-base''': (
'''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json'''
),
},
}
__magic_name__ : Union[str, Any] = {
'''vocab_file''': {
'''facebook/dpr-reader-single-nq-base''': (
'''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt'''
),
'''facebook/dpr-reader-multiset-base''': (
'''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt'''
),
},
'''tokenizer_file''': {
'''facebook/dpr-reader-single-nq-base''': (
'''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json'''
),
'''facebook/dpr-reader-multiset-base''': (
'''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json'''
),
},
}
__magic_name__ : Tuple = {
'''facebook/dpr-ctx_encoder-single-nq-base''': 512,
'''facebook/dpr-ctx_encoder-multiset-base''': 512,
}
__magic_name__ : List[str] = {
'''facebook/dpr-question_encoder-single-nq-base''': 512,
'''facebook/dpr-question_encoder-multiset-base''': 512,
}
__magic_name__ : str = {
'''facebook/dpr-reader-single-nq-base''': 512,
'''facebook/dpr-reader-multiset-base''': 512,
}
__magic_name__ : Any = {
'''facebook/dpr-ctx_encoder-single-nq-base''': {'''do_lower_case''': True},
'''facebook/dpr-ctx_encoder-multiset-base''': {'''do_lower_case''': True},
}
__magic_name__ : Optional[Any] = {
'''facebook/dpr-question_encoder-single-nq-base''': {'''do_lower_case''': True},
'''facebook/dpr-question_encoder-multiset-base''': {'''do_lower_case''': True},
}
__magic_name__ : Optional[Any] = {
'''facebook/dpr-reader-single-nq-base''': {'''do_lower_case''': True},
'''facebook/dpr-reader-multiset-base''': {'''do_lower_case''': True},
}
class A__ ( __snake_case ):
'''simple docstring'''
snake_case__ = VOCAB_FILES_NAMES
snake_case__ = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP
snake_case__ = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
snake_case__ = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION
class A__ ( __snake_case ):
'''simple docstring'''
snake_case__ = VOCAB_FILES_NAMES
snake_case__ = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP
snake_case__ = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
snake_case__ = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION
__magic_name__ : Tuple = collections.namedtuple(
'''DPRSpanPrediction''', ['''span_score''', '''relevance_score''', '''doc_id''', '''start_index''', '''end_index''', '''text''']
)
__magic_name__ : Optional[Any] = collections.namedtuple('''DPRReaderOutput''', ['''start_logits''', '''end_logits''', '''relevance_logits'''])
__magic_name__ : str = r'''
Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.
It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),
using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`
with the format:
```
[CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>
```
Args:
questions (`str` or `List[str]`):
The questions to be encoded. You can specify one question for many passages. In this case, the question
will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in
`titles` or `texts`.
titles (`str` or `List[str]`):
The passages titles to be encoded. This can be a string or a list of strings if there are several passages.
texts (`str` or `List[str]`):
The passages texts to be encoded. This can be a string or a list of strings if there are several passages.
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
Activates and controls padding. Accepts the following values:
- `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence
if provided).
- `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
acceptable input length for the model if that argument is not provided.
- `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different
lengths).
truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
Activates and controls truncation. Accepts the following values:
- `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to
the maximum acceptable input length for the model if that argument is not provided. This will truncate
token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch
of pairs) is provided.
- `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
acceptable input length for the model if that argument is not provided. This will only truncate the first
sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
- `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
acceptable input length for the model if that argument is not provided. This will only truncate the
second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
- `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths
greater than the model maximum admissible input size).
max_length (`int`, *optional*):
Controls the maximum length to use by one of the truncation/padding parameters.
If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
is required by one of the truncation/padding parameters. If the model has no specific maximum input
length (like XLNet) truncation/padding to a maximum length will be deactivated.
return_tensors (`str` or [`~utils.TensorType`], *optional*):
If set, will return tensors instead of list of python integers. Acceptable values are:
- `\'tf\'`: Return TensorFlow `tf.constant` objects.
- `\'pt\'`: Return PyTorch `torch.Tensor` objects.
- `\'np\'`: Return Numpy `np.ndarray` objects.
return_attention_mask (`bool`, *optional*):
Whether or not to return the attention mask. If not set, will return the attention mask according to the
specific tokenizer\'s default, defined by the `return_outputs` attribute.
[What are attention masks?](../glossary#attention-mask)
Returns:
`Dict[str, List[List[int]]]`: A dictionary with the following keys:
- `input_ids`: List of token ids to be fed to a model.
- `attention_mask`: List of indices specifying which tokens should be attended to by the model.
'''
@add_start_docstrings(__snake_case )
class A__ :
'''simple docstring'''
def __call__( self : Optional[int] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[str] = None , _SCREAMING_SNAKE_CASE : Optional[str] = None , _SCREAMING_SNAKE_CASE : Union[bool, str] = False , _SCREAMING_SNAKE_CASE : Union[bool, str] = False , _SCREAMING_SNAKE_CASE : Optional[int] = None , _SCREAMING_SNAKE_CASE : Optional[Union[str, TensorType]] = None , _SCREAMING_SNAKE_CASE : Optional[bool] = None , **_SCREAMING_SNAKE_CASE : Any , ):
"""simple docstring"""
if titles is None and texts is None:
return super().__call__(
_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , )
elif titles is None or texts is None:
UpperCamelCase = titles if texts is None else texts
return super().__call__(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , )
UpperCamelCase = titles if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else [titles]
UpperCamelCase = texts if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else [texts]
UpperCamelCase = len(_SCREAMING_SNAKE_CASE )
UpperCamelCase = questions if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else [questions] * n_passages
if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ):
raise ValueError(
f'There should be as many titles than texts but got {len(_SCREAMING_SNAKE_CASE )} titles and {len(_SCREAMING_SNAKE_CASE )} texts.' )
UpperCamelCase = super().__call__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE )['input_ids']
UpperCamelCase = super().__call__(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE )['input_ids']
UpperCamelCase = {
'input_ids': [
(encoded_question_and_title + encoded_text)[:max_length]
if max_length is not None and truncation
else encoded_question_and_title + encoded_text
for encoded_question_and_title, encoded_text in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
]
}
if return_attention_mask is not False:
UpperCamelCase = []
for input_ids in encoded_inputs["input_ids"]:
attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] )
UpperCamelCase = attention_mask
return self.pad(_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( self : List[str] , _SCREAMING_SNAKE_CASE : BatchEncoding , _SCREAMING_SNAKE_CASE : DPRReaderOutput , _SCREAMING_SNAKE_CASE : int = 16 , _SCREAMING_SNAKE_CASE : int = 64 , _SCREAMING_SNAKE_CASE : int = 4 , ):
"""simple docstring"""
UpperCamelCase = reader_input['input_ids']
UpperCamelCase , UpperCamelCase , UpperCamelCase = reader_output[:3]
UpperCamelCase = len(_SCREAMING_SNAKE_CASE )
UpperCamelCase = sorted(range(_SCREAMING_SNAKE_CASE ) , reverse=_SCREAMING_SNAKE_CASE , key=relevance_logits.__getitem__ )
UpperCamelCase = []
for doc_id in sorted_docs:
UpperCamelCase = list(input_ids[doc_id] )
# assuming question & title information is at the beginning of the sequence
UpperCamelCase = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id
if sequence_ids[-1] == self.pad_token_id:
UpperCamelCase = sequence_ids.index(self.pad_token_id )
else:
UpperCamelCase = len(_SCREAMING_SNAKE_CASE )
UpperCamelCase = self._get_best_spans(
start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=_SCREAMING_SNAKE_CASE , top_spans=_SCREAMING_SNAKE_CASE , )
for start_index, end_index in best_spans:
start_index += passage_offset
end_index += passage_offset
nbest_spans_predictions.append(
DPRSpanPrediction(
span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=_SCREAMING_SNAKE_CASE , start_index=_SCREAMING_SNAKE_CASE , end_index=_SCREAMING_SNAKE_CASE , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) )
if len(_SCREAMING_SNAKE_CASE ) >= num_spans:
break
return nbest_spans_predictions[:num_spans]
def _SCREAMING_SNAKE_CASE ( self : List[Any] , _SCREAMING_SNAKE_CASE : List[int] , _SCREAMING_SNAKE_CASE : List[int] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , ):
"""simple docstring"""
UpperCamelCase = []
for start_index, start_score in enumerate(_SCREAMING_SNAKE_CASE ):
for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ):
scores.append(((start_index, start_index + answer_length), start_score + end_score) )
UpperCamelCase = sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x[1] , reverse=_SCREAMING_SNAKE_CASE )
UpperCamelCase = []
for (start_index, end_index), score in scores:
if start_index > end_index:
raise ValueError(f'Wrong span indices: [{start_index}:{end_index}]' )
UpperCamelCase = end_index - start_index + 1
if length > max_answer_length:
raise ValueError(f'Span is too long: {length} > {max_answer_length}' )
if any(
start_index <= prev_start_index <= prev_end_index <= end_index
or prev_start_index <= start_index <= end_index <= prev_end_index
for (prev_start_index, prev_end_index) in chosen_span_intervals ):
continue
chosen_span_intervals.append((start_index, end_index) )
if len(_SCREAMING_SNAKE_CASE ) == top_spans:
break
return chosen_span_intervals
@add_end_docstrings(__snake_case )
class A__ ( __snake_case , __snake_case ):
'''simple docstring'''
snake_case__ = VOCAB_FILES_NAMES
snake_case__ = READER_PRETRAINED_VOCAB_FILES_MAP
snake_case__ = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
snake_case__ = READER_PRETRAINED_INIT_CONFIGURATION
snake_case__ = ["""input_ids""", """attention_mask"""]
| 410 | 1 |
__a : Optional[int] = {"""a""": ["""c""", """b"""], """b""": ["""d""", """e"""], """c""": [], """d""": [], """e""": []}
__a : int = ["""a""", """b""", """c""", """d""", """e"""]
def __magic_name__ ( lowercase_ , lowercase_ , lowercase_ ) -> List[str]:
'''simple docstring'''
UpperCamelCase = start
# add current to visited
visited.append(lowercase_ )
UpperCamelCase = edges[current]
for neighbor in neighbors:
# if neighbor not in visited, visit
if neighbor not in visited:
UpperCamelCase = topological_sort(lowercase_ , lowercase_ , lowercase_ )
# if all neighbors visited add current to sort
sort.append(lowercase_ )
# if all vertices haven't been visited select a new one to visit
if len(lowercase_ ) != len(lowercase_ ):
for vertice in vertices:
if vertice not in visited:
UpperCamelCase = topological_sort(lowercase_ , lowercase_ , lowercase_ )
# return sort
return sort
if __name__ == "__main__":
__a : str = topological_sort("""a""", [], [])
print(sort)
| 606 |
import unittest
import numpy as np
from transformers import RobertaConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
if is_flax_available():
from transformers.models.roberta.modeling_flax_roberta import (
FlaxRobertaForCausalLM,
FlaxRobertaForMaskedLM,
FlaxRobertaForMultipleChoice,
FlaxRobertaForQuestionAnswering,
FlaxRobertaForSequenceClassification,
FlaxRobertaForTokenClassification,
FlaxRobertaModel,
)
class __UpperCAmelCase ( unittest.TestCase ):
"""simple docstring"""
def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=7 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=99 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=5 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=37 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=4 , ) -> str:
"""simple docstring"""
UpperCamelCase = parent
UpperCamelCase = batch_size
UpperCamelCase = seq_length
UpperCamelCase = is_training
UpperCamelCase = use_attention_mask
UpperCamelCase = use_token_type_ids
UpperCamelCase = use_labels
UpperCamelCase = vocab_size
UpperCamelCase = hidden_size
UpperCamelCase = num_hidden_layers
UpperCamelCase = num_attention_heads
UpperCamelCase = intermediate_size
UpperCamelCase = hidden_act
UpperCamelCase = hidden_dropout_prob
UpperCamelCase = attention_probs_dropout_prob
UpperCamelCase = max_position_embeddings
UpperCamelCase = type_vocab_size
UpperCamelCase = type_sequence_label_size
UpperCamelCase = initializer_range
UpperCamelCase = num_choices
def __lowerCAmelCase ( self ) -> Optional[Any]:
"""simple docstring"""
UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
UpperCamelCase = None
if self.use_attention_mask:
UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] )
UpperCamelCase = None
if self.use_token_type_ids:
UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
UpperCamelCase = RobertaConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , )
return config, input_ids, token_type_ids, attention_mask
def __lowerCAmelCase ( self ) -> Optional[int]:
"""simple docstring"""
UpperCamelCase = self.prepare_config_and_inputs()
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = config_and_inputs
UpperCamelCase = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask}
return config, inputs_dict
def __lowerCAmelCase ( self ) -> Union[str, Any]:
"""simple docstring"""
UpperCamelCase = self.prepare_config_and_inputs()
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = config_and_inputs
UpperCamelCase = True
UpperCamelCase = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] )
UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 )
return (
config,
input_ids,
token_type_ids,
encoder_hidden_states,
encoder_attention_mask,
)
@require_flax
class __UpperCAmelCase ( snake_case__ , unittest.TestCase ):
"""simple docstring"""
lowercase = True
lowercase = (
(
FlaxRobertaModel,
FlaxRobertaForCausalLM,
FlaxRobertaForMaskedLM,
FlaxRobertaForSequenceClassification,
FlaxRobertaForTokenClassification,
FlaxRobertaForMultipleChoice,
FlaxRobertaForQuestionAnswering,
)
if is_flax_available()
else ()
)
def __lowerCAmelCase ( self ) -> Union[str, Any]:
"""simple docstring"""
UpperCamelCase = FlaxRobertaModelTester(self )
@slow
def __lowerCAmelCase ( self ) -> Dict:
"""simple docstring"""
for model_class_name in self.all_model_classes:
UpperCamelCase = model_class_name.from_pretrained("roberta-base" , from_pt=SCREAMING_SNAKE_CASE )
UpperCamelCase = model(np.ones((1, 1) ) )
self.assertIsNotNone(SCREAMING_SNAKE_CASE )
| 606 | 1 |
import functools
def lowerCamelCase__ ( _lowercase , _lowercase ):
'''simple docstring'''
UpperCAmelCase_ : List[str] = len(_lowercase )
UpperCAmelCase_ : int = len(_lowercase )
@functools.cache
def min_distance(_lowercase , _lowercase ) -> int:
# if first word index is overflow - delete all from the second word
if indexa >= len_worda:
return len_worda - indexa
# if second word index is overflow - delete all from the first word
if indexa >= len_worda:
return len_worda - indexa
UpperCAmelCase_ : Union[str, Any] = int(worda[indexa] != worda[indexa] ) # current letters not identical
return min(
1 + min_distance(indexa + 1 , _lowercase ) , 1 + min_distance(_lowercase , indexa + 1 ) , diff + min_distance(indexa + 1 , indexa + 1 ) , )
return min_distance(0 , 0 )
if __name__ == "__main__":
import doctest
doctest.testmod() | 300 |
import tempfile
import unittest
from transformers import AutoModelForSeqaSeqLM, AutoTokenizer
from transformers.testing_utils import (
is_torch_available,
require_optimum,
require_torch,
slow,
)
if is_torch_available():
import torch
@require_torch
@require_optimum
@slow
class __a( unittest.TestCase ):
"""simple docstring"""
def a__ ( self ) -> Union[str, Any]:
UpperCAmelCase_ : Optional[int] = '''hf-internal-testing/tiny-random-t5'''
UpperCAmelCase_ : Dict = AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : str = tokenizer('''This is me''' ,return_tensors='''pt''' )
UpperCAmelCase_ : int = model.to_bettertransformer()
self.assertTrue(any('''BetterTransformer''' in mod.__class__.__name__ for _, mod in model.named_modules() ) )
UpperCAmelCase_ : List[str] = model.generate(**_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : str = model.reverse_bettertransformer()
self.assertFalse(any('''BetterTransformer''' in mod.__class__.__name__ for _, mod in model.named_modules() ) )
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Dict = AutoModelForSeqaSeqLM.from_pretrained(_SCREAMING_SNAKE_CASE )
self.assertFalse(
any('''BetterTransformer''' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) )
UpperCAmelCase_ : Optional[Any] = model_reloaded.generate(**_SCREAMING_SNAKE_CASE )
self.assertTrue(torch.allclose(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) )
def a__ ( self ) -> Optional[int]:
UpperCAmelCase_ : Dict = '''hf-internal-testing/tiny-random-t5'''
UpperCAmelCase_ : Any = AutoModelForSeqaSeqLM.from_pretrained(_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : List[str] = model.to_bettertransformer()
with tempfile.TemporaryDirectory() as tmpdirname:
with self.assertRaises(_SCREAMING_SNAKE_CASE ):
model.save_pretrained(_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Tuple = model.reverse_bettertransformer()
model.save_pretrained(_SCREAMING_SNAKE_CASE ) | 300 | 1 |
"""simple docstring"""
from collections.abc import Callable
import numpy as np
def _snake_case ( _snake_case : Any , _snake_case : Dict , _snake_case : Any , _snake_case : int , _snake_case : List[str] ) -> np.ndarray:
'''simple docstring'''
_A = int(np.ceil((x_end - xa) / step_size ) )
_A = np.zeros((n + 1,) )
_A = ya
_A = xa
for k in range(_snake_case ):
_A = y[k] + step_size * ode_func(_snake_case , y[k] )
x += step_size
return y
if __name__ == "__main__":
import doctest
doctest.testmod()
| 7 |
import argparse
from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline
if __name__ == "__main__":
lowerCamelCase_ : int = argparse.ArgumentParser()
parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the output model.""")
parser.add_argument(
"""--txt2img_unclip""",
default="""kakaobrain/karlo-v1-alpha""",
type=str,
required=False,
help="""The pretrained txt2img unclip.""",
)
lowerCamelCase_ : Dict = parser.parse_args()
lowerCamelCase_ : str = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip)
lowerCamelCase_ : int = CLIPImageProcessor()
lowerCamelCase_ : Any = CLIPVisionModelWithProjection.from_pretrained("""openai/clip-vit-large-patch14""")
lowerCamelCase_ : Union[str, Any] = UnCLIPImageVariationPipeline(
decoder=txtaimg.decoder,
text_encoder=txtaimg.text_encoder,
tokenizer=txtaimg.tokenizer,
text_proj=txtaimg.text_proj,
feature_extractor=feature_extractor,
image_encoder=image_encoder,
super_res_first=txtaimg.super_res_first,
super_res_last=txtaimg.super_res_last,
decoder_scheduler=txtaimg.decoder_scheduler,
super_res_scheduler=txtaimg.super_res_scheduler,
)
imgaimg.save_pretrained(args.dump_path)
| 548 | 0 |
import re
from pathlib import Path
from unittest import TestCase
import pytest
@pytest.mark.integration
class SCREAMING_SNAKE_CASE ( UpperCamelCase__ ):
"""simple docstring"""
def __lowerCAmelCase ( self , __UpperCamelCase ):
"""simple docstring"""
with open(__A , encoding='utf-8' ) as input_file:
snake_case_ = re.compile(r'(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)' )
snake_case_ = input_file.read()
snake_case_ = regexp.search(__A )
return match
def __lowerCAmelCase ( self , __UpperCamelCase ):
"""simple docstring"""
with open(__A , encoding='utf-8' ) as input_file:
snake_case_ = re.compile(r'#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()' , re.DOTALL )
snake_case_ = input_file.read()
# use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search`
snake_case_ = regexp.finditer(__A )
snake_case_ = [match for match in matches if match is not None and match.group(1 ) is not None]
return matches[0] if matches else None
def __lowerCAmelCase ( self ):
"""simple docstring"""
snake_case_ = Path('./datasets' )
snake_case_ = list(dataset_paths.absolute().glob('**/*.py' ) )
for dataset in dataset_files:
if self._no_encoding_on_file_open(str(__A ) ):
raise AssertionError(f"""open(...) must use utf-8 encoding in {dataset}""" )
def __lowerCAmelCase ( self ):
"""simple docstring"""
snake_case_ = Path('./datasets' )
snake_case_ = list(dataset_paths.absolute().glob('**/*.py' ) )
for dataset in dataset_files:
if self._no_print_statements(str(__A ) ):
raise AssertionError(f"""print statement found in {dataset}. Use datasets.logger/logging instead.""" )
| 714 |
from __future__ import annotations
import unittest
from transformers import LEDConfig, 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 TFLEDForConditionalGeneration, TFLEDModel
@require_tf
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
__A = LEDConfig
__A = {}
__A = """gelu"""
def __init__( self , __UpperCamelCase , __UpperCamelCase=13 , __UpperCamelCase=7 , __UpperCamelCase=True , __UpperCamelCase=False , __UpperCamelCase=99 , __UpperCamelCase=32 , __UpperCamelCase=2 , __UpperCamelCase=4 , __UpperCamelCase=37 , __UpperCamelCase=0.1 , __UpperCamelCase=0.1 , __UpperCamelCase=20 , __UpperCamelCase=2 , __UpperCamelCase=1 , __UpperCamelCase=0 , __UpperCamelCase=4 , ):
"""simple docstring"""
snake_case_ = parent
snake_case_ = batch_size
snake_case_ = seq_length
snake_case_ = is_training
snake_case_ = use_labels
snake_case_ = vocab_size
snake_case_ = hidden_size
snake_case_ = num_hidden_layers
snake_case_ = num_attention_heads
snake_case_ = intermediate_size
snake_case_ = hidden_dropout_prob
snake_case_ = attention_probs_dropout_prob
snake_case_ = max_position_embeddings
snake_case_ = eos_token_id
snake_case_ = pad_token_id
snake_case_ = bos_token_id
snake_case_ = attention_window
# `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size
# [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention
# returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1]
# because its local attention only attends to `self.attention_window` and one before and one after
snake_case_ = self.attention_window + 2
# because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for
# the `test_attention_outputs` and `test_hidden_states_output` tests
snake_case_ = (
self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window
)
def __lowerCAmelCase ( self ):
"""simple docstring"""
snake_case_ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size )
snake_case_ = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 )
snake_case_ = tf.concat([input_ids, eos_tensor] , axis=1 )
snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
snake_case_ = self.config_cls(
vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , )
snake_case_ = prepare_led_inputs_dict(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
snake_case_ = tf.concat(
[tf.zeros_like(__UpperCamelCase )[:, :-1], tf.ones_like(__UpperCamelCase )[:, -1:]] , axis=-1 , )
snake_case_ = global_attention_mask
return config, inputs_dict
def __lowerCAmelCase ( self , __UpperCamelCase , __UpperCamelCase ):
"""simple docstring"""
snake_case_ = TFLEDModel(config=__UpperCamelCase ).get_decoder()
snake_case_ = inputs_dict['input_ids']
snake_case_ = input_ids[:1, :]
snake_case_ = inputs_dict['attention_mask'][:1, :]
snake_case_ = 1
# first forward pass
snake_case_ = model(__UpperCamelCase , attention_mask=__UpperCamelCase , use_cache=__UpperCamelCase )
snake_case_ , snake_case_ = outputs.to_tuple()
# create hypothetical next token and extent to next_input_ids
snake_case_ = ids_tensor((self.batch_size, 3) , config.vocab_size )
snake_case_ = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta )
# append to next input_ids and
snake_case_ = tf.concat([input_ids, next_tokens] , axis=-1 )
snake_case_ = tf.concat([attention_mask, next_attn_mask] , axis=-1 )
snake_case_ = model(__UpperCamelCase , attention_mask=__UpperCamelCase )[0]
snake_case_ = model(__UpperCamelCase , attention_mask=__UpperCamelCase , past_key_values=__UpperCamelCase )[0]
self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] )
# select random slice
snake_case_ = int(ids_tensor((1,) , output_from_past.shape[-1] ) )
snake_case_ = output_from_no_past[:, -3:, random_slice_idx]
snake_case_ = output_from_past[:, :, random_slice_idx]
# test that outputs are equal for slice
tf.debugging.assert_near(__UpperCamelCase , __UpperCamelCase , rtol=1E-3 )
def a(lowercase__ , lowercase__ , lowercase__ , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__=None , ):
'''simple docstring'''
if attention_mask is None:
snake_case_ = tf.cast(tf.math.not_equal(lowercase__ , config.pad_token_id ) , tf.inta )
if decoder_attention_mask is None:
snake_case_ = tf.concat(
[
tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ),
tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ),
] , axis=-1 , )
if head_mask is None:
snake_case_ = tf.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
snake_case_ = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
return {
"input_ids": input_ids,
"attention_mask": attention_mask,
"decoder_input_ids": decoder_input_ids,
"decoder_attention_mask": decoder_attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
}
@require_tf
class SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , unittest.TestCase ):
"""simple docstring"""
__A = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else ()
__A = (TFLEDForConditionalGeneration,) if is_tf_available() else ()
__A = (
{
"""conversational""": TFLEDForConditionalGeneration,
"""feature-extraction""": TFLEDModel,
"""summarization""": TFLEDForConditionalGeneration,
"""text2text-generation""": TFLEDForConditionalGeneration,
"""translation""": TFLEDForConditionalGeneration,
}
if is_tf_available()
else {}
)
__A = True
__A = False
__A = False
__A = False
def __lowerCAmelCase ( self ):
"""simple docstring"""
snake_case_ = TFLEDModelTester(self )
snake_case_ = ConfigTester(self , config_class=__UpperCamelCase )
def __lowerCAmelCase ( self ):
"""simple docstring"""
self.config_tester.run_common_tests()
def __lowerCAmelCase ( self ):
"""simple docstring"""
snake_case_ = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*__UpperCamelCase )
def __lowerCAmelCase ( self ):
"""simple docstring"""
snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common()
snake_case_ = tf.zeros_like(inputs_dict['attention_mask'] )
snake_case_ = 2
snake_case_ = tf.where(
tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict['global_attention_mask'] , )
snake_case_ = True
snake_case_ = self.model_tester.seq_length
snake_case_ = self.model_tester.encoder_seq_length
def check_decoder_attentions_output(__UpperCamelCase ):
snake_case_ = outputs.decoder_attentions
self.assertEqual(len(__UpperCamelCase ) , self.model_tester.num_hidden_layers )
self.assertListEqual(
list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , )
def check_encoder_attentions_output(__UpperCamelCase ):
snake_case_ = [t.numpy() for t in outputs.encoder_attentions]
snake_case_ = [t.numpy() for t in outputs.encoder_global_attentions]
self.assertEqual(len(__UpperCamelCase ) , self.model_tester.num_hidden_layers )
self.assertEqual(len(__UpperCamelCase ) , self.model_tester.num_hidden_layers )
self.assertListEqual(
list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , )
self.assertListEqual(
list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , )
for model_class in self.all_model_classes:
snake_case_ = True
snake_case_ = False
snake_case_ = False
snake_case_ = model_class(__UpperCamelCase )
snake_case_ = model(self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) )
snake_case_ = len(__UpperCamelCase )
self.assertEqual(config.output_hidden_states , __UpperCamelCase )
check_encoder_attentions_output(__UpperCamelCase )
if self.is_encoder_decoder:
snake_case_ = model_class(__UpperCamelCase )
snake_case_ = model(self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) )
self.assertEqual(config.output_hidden_states , __UpperCamelCase )
check_decoder_attentions_output(__UpperCamelCase )
# Check that output attentions can also be changed via the config
del inputs_dict["output_attentions"]
snake_case_ = True
snake_case_ = model_class(__UpperCamelCase )
snake_case_ = model(self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) )
self.assertEqual(config.output_hidden_states , __UpperCamelCase )
check_encoder_attentions_output(__UpperCamelCase )
# Check attention is always last and order is fine
snake_case_ = True
snake_case_ = True
snake_case_ = model_class(__UpperCamelCase )
snake_case_ = model(self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) )
self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(__UpperCamelCase ) )
self.assertEqual(model.config.output_hidden_states , __UpperCamelCase )
check_encoder_attentions_output(__UpperCamelCase )
@unittest.skip('LED keeps using potentially symbolic tensors in conditionals and breaks tracing.' )
def __lowerCAmelCase ( self ):
"""simple docstring"""
pass
def __lowerCAmelCase ( self ):
"""simple docstring"""
pass
def a(lowercase__ ):
'''simple docstring'''
return tf.constant(lowercase__ , dtype=tf.intaa )
A = 1e-4
@slow
@require_tf
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __lowerCAmelCase ( self ):
"""simple docstring"""
snake_case_ = TFLEDForConditionalGeneration.from_pretrained('allenai/led-base-16384' ).led
# change to intended input here
snake_case_ = _long_tensor([5_12 * [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69]] )
snake_case_ = _long_tensor([1_28 * [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69]] )
snake_case_ = prepare_led_inputs_dict(model.config , __UpperCamelCase , __UpperCamelCase )
snake_case_ = model(**__UpperCamelCase )[0]
snake_case_ = (1, 10_24, 7_68)
self.assertEqual(output.shape , __UpperCamelCase )
# change to expected output here
snake_case_ = tf.convert_to_tensor(
[[2.3050, 2.8279, 0.6531], [-1.8457, -0.1455, -3.5661], [-1.0186, 0.4586, -2.2043]] , )
tf.debugging.assert_near(output[:, :3, :3] , __UpperCamelCase , atol=1E-3 )
def __lowerCAmelCase ( self ):
"""simple docstring"""
snake_case_ = TFLEDForConditionalGeneration.from_pretrained('allenai/led-base-16384' )
# change to intended input here
snake_case_ = _long_tensor([5_12 * [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69]] )
snake_case_ = _long_tensor([1_28 * [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69]] )
snake_case_ = prepare_led_inputs_dict(model.config , __UpperCamelCase , __UpperCamelCase )
snake_case_ = model(**__UpperCamelCase )[0]
snake_case_ = (1, 10_24, model.config.vocab_size)
self.assertEqual(output.shape , __UpperCamelCase )
# change to expected output here
snake_case_ = tf.convert_to_tensor(
[[33.6507, 6.4572, 16.8089], [5.8739, -2.4238, 11.2902], [-3.2139, -4.3149, 4.2783]] , )
tf.debugging.assert_near(output[:, :3, :3] , __UpperCamelCase , atol=1E-3 , rtol=1E-3 )
| 46 | 0 |
'''simple docstring'''
import sys
import webbrowser
import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent
if __name__ == "__main__":
print('''Googling.....''')
lowerCAmelCase__ = '''https://www.google.com/search?q=''' + ''' '''.join(sys.argv[1:])
lowerCAmelCase__ = requests.get(url, headers={'''UserAgent''': UserAgent().random})
# res.raise_for_status()
with open('''project1a.html''', '''wb''') as out_file: # only for knowing the class
for data in res.iter_content(1_0000):
out_file.write(data)
lowerCAmelCase__ = BeautifulSoup(res.text, '''html.parser''')
lowerCAmelCase__ = list(soup.select('''.eZt8xd'''))[:5]
print(len(links))
for link in links:
if link.text == "Maps":
webbrowser.open(link.get('''href'''))
else:
webbrowser.open(f'https://google.com{link.get("href")}')
| 41 |
"""simple docstring"""
import numpy as np
from PIL import Image
def _lowerCAmelCase(a : np.ndarray , a : int , a : int ) -> np.ndarray:
_SCREAMING_SNAKE_CASE =np.array(a )
if arr.shape[0] != arr.shape[1]:
raise ValueError('''The input array is not a square matrix''' )
_SCREAMING_SNAKE_CASE =0
_SCREAMING_SNAKE_CASE =0
_SCREAMING_SNAKE_CASE =0
_SCREAMING_SNAKE_CASE =0
# compute the shape of the output matrix
_SCREAMING_SNAKE_CASE =(arr.shape[0] - size) // stride + 1
# initialize the output matrix with zeros of shape maxpool_shape
_SCREAMING_SNAKE_CASE =np.zeros((maxpool_shape, maxpool_shape) )
while i < arr.shape[0]:
if i + size > arr.shape[0]:
# if the end of the matrix is reached, break
break
while j < arr.shape[1]:
# if the end of the matrix is reached, break
if j + size > arr.shape[1]:
break
# compute the maximum of the pooling matrix
_SCREAMING_SNAKE_CASE =np.max(arr[i : i + size, j : j + size] )
# shift the pooling matrix by stride of column pixels
j += stride
mat_j += 1
# shift the pooling matrix by stride of row pixels
i += stride
mat_i += 1
# reset the column index to 0
_SCREAMING_SNAKE_CASE =0
_SCREAMING_SNAKE_CASE =0
return updated_arr
def _lowerCAmelCase(a : np.ndarray , a : int , a : int ) -> np.ndarray:
_SCREAMING_SNAKE_CASE =np.array(a )
if arr.shape[0] != arr.shape[1]:
raise ValueError('''The input array is not a square matrix''' )
_SCREAMING_SNAKE_CASE =0
_SCREAMING_SNAKE_CASE =0
_SCREAMING_SNAKE_CASE =0
_SCREAMING_SNAKE_CASE =0
# compute the shape of the output matrix
_SCREAMING_SNAKE_CASE =(arr.shape[0] - size) // stride + 1
# initialize the output matrix with zeros of shape avgpool_shape
_SCREAMING_SNAKE_CASE =np.zeros((avgpool_shape, avgpool_shape) )
while i < arr.shape[0]:
# if the end of the matrix is reached, break
if i + size > arr.shape[0]:
break
while j < arr.shape[1]:
# if the end of the matrix is reached, break
if j + size > arr.shape[1]:
break
# compute the average of the pooling matrix
_SCREAMING_SNAKE_CASE =int(np.average(arr[i : i + size, j : j + size] ) )
# shift the pooling matrix by stride of column pixels
j += stride
mat_j += 1
# shift the pooling matrix by stride of row pixels
i += stride
mat_i += 1
# reset the column index to 0
_SCREAMING_SNAKE_CASE =0
_SCREAMING_SNAKE_CASE =0
return updated_arr
# Main Function
if __name__ == "__main__":
from doctest import testmod
testmod(name='''avgpooling''', verbose=True)
# Loading the image
UpperCAmelCase_ : List[str] = Image.open('''path_to_image''')
# Converting the image to numpy array and maxpooling, displaying the result
# Ensure that the image is a square matrix
Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show()
# Converting the image to numpy array and averagepooling, displaying the result
# Ensure that the image is a square matrix
Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
| 255 | 0 |
# 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.whisper import WhisperForConditionalGeneration, WhisperProcessor
from .base import PipelineTool
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """openai/whisper-base"""
a__ = (
"""This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the """
"""transcribed text."""
)
a__ = """transcriber"""
a__ = WhisperProcessor
a__ = WhisperForConditionalGeneration
a__ = ["""audio"""]
a__ = ["""text"""]
def _lowercase ( self : int , UpperCamelCase__ : Optional[int] ) -> Any:
"""simple docstring"""
return self.pre_processor(UpperCamelCase__ , return_tensors="""pt""" ).input_features
def _lowercase ( self : Dict , UpperCamelCase__ : int ) -> Union[str, Any]:
"""simple docstring"""
return self.model.generate(inputs=UpperCamelCase__ )
def _lowercase ( self : List[str] , UpperCamelCase__ : Union[str, Any] ) -> Optional[int]:
"""simple docstring"""
return self.pre_processor.batch_decode(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ )[0]
| 76 |
import json
import os
import tempfile
from transformers.testing_utils import check_json_file_has_correct_format
class UpperCAmelCase_ :
'''simple docstring'''
a__ = None
def _lowercase ( self : Optional[int] ) -> str:
"""simple docstring"""
__magic_name__ = self.feature_extraction_class(**self.feat_extract_dict )
__magic_name__ = json.loads(feat_extract.to_json_string() )
for key, value in self.feat_extract_dict.items():
self.assertEqual(obj[key] , UpperCamelCase__ )
def _lowercase ( self : Union[str, Any] ) -> str:
"""simple docstring"""
__magic_name__ = self.feature_extraction_class(**self.feat_extract_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
__magic_name__ = os.path.join(UpperCamelCase__ , """feat_extract.json""" )
feat_extract_first.to_json_file(UpperCamelCase__ )
__magic_name__ = self.feature_extraction_class.from_json_file(UpperCamelCase__ )
self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() )
def _lowercase ( self : str ) -> str:
"""simple docstring"""
__magic_name__ = self.feature_extraction_class(**self.feat_extract_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
__magic_name__ = feat_extract_first.save_pretrained(UpperCamelCase__ )[0]
check_json_file_has_correct_format(UpperCamelCase__ )
__magic_name__ = self.feature_extraction_class.from_pretrained(UpperCamelCase__ )
self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() )
def _lowercase ( self : Optional[int] ) -> Tuple:
"""simple docstring"""
__magic_name__ = self.feature_extraction_class()
self.assertIsNotNone(UpperCamelCase__ )
| 76 | 1 |
'''simple docstring'''
import json
import os
import unittest
from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import (
VOCAB_FILES_NAMES,
GPTSanJapaneseTokenizer,
)
from transformers.testing_utils import require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class A ( __UpperCAmelCase , unittest.TestCase ):
lowerCamelCase : int = GPTSanJapaneseTokenizer
lowerCamelCase : List[str] = False
lowerCamelCase : List[Any] = {"""do_clean_text""": False, """add_prefix_space""": False}
def A__ ( self ) -> Tuple:
'''simple docstring'''
super().setUp()
# fmt: off
lowercase__ = ["""こん""", """こんに""", """にちは""", """ばんは""", """世界,㔺界""", """、""", """。""", """<BR>""", """<SP>""", """<TAB>""", """<URL>""", """<EMAIL>""", """<TEL>""", """<DATE>""", """<PRICE>""", """<BLOCK>""", """<KIGOU>""", """<U2000U2BFF>""", """<|emoji1|>""", """<unk>""", """<|bagoftoken|>""", """<|endoftext|>"""]
# fmt: on
lowercase__ = {"""emoji""": {"""\ud83d\ude00""": """<|emoji1|>"""}, """emoji_inv""": {"""<|emoji1|>""": """\ud83d\ude00"""}} # 😀
lowercase__ = {"""unk_token""": """<unk>"""}
lowercase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] )
lowercase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""emoji_file"""] )
with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer:
vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) )
with open(self.emoji_file , """w""" ) as emoji_writer:
emoji_writer.write(json.dumps(lowerCamelCase__ ) )
def A__ ( self , **lowerCamelCase__ ) -> Optional[int]:
'''simple docstring'''
kwargs.update(self.special_tokens_map )
return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **lowerCamelCase__ )
def A__ ( self , lowerCamelCase__ ) -> Any:
'''simple docstring'''
lowercase__ = """こんにちは、世界。 \nこんばんは、㔺界。😀"""
lowercase__ = """こんにちは、世界。 \nこんばんは、世界。😀"""
return input_text, output_text
def A__ ( self , lowerCamelCase__ ) -> str:
'''simple docstring'''
lowercase__ , lowercase__ = self.get_input_output_texts(lowerCamelCase__ )
lowercase__ = tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ )
lowercase__ = tokenizer.decode(lowerCamelCase__ , clean_up_tokenization_spaces=lowerCamelCase__ )
return text, ids
def A__ ( self ) -> List[str]:
'''simple docstring'''
pass # TODO add if relevant
def A__ ( self ) -> Optional[int]:
'''simple docstring'''
pass # TODO add if relevant
def A__ ( self ) -> Union[str, Any]:
'''simple docstring'''
pass # TODO add if relevant
def A__ ( self ) -> List[str]:
'''simple docstring'''
lowercase__ = self.get_tokenizer()
# Testing tokenization
lowercase__ = """こんにちは、世界。 こんばんは、㔺界。"""
lowercase__ = ["""こん""", """にちは""", """、""", """世界""", """。""", """<SP>""", """こん""", """ばんは""", """、""", """㔺界""", """。"""]
lowercase__ = tokenizer.tokenize(lowerCamelCase__ )
self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ )
# Testing conversion to ids without special tokens
lowercase__ = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6]
lowercase__ = tokenizer.convert_tokens_to_ids(lowerCamelCase__ )
self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ )
# Testing conversion to ids with special tokens
lowercase__ = tokens + [tokenizer.unk_token]
lowercase__ = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19]
lowercase__ = tokenizer.convert_tokens_to_ids(lowerCamelCase__ )
self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ )
def A__ ( self ) -> Optional[int]:
'''simple docstring'''
lowercase__ = self.get_tokenizer()
# Testing tokenization
lowercase__ = """こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。"""
lowercase__ = """こんにちは、、、、世界。こんばんは、、、、世界。"""
lowercase__ = tokenizer.encode(lowerCamelCase__ )
lowercase__ = tokenizer.decode(lowerCamelCase__ )
self.assertEqual(lowerCamelCase__ , lowerCamelCase__ )
@slow
def A__ ( self ) -> List[Any]:
'''simple docstring'''
lowercase__ = self.tokenizer_class.from_pretrained("""Tanrei/GPTSAN-japanese""" )
# Testing tokenization
lowercase__ = """こんにちは、世界。"""
lowercase__ = """こんばんは、㔺界。😀"""
lowercase__ = """こんにちは、世界。こんばんは、世界。😀"""
lowercase__ = tokenizer.encode(prefix_text + input_text )
lowercase__ = tokenizer.encode("""""" , prefix_text=prefix_text + input_text )
lowercase__ = tokenizer.encode(lowerCamelCase__ , prefix_text=lowerCamelCase__ )
lowercase__ = tokenizer.decode(lowerCamelCase__ )
lowercase__ = tokenizer.decode(lowerCamelCase__ )
lowercase__ = tokenizer.decode(lowerCamelCase__ )
self.assertEqual(lowerCamelCase__ , lowerCamelCase__ )
self.assertEqual(lowerCamelCase__ , lowerCamelCase__ )
self.assertEqual(lowerCamelCase__ , lowerCamelCase__ )
@slow
def A__ ( self ) -> Any:
'''simple docstring'''
lowercase__ = self.tokenizer_class.from_pretrained("""Tanrei/GPTSAN-japanese""" )
# Testing tokenization
lowercase__ = """こんにちは、世界。"""
lowercase__ = """こんばんは、㔺界。😀"""
lowercase__ = len(tokenizer.encode(lowerCamelCase__ ) ) - 2
lowercase__ = len(tokenizer.encode(lowerCamelCase__ ) ) - 2
lowercase__ = [1] + [0] * (len_prefix + len_text + 1)
lowercase__ = [1] * (len_prefix + len_text + 1) + [0]
lowercase__ = [1] + [1] * (len_prefix) + [0] * (len_text + 1)
lowercase__ = tokenizer(prefix_text + input_text ).token_type_ids
lowercase__ = tokenizer("""""" , prefix_text=prefix_text + input_text ).token_type_ids
lowercase__ = tokenizer(lowerCamelCase__ , prefix_text=lowerCamelCase__ ).token_type_ids
self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ )
self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ )
self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ )
@slow
def A__ ( self ) -> Optional[Any]:
'''simple docstring'''
lowercase__ = self.tokenizer_class.from_pretrained("""Tanrei/GPTSAN-japanese""" )
lowercase__ = tokenizer.encode("""あンいワ""" )
lowercase__ = tokenizer.encode("""""" , prefix_text="""あンいワ""" )
lowercase__ = tokenizer.encode("""いワ""" , prefix_text="""あン""" )
self.assertEqual(tokenizer.decode(lowerCamelCase__ ) , tokenizer.decode(lowerCamelCase__ ) )
self.assertEqual(tokenizer.decode(lowerCamelCase__ ) , tokenizer.decode(lowerCamelCase__ ) )
self.assertNotEqual(lowerCamelCase__ , lowerCamelCase__ )
self.assertNotEqual(lowerCamelCase__ , lowerCamelCase__ )
self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token
self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token
@slow
def A__ ( self ) -> Tuple:
'''simple docstring'''
lowercase__ = self.tokenizer_class.from_pretrained("""Tanrei/GPTSAN-japanese""" )
lowercase__ = [["""武田信玄""", """は、"""], ["""織田信長""", """の配下の、"""]]
lowercase__ = tokenizer(lowerCamelCase__ , padding=lowerCamelCase__ )
lowercase__ = tokenizer.batch_encode_plus(lowerCamelCase__ , padding=lowerCamelCase__ )
# fmt: off
lowercase__ = [[35_993, 8_640, 25_948, 35_998, 30_647, 35_675, 35_999, 35_999], [35_993, 10_382, 9_868, 35_998, 30_646, 9_459, 30_646, 35_675]]
lowercase__ = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]]
lowercase__ = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]]
# fmt: on
self.assertListEqual(x_token.input_ids , lowerCamelCase__ )
self.assertListEqual(x_token.token_type_ids , lowerCamelCase__ )
self.assertListEqual(x_token.attention_mask , lowerCamelCase__ )
self.assertListEqual(x_token_a.input_ids , lowerCamelCase__ )
self.assertListEqual(x_token_a.token_type_ids , lowerCamelCase__ )
self.assertListEqual(x_token_a.attention_mask , lowerCamelCase__ )
def A__ ( self ) -> int:
'''simple docstring'''
pass
def A__ ( self ) -> int:
'''simple docstring'''
pass
| 325 |
'''simple docstring'''
from ..utils import (
OptionalDependencyNotAvailable,
is_flax_available,
is_scipy_available,
is_torch_available,
is_torchsde_available,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ..utils.dummy_pt_objects import * # noqa F403
else:
from .scheduling_consistency_models import CMStochasticIterativeScheduler
from .scheduling_ddim import DDIMScheduler
from .scheduling_ddim_inverse import DDIMInverseScheduler
from .scheduling_ddim_parallel import DDIMParallelScheduler
from .scheduling_ddpm import DDPMScheduler
from .scheduling_ddpm_parallel import DDPMParallelScheduler
from .scheduling_deis_multistep import DEISMultistepScheduler
from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler
from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler
from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler
from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler
from .scheduling_euler_discrete import EulerDiscreteScheduler
from .scheduling_heun_discrete import HeunDiscreteScheduler
from .scheduling_ipndm import IPNDMScheduler
from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler
from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler
from .scheduling_karras_ve import KarrasVeScheduler
from .scheduling_pndm import PNDMScheduler
from .scheduling_repaint import RePaintScheduler
from .scheduling_sde_ve import ScoreSdeVeScheduler
from .scheduling_sde_vp import ScoreSdeVpScheduler
from .scheduling_unclip import UnCLIPScheduler
from .scheduling_unipc_multistep import UniPCMultistepScheduler
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin
from .scheduling_vq_diffusion import VQDiffusionScheduler
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ..utils.dummy_flax_objects import * # noqa F403
else:
from .scheduling_ddim_flax import FlaxDDIMScheduler
from .scheduling_ddpm_flax import FlaxDDPMScheduler
from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler
from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler
from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler
from .scheduling_pndm_flax import FlaxPNDMScheduler
from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler
from .scheduling_utils_flax import (
FlaxKarrasDiffusionSchedulers,
FlaxSchedulerMixin,
FlaxSchedulerOutput,
broadcast_to_shape_from_left,
)
try:
if not (is_torch_available() and is_scipy_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ..utils.dummy_torch_and_scipy_objects import * # noqa F403
else:
from .scheduling_lms_discrete import LMSDiscreteScheduler
try:
if not (is_torch_available() and is_torchsde_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ..utils.dummy_torch_and_torchsde_objects import * # noqa F403
else:
from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler
| 325 | 1 |
'''simple docstring'''
from math import factorial, pi
def UpperCamelCase_ ( A__ : float , A__ : int = 30 ):
'''simple docstring'''
if not isinstance(A__ , (int, float) ):
raise ValueError("""maclaurin_sin() requires either an int or float for theta""" )
if not isinstance(A__ , A__ ) or accuracy <= 0:
raise ValueError("""maclaurin_sin() requires a positive int for accuracy""" )
lowerCAmelCase_ : Optional[Any] = float(A__ )
lowerCAmelCase_ : List[str] = theta // (2 * pi)
theta -= 2 * div * pi
return sum(
(-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(A__ ) )
def UpperCamelCase_ ( A__ : float , A__ : int = 30 ):
'''simple docstring'''
if not isinstance(A__ , (int, float) ):
raise ValueError("""maclaurin_cos() requires either an int or float for theta""" )
if not isinstance(A__ , A__ ) or accuracy <= 0:
raise ValueError("""maclaurin_cos() requires a positive int for accuracy""" )
lowerCAmelCase_ : Optional[Any] = float(A__ )
lowerCAmelCase_ : Optional[Any] = theta // (2 * pi)
theta -= 2 * div * pi
return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(A__ ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
print(maclaurin_sin(10))
print(maclaurin_sin(-10))
print(maclaurin_sin(10, 15))
print(maclaurin_sin(-10, 15))
print(maclaurin_cos(5))
print(maclaurin_cos(-5))
print(maclaurin_cos(10, 15))
print(maclaurin_cos(-10, 15))
| 398 |
'''simple docstring'''
def UpperCamelCase_ ( A__ : int ):
'''simple docstring'''
if not isinstance(A__ , A__ ) or number < 0:
raise ValueError("""Input must be a non-negative integer""" )
lowerCAmelCase_ : List[str] = 0
while number:
# This way we arrive at next set bit (next 1) instead of looping
# through each bit and checking for 1s hence the
# loop won't run 32 times it will only run the number of `1` times
number &= number - 1
count += 1
return count
if __name__ == "__main__":
import doctest
doctest.testmod()
| 398 | 1 |
'''simple docstring'''
from __future__ import annotations
from collections import deque
class _A :
def __init__( self : Optional[Any] , __magic_name__ : list[str] ) -> Tuple:
"""simple docstring"""
__snake_case : list[dict] = []
self.adlist.append(
{"""value""": """""", """next_states""": [], """fail_state""": 0, """output""": []} )
for keyword in keywords:
self.add_keyword(__magic_name__ )
self.set_fail_transitions()
def lowercase__ ( self : Union[str, Any] , __magic_name__ : int , __magic_name__ : str ) -> int | None:
"""simple docstring"""
for state in self.adlist[current_state]["next_states"]:
if char == self.adlist[state]["value"]:
return state
return None
def lowercase__ ( self : str , __magic_name__ : str ) -> None:
"""simple docstring"""
__snake_case : Optional[Any] = 0
for character in keyword:
__snake_case : int = self.find_next_state(__magic_name__ , __magic_name__ )
if next_state is None:
self.adlist.append(
{
"""value""": character,
"""next_states""": [],
"""fail_state""": 0,
"""output""": [],
} )
self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 )
__snake_case : Union[str, Any] = len(self.adlist ) - 1
else:
__snake_case : List[str] = next_state
self.adlist[current_state]["output"].append(__magic_name__ )
def lowercase__ ( self : Dict ) -> None:
"""simple docstring"""
__snake_case : deque = deque()
for node in self.adlist[0]["next_states"]:
q.append(__magic_name__ )
__snake_case : Dict = 0
while q:
__snake_case : Optional[Any] = q.popleft()
for child in self.adlist[r]["next_states"]:
q.append(__magic_name__ )
__snake_case : Dict = self.adlist[r]["""fail_state"""]
while (
self.find_next_state(__magic_name__ , self.adlist[child]["""value"""] ) is None
and state != 0
):
__snake_case : Optional[int] = self.adlist[state]["""fail_state"""]
__snake_case : Union[str, Any] = self.find_next_state(
__magic_name__ , self.adlist[child]["""value"""] )
if self.adlist[child]["fail_state"] is None:
__snake_case : List[Any] = 0
__snake_case : Any = (
self.adlist[child]["""output"""]
+ self.adlist[self.adlist[child]["""fail_state"""]]["""output"""]
)
def lowercase__ ( self : List[str] , __magic_name__ : str ) -> dict[str, list[int]]:
"""simple docstring"""
__snake_case : dict = {} # returns a dict with keywords and list of its occurrences
__snake_case : Optional[int] = 0
for i in range(len(__magic_name__ ) ):
while (
self.find_next_state(__magic_name__ , string[i] ) is None
and current_state != 0
):
__snake_case : List[Any] = self.adlist[current_state]["""fail_state"""]
__snake_case : List[Any] = self.find_next_state(__magic_name__ , string[i] )
if next_state is None:
__snake_case : int = 0
else:
__snake_case : Dict = next_state
for key in self.adlist[current_state]["output"]:
if key not in result:
__snake_case : Union[str, Any] = []
result[key].append(i - len(__magic_name__ ) + 1 )
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
| 26 |
import sys
def __magic_name__ ( __lowerCAmelCase : str ) -> Union[str, Any]:
__lowerCamelCase = len(__lowerCAmelCase )
__lowerCamelCase = [[0 for x in range(__lowerCAmelCase )] for x in range(__lowerCAmelCase )]
__lowerCamelCase = [[0 for x in range(__lowerCAmelCase )] for x in range(__lowerCAmelCase )]
for chain_length in range(2 , __lowerCAmelCase ):
for a in range(1 , n - chain_length + 1 ):
__lowerCamelCase = a + chain_length - 1
__lowerCamelCase = sys.maxsize
for c in range(__lowerCAmelCase , __lowerCAmelCase ):
__lowerCamelCase = (
matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b]
)
if cost < matrix[a][b]:
__lowerCamelCase = cost
__lowerCamelCase = c
return matrix, sol
def __magic_name__ ( __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[int] ) -> List[str]:
if i == j:
print('''A''' + str(__lowerCAmelCase ) , end=''' ''' )
else:
print('''(''' , end=''' ''' )
print_optiomal_solution(__lowerCAmelCase , __lowerCAmelCase , optimal_solution[i][j] )
print_optiomal_solution(__lowerCAmelCase , optimal_solution[i][j] + 1 , __lowerCAmelCase )
print(''')''' , end=''' ''' )
def __magic_name__ ( ) -> Optional[Any]:
__lowerCamelCase = [30, 35, 15, 5, 10, 20, 25]
__lowerCamelCase = len(__lowerCAmelCase )
# Size of matrix created from above array will be
# 30*35 35*15 15*5 5*10 10*20 20*25
__lowerCamelCase , __lowerCamelCase = matrix_chain_order(__lowerCAmelCase )
print('''No. of Operation required: ''' + str(matrix[1][n - 1] ) )
print_optiomal_solution(__lowerCAmelCase , 1 , n - 1 )
if __name__ == "__main__":
main()
| 298 | 0 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
SCREAMING_SNAKE_CASE = {
'configuration_graphormer': ['GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GraphormerConfig'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE = [
'GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
'GraphormerForGraphClassification',
'GraphormerModel',
'GraphormerPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_graphormer import GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, GraphormerConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_graphormer import (
GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
GraphormerForGraphClassification,
GraphormerModel,
GraphormerPreTrainedModel,
)
else:
import sys
SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 209 |
import os
from argparse import ArgumentParser
from typing import List
import torch.utils.data
from datasets import Dataset, IterableDataset
from datasets.distributed import split_dataset_by_node
SCREAMING_SNAKE_CASE = 4
SCREAMING_SNAKE_CASE = 3
class __UpperCAmelCase ( __A ):
"""simple docstring"""
pass
def a (lowerCAmelCase__ ):
for shard in shards:
for i in range(lowerCAmelCase__ ):
yield {"i": i, "shard": shard}
def a ():
__a = int(os.environ["""RANK"""] )
__a = int(os.environ["""WORLD_SIZE"""] )
__a = ArgumentParser()
parser.add_argument("""--streaming""" , type=lowerCAmelCase__ )
parser.add_argument("""--local_rank""" , type=lowerCAmelCase__ )
parser.add_argument("""--num_workers""" , type=lowerCAmelCase__ , default=0 )
__a = parser.parse_args()
__a = args.streaming
__a = args.num_workers
__a = {"""shards""": [f'''shard_{shard_idx}''' for shard_idx in range(lowerCAmelCase__ )]}
__a = IterableDataset.from_generator(lowerCAmelCase__ , gen_kwargs=lowerCAmelCase__ )
if not streaming:
__a = Dataset.from_list(list(lowerCAmelCase__ ) )
__a = split_dataset_by_node(lowerCAmelCase__ , rank=lowerCAmelCase__ , world_size=lowerCAmelCase__ )
__a = torch.utils.data.DataLoader(lowerCAmelCase__ , num_workers=lowerCAmelCase__ )
__a = NUM_SHARDS * NUM_ITEMS_PER_SHARD
__a = full_size // world_size
expected_local_size += int(rank < (full_size % world_size) )
__a = sum(1 for _ in dataloader )
if local_size != expected_local_size:
raise FailedTestError(f'''local_size {local_size} != expected_local_size {expected_local_size}''' )
if __name__ == "__main__":
main()
| 209 | 1 |
import multiprocessing
from typing import TYPE_CHECKING, Optional, Union
from .. import Dataset, Features, config
from ..formatting import query_table
from ..packaged_modules.sql.sql import Sql
from ..utils import logging
from .abc import AbstractDatasetInputStream
if TYPE_CHECKING:
import sqlitea
import sqlalchemy
class _lowerCAmelCase ( a__ ):
def __init__( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = None , _UpperCamelCase = None , _UpperCamelCase = False , **_UpperCamelCase , ) -> Tuple:
super().__init__(features=_lowerCamelCase , cache_dir=_lowerCamelCase , keep_in_memory=_lowerCamelCase , **_lowerCamelCase )
lowerCAmelCase_ = Sql(
cache_dir=_lowerCamelCase , features=_lowerCamelCase , sql=_lowerCamelCase , con=_lowerCamelCase , **_lowerCamelCase , )
def __a ( self ) -> int:
lowerCAmelCase_ = None
lowerCAmelCase_ = None
lowerCAmelCase_ = None
lowerCAmelCase_ = None
self.builder.download_and_prepare(
download_config=_lowerCamelCase , download_mode=_lowerCamelCase , verification_mode=_lowerCamelCase , base_path=_lowerCamelCase , )
# Build dataset for splits
lowerCAmelCase_ = self.builder.as_dataset(
split="train" , verification_mode=_lowerCamelCase , in_memory=self.keep_in_memory )
return dataset
class _lowerCAmelCase :
def __init__( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = None , _UpperCamelCase = None , **_UpperCamelCase , ) -> Any:
if num_proc is not None and num_proc <= 0:
raise ValueError(f"""num_proc {num_proc} must be an integer > 0.""" )
lowerCAmelCase_ = dataset
lowerCAmelCase_ = name
lowerCAmelCase_ = con
lowerCAmelCase_ = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
lowerCAmelCase_ = num_proc
lowerCAmelCase_ = to_sql_kwargs
def __a ( self ) -> int:
lowerCAmelCase_ = self.to_sql_kwargs.pop("sql" , _lowerCamelCase )
lowerCAmelCase_ = self.to_sql_kwargs.pop("con" , _lowerCamelCase )
lowerCAmelCase_ = self.to_sql_kwargs.pop("index" , _lowerCamelCase )
lowerCAmelCase_ = self._write(index=_lowerCamelCase , **self.to_sql_kwargs )
return written
def __a ( self , _UpperCamelCase ) -> Any:
lowerCAmelCase_ = args
lowerCAmelCase_ = {**to_sql_kwargs, """if_exists""": """append"""} if offset > 0 else to_sql_kwargs
lowerCAmelCase_ = query_table(
table=self.dataset.data , key=slice(_lowerCamelCase , offset + self.batch_size ) , indices=self.dataset._indices , )
lowerCAmelCase_ = batch.to_pandas()
lowerCAmelCase_ = df.to_sql(self.name , self.con , index=_lowerCamelCase , **_lowerCamelCase )
return num_rows or len(_lowerCamelCase )
def __a ( self , _UpperCamelCase , **_UpperCamelCase ) -> Dict:
lowerCAmelCase_ = 0
if self.num_proc is None or self.num_proc == 1:
for offset in logging.tqdm(
range(0 , len(self.dataset ) , self.batch_size ) , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ):
written += self._batch_sql((offset, index, to_sql_kwargs) )
else:
lowerCAmelCase_ = len(self.dataset ), self.batch_size
with multiprocessing.Pool(self.num_proc ) as pool:
for num_rows in logging.tqdm(
pool.imap(
self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , _lowerCamelCase , _lowerCamelCase )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ):
written += num_rows
return written
| 290 |
'''simple docstring'''
import unittest
import numpy as np
from transformers import BertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
if is_flax_available():
from transformers.models.bert.modeling_flax_bert import (
FlaxBertForMaskedLM,
FlaxBertForMultipleChoice,
FlaxBertForNextSentencePrediction,
FlaxBertForPreTraining,
FlaxBertForQuestionAnswering,
FlaxBertForSequenceClassification,
FlaxBertForTokenClassification,
FlaxBertModel,
)
class _snake_case ( unittest.TestCase ):
def __init__( self , _lowerCamelCase , _lowerCamelCase=13 , _lowerCamelCase=7 , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=99 , _lowerCamelCase=32 , _lowerCamelCase=5 , _lowerCamelCase=4 , _lowerCamelCase=37 , _lowerCamelCase="gelu" , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=512 , _lowerCamelCase=16 , _lowerCamelCase=2 , _lowerCamelCase=0.02 , _lowerCamelCase=4 , ):
UpperCAmelCase__ : Any = parent
UpperCAmelCase__ : Any = batch_size
UpperCAmelCase__ : str = seq_length
UpperCAmelCase__ : List[str] = is_training
UpperCAmelCase__ : str = use_attention_mask
UpperCAmelCase__ : Any = use_token_type_ids
UpperCAmelCase__ : Union[str, Any] = use_labels
UpperCAmelCase__ : int = vocab_size
UpperCAmelCase__ : Optional[Any] = hidden_size
UpperCAmelCase__ : Optional[int] = num_hidden_layers
UpperCAmelCase__ : Optional[int] = num_attention_heads
UpperCAmelCase__ : Optional[int] = intermediate_size
UpperCAmelCase__ : str = hidden_act
UpperCAmelCase__ : Optional[int] = hidden_dropout_prob
UpperCAmelCase__ : Optional[Any] = attention_probs_dropout_prob
UpperCAmelCase__ : Optional[int] = max_position_embeddings
UpperCAmelCase__ : List[str] = type_vocab_size
UpperCAmelCase__ : Optional[int] = type_sequence_label_size
UpperCAmelCase__ : Optional[int] = initializer_range
UpperCAmelCase__ : Optional[int] = num_choices
def snake_case__ ( self):
UpperCAmelCase__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
UpperCAmelCase__ : List[Any] = None
if self.use_attention_mask:
UpperCAmelCase__ : Tuple = random_attention_mask([self.batch_size, self.seq_length])
UpperCAmelCase__ : Any = None
if self.use_token_type_ids:
UpperCAmelCase__ : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size)
UpperCAmelCase__ : Dict = BertConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_lowerCamelCase , initializer_range=self.initializer_range , )
return config, input_ids, token_type_ids, attention_mask
def snake_case__ ( self):
UpperCAmelCase__ : int = self.prepare_config_and_inputs()
UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Dict = config_and_inputs
UpperCAmelCase__ : int = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask}
return config, inputs_dict
def snake_case__ ( self):
UpperCAmelCase__ : str = self.prepare_config_and_inputs()
UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Dict = config_and_inputs
UpperCAmelCase__ : Any = True
UpperCAmelCase__ : Dict = 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,
attention_mask,
encoder_hidden_states,
encoder_attention_mask,
)
@require_flax
class _snake_case ( a__ , unittest.TestCase ):
lowerCAmelCase :List[Any] = True
lowerCAmelCase :int = (
(
FlaxBertModel,
FlaxBertForPreTraining,
FlaxBertForMaskedLM,
FlaxBertForMultipleChoice,
FlaxBertForQuestionAnswering,
FlaxBertForNextSentencePrediction,
FlaxBertForSequenceClassification,
FlaxBertForTokenClassification,
FlaxBertForQuestionAnswering,
)
if is_flax_available()
else ()
)
def snake_case__ ( self):
UpperCAmelCase__ : List[str] = FlaxBertModelTester(self)
@slow
def snake_case__ ( self):
# Only check this for base model, not necessary for all model classes.
# This will also help speed-up tests.
UpperCAmelCase__ : Optional[int] = FlaxBertModel.from_pretrained("""bert-base-cased""")
UpperCAmelCase__ : Optional[Any] = model(np.ones((1, 1)))
self.assertIsNotNone(_lowerCamelCase) | 407 | 0 |
'''simple docstring'''
import numpy as np
import qiskit
def UpperCAmelCase ( a_ = 8 , a_ = None ) -> str:
"""simple docstring"""
A_ : Any = np.random.default_rng(seed=lowercase__ )
# Roughly 25% of the qubits will contribute to the key.
# So we take more than we need.
A_ : Union[str, Any] = 6 * key_len
# Measurement basis for Alice's qubits.
A_ : Optional[int] = rng.integers(2 , size=lowercase__ )
# The set of states Alice will prepare.
A_ : Optional[int] = rng.integers(2 , size=lowercase__ )
# Measurement basis for Bob's qubits.
A_ : Any = rng.integers(2 , size=lowercase__ )
# Quantum Circuit to simulate BB84
A_ : List[Any] = qiskit.QuantumCircuit(lowercase__ , name="""BB84""" )
# Alice prepares her qubits according to rules above.
for index, _ in enumerate(lowercase__ ):
if alice_state[index] == 1:
bbaa_circ.x(lowercase__ )
if alice_basis[index] == 1:
bbaa_circ.h(lowercase__ )
bbaa_circ.barrier()
# Bob measures the received qubits according to rules above.
for index, _ in enumerate(lowercase__ ):
if bob_basis[index] == 1:
bbaa_circ.h(lowercase__ )
bbaa_circ.barrier()
bbaa_circ.measure_all()
# Simulate the quantum circuit.
A_ : List[Any] = qiskit.Aer.get_backend("""aer_simulator""" )
# We only need to run one shot because the key is unique.
# Multiple shots will produce the same key.
A_ : Optional[Any] = qiskit.execute(lowercase__ , lowercase__ , shots=1 , seed_simulator=lowercase__ )
# Returns the result of measurement.
A_ : Tuple = job.result().get_counts(lowercase__ ).most_frequent()
# Extracting the generated key from the simulation results.
# Only keep measurement results where Alice and Bob chose the same basis.
A_ : Union[str, Any] = """""".join(
[
result_bit
for alice_basis_bit, bob_basis_bit, result_bit in zip(
lowercase__ , lowercase__ , lowercase__ )
if alice_basis_bit == bob_basis_bit
] )
# Get final key. Pad with 0 if too short, otherwise truncate.
A_ : int = gen_key[:key_len] if len(lowercase__ ) >= key_len else gen_key.ljust(lowercase__ , """0""" )
return key
if __name__ == "__main__":
print(f'The generated key is : {bbaa(8, seed=0)}')
from doctest import testmod
testmod()
| 719 |
'''simple docstring'''
import copy
from dataclasses import dataclass, field
from typing import ClassVar, Dict
from ..features import Audio, ClassLabel, Features
from .base import TaskTemplate
@dataclass(frozen=__A )
class _lowerCAmelCase ( __A ):
"""simple docstring"""
lowerCamelCase = field(default='''audio-classification''', metadata={'''include_in_asdict_even_if_is_default''': True} )
lowerCamelCase = Features({'''audio''': Audio()} )
lowerCamelCase = Features({'''labels''': ClassLabel} )
lowerCamelCase = "audio"
lowerCamelCase = "labels"
def UpperCAmelCase_ ( self , _lowerCamelCase ) -> List[Any]:
if self.label_column not in features:
raise ValueError(F"Column {self.label_column} is not present in features." )
if not isinstance(features[self.label_column] , _lowerCamelCase ):
raise ValueError(F"Column {self.label_column} is not a ClassLabel." )
A_ : Optional[int] = copy.deepcopy(self )
A_ : int = self.label_schema.copy()
A_ : Optional[Any] = features[self.label_column]
A_ : Optional[Any] = label_schema
return task_template
@property
def UpperCAmelCase_ ( self ) -> Dict[str, str]:
return {
self.audio_column: "audio",
self.label_column: "labels",
}
| 385 | 0 |
import copy
from typing import Dict, Optional
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
from ..detr import DetrConfig
from ..swin import SwinConfig
UpperCAmelCase_ = {
"facebook/maskformer-swin-base-ade": (
"https://huggingface.co/facebook/maskformer-swin-base-ade/blob/main/config.json"
)
# See all MaskFormer models at https://huggingface.co/models?filter=maskformer
}
UpperCAmelCase_ = logging.get_logger(__name__)
class __UpperCamelCase ( A__ ):
__A : Optional[int] = """maskformer"""
__A : List[str] = {"""hidden_size""": """mask_feature_size"""}
__A : Union[str, Any] = ["""resnet""", """swin"""]
__A : Union[str, Any] = ["""detr"""]
def __init__( self , _UpperCamelCase = 256 , _UpperCamelCase = 256 , _UpperCamelCase = 0.1 , _UpperCamelCase = False , _UpperCamelCase = None , _UpperCamelCase = None , _UpperCamelCase = 0.02 , _UpperCamelCase = 1.0 , _UpperCamelCase = 1.0 , _UpperCamelCase = 1.0 , _UpperCamelCase = 20.0 , _UpperCamelCase = None , **_UpperCamelCase , ):
if backbone_config is None:
# fall back to https://huggingface.co/microsoft/swin-base-patch4-window12-384-in22k
_UpperCAmelCase = SwinConfig(
image_size=384 , in_channels=3 , patch_size=4 , embed_dim=128 , depths=[2, 2, 18, 2] , num_heads=[4, 8, 16, 32] , window_size=12 , drop_path_rate=0.3 , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , )
if isinstance(_UpperCamelCase , _UpperCamelCase ):
_UpperCAmelCase = backbone_config.pop('''model_type''' )
_UpperCAmelCase = CONFIG_MAPPING[backbone_model_type]
_UpperCAmelCase = config_class.from_dict(_UpperCamelCase )
# verify that the backbone is supported
if backbone_config.model_type not in self.backbones_supported:
logger.warning_once(
f'''Backbone {backbone_config.model_type} is not a supported model and may not be compatible with MaskFormer. '''
f'''Supported model types: {','.join(self.backbones_supported )}''' )
if decoder_config is None:
# fall back to https://huggingface.co/facebook/detr-resnet-50
_UpperCAmelCase = DetrConfig()
else:
# verify that the decoder is supported
_UpperCAmelCase = (
decoder_config.pop('''model_type''' ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else decoder_config.model_type
)
if decoder_type not in self.decoders_supported:
raise ValueError(
f'''Transformer Decoder {decoder_type} not supported, please use one of'''
f''' {','.join(self.decoders_supported )}''' )
if isinstance(_UpperCamelCase , _UpperCamelCase ):
_UpperCAmelCase = CONFIG_MAPPING[decoder_type]
_UpperCAmelCase = config_class.from_dict(_UpperCamelCase )
_UpperCAmelCase = backbone_config
_UpperCAmelCase = decoder_config
# main feature dimension for the model
_UpperCAmelCase = fpn_feature_size
_UpperCAmelCase = mask_feature_size
# initializer
_UpperCAmelCase = init_std
_UpperCAmelCase = init_xavier_std
# Hungarian matcher && loss
_UpperCAmelCase = cross_entropy_weight
_UpperCAmelCase = dice_weight
_UpperCAmelCase = mask_weight
_UpperCAmelCase = use_auxiliary_loss
_UpperCAmelCase = no_object_weight
_UpperCAmelCase = output_auxiliary_logits
_UpperCAmelCase = self.decoder_config.encoder_attention_heads
_UpperCAmelCase = self.decoder_config.num_hidden_layers
super().__init__(**_UpperCamelCase )
@classmethod
def UpperCamelCase( cls , _UpperCamelCase , _UpperCamelCase , **_UpperCamelCase ):
return cls(
backbone_config=_UpperCamelCase , decoder_config=_UpperCamelCase , **_UpperCamelCase , )
def UpperCamelCase( self ):
_UpperCAmelCase = copy.deepcopy(self.__dict__ )
_UpperCAmelCase = self.backbone_config.to_dict()
_UpperCAmelCase = self.decoder_config.to_dict()
_UpperCAmelCase = self.__class__.model_type
return output | 32 | 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 lowerCamelCase_ ( UpperCamelCase__ : Dataset, UpperCamelCase__ : Dict[str, str] ):
'''simple docstring'''
UpperCamelCase__ = args.log_outputs
UpperCamelCase__ = '''_'''.join(args.dataset.split('''/''' ) + [args.config, args.split] )
# load metric
UpperCamelCase__ = load_metric('''wer''' )
UpperCamelCase__ = load_metric('''cer''' )
# compute metrics
UpperCamelCase__ = wer.compute(references=result['''target'''], predictions=result['''prediction'''] )
UpperCamelCase__ = cer.compute(references=result['''target'''], predictions=result['''prediction'''] )
# print & log results
UpperCamelCase__ = F"""WER: {wer_result}\nCER: {cer_result}"""
print(UpperCamelCase__ )
with open(F"""{dataset_id}_eval_results.txt""", '''w''' ) as f:
f.write(UpperCamelCase__ )
# log all results in text file. Possibly interesting for analysis
if log_outputs is not None:
UpperCamelCase__ = F"""log_{dataset_id}_predictions.txt"""
UpperCamelCase__ = F"""log_{dataset_id}_targets.txt"""
with open(UpperCamelCase__, '''w''' ) as p, open(UpperCamelCase__, '''w''' ) as t:
# mapping function to write output
def write_to_file(UpperCamelCase__ : Optional[Any], UpperCamelCase__ : Tuple ):
p.write(F"""{i}""" + '''\n''' )
p.write(batch['''prediction'''] + '''\n''' )
t.write(F"""{i}""" + '''\n''' )
t.write(batch['''target'''] + '''\n''' )
result.map(UpperCamelCase__, with_indices=UpperCamelCase__ )
def lowerCamelCase_ ( UpperCamelCase__ : str ):
'''simple docstring'''
UpperCamelCase__ = '''[,?.!\-\;\:"“%‘”�—’…–]''' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training
UpperCamelCase__ = re.sub(UpperCamelCase__, '''''', text.lower() )
# In addition, we can normalize the target text, e.g. removing new lines characters etc...
# note that order is important here!
UpperCamelCase__ = ['''\n\n''', '''\n''', ''' ''', ''' ''']
for t in token_sequences_to_ignore:
UpperCamelCase__ = ''' '''.join(text.split(UpperCamelCase__ ) )
return text
def lowerCamelCase_ ( UpperCamelCase__ : Tuple ):
'''simple docstring'''
UpperCamelCase__ = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=UpperCamelCase__ )
# for testing: only process the first two examples as a test
# dataset = dataset.select(range(10))
# load processor
UpperCamelCase__ = AutoFeatureExtractor.from_pretrained(args.model_id )
UpperCamelCase__ = feature_extractor.sampling_rate
# resample audio
UpperCamelCase__ = dataset.cast_column('''audio''', Audio(sampling_rate=UpperCamelCase__ ) )
# load eval pipeline
if args.device is None:
UpperCamelCase__ = 0 if torch.cuda.is_available() else -1
UpperCamelCase__ = pipeline('''automatic-speech-recognition''', model=args.model_id, device=args.device )
# map function to decode audio
def map_to_pred(UpperCamelCase__ : Any ):
UpperCamelCase__ = asr(
batch['''audio''']['''array'''], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s )
UpperCamelCase__ = prediction['''text''']
UpperCamelCase__ = normalize_text(batch['''sentence'''] )
return batch
# run inference on all examples
UpperCamelCase__ = dataset.map(UpperCamelCase__, remove_columns=dataset.column_names )
# compute and log_results
# do not change function below
log_results(UpperCamelCase__, UpperCamelCase__ )
if __name__ == "__main__":
lowercase = 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.""",
)
lowercase = parser.parse_args()
main(args)
| 240 | 0 |
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging
_lowercase : List[Any] = logging.get_logger(__name__)
_lowercase : Dict = {"vocab_file": "sentencepiece.bpe.model"}
_lowercase : Union[str, Any] = {
"vocab_file": {
"moussaKam/mbarthez": "https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model",
"moussaKam/barthez": "https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model",
"moussaKam/barthez-orangesum-title": (
"https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model"
),
},
}
_lowercase : Dict = {
"moussaKam/mbarthez": 1024,
"moussaKam/barthez": 1024,
"moussaKam/barthez-orangesum-title": 1024,
}
_lowercase : int = "▁"
class _UpperCamelCase ( __snake_case ):
"""simple docstring"""
lowerCAmelCase = VOCAB_FILES_NAMES
lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP
lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowerCAmelCase = ['input_ids', 'attention_mask']
def __init__( self , a__ , a__="<s>" , a__="</s>" , a__="</s>" , a__="<s>" , a__="<unk>" , a__="<pad>" , a__="<mask>" , a__ = None , **a__ , ) -> None:
# Mask token behave like a normal word, i.e. include the space before it
A = AddedToken(a__ , lstrip=a__ , rstrip=a__ ) if isinstance(a__ , a__ ) else mask_token
A = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
bos_token=a__ , eos_token=a__ , unk_token=a__ , sep_token=a__ , cls_token=a__ , pad_token=a__ , mask_token=a__ , sp_model_kwargs=self.sp_model_kwargs , **a__ , )
A = vocab_file
A = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(str(a__ ) )
A = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3}
A = len(self.sp_model ) - 1
A = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
def _UpperCAmelCase ( self , a__ , a__ = None ) -> List[int]:
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
A = [self.cls_token_id]
A = [self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def _UpperCAmelCase ( self , a__ , a__ = None , a__ = False ) -> List[int]:
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=a__ , token_ids_a=a__ , already_has_special_tokens=a__ )
if token_ids_a is None:
return [1] + ([0] * len(a__ )) + [1]
return [1] + ([0] * len(a__ )) + [1, 1] + ([0] * len(a__ )) + [1]
def _UpperCAmelCase ( self , a__ , a__ = None ) -> List[int]:
A = [self.sep_token_id]
A = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
@property
def _UpperCAmelCase ( self ) -> Tuple:
return len(self.sp_model )
def _UpperCAmelCase ( self ) -> List[Any]:
A = {self.convert_ids_to_tokens(a__ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def _UpperCAmelCase ( self , a__ ) -> List[str]:
return self.sp_model.encode(a__ , out_type=a__ )
def _UpperCAmelCase ( self , a__ ) -> Tuple:
if token in self.fairseq_tokens_to_ids:
return self.fairseq_tokens_to_ids[token]
A = self.sp_model.PieceToId(a__ )
return spm_id if spm_id else self.unk_token_id
def _UpperCAmelCase ( self , a__ ) -> List[Any]:
if index in self.fairseq_ids_to_tokens:
return self.fairseq_ids_to_tokens[index]
return self.sp_model.IdToPiece(a__ )
def _UpperCAmelCase ( self , a__ ) -> List[str]:
A = []
A = """"""
A = False
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
if not prev_is_special:
out_string += " "
out_string += self.sp_model.decode(a__ ) + token
A = True
A = []
else:
current_sub_tokens.append(a__ )
A = False
out_string += self.sp_model.decode(a__ )
return out_string.strip()
def __getstate__( self ) -> int:
A = self.__dict__.copy()
A = None
return state
def __setstate__( self , a__ ) -> Optional[Any]:
A = d
# for backward compatibility
if not hasattr(self , """sp_model_kwargs""" ):
A = {}
A = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def _UpperCAmelCase ( self , a__ , a__ = None ) -> Tuple[str]:
if not os.path.isdir(a__ ):
logger.error(f'Vocabulary path ({save_directory}) should be a directory' )
return
A = os.path.join(
a__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(a__ ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , a__ )
elif not os.path.isfile(self.vocab_file ):
with open(a__ , """wb""" ) as fi:
A = self.sp_model.serialized_model_proto()
fi.write(a__ )
return (out_vocab_file,)
| 546 |
from typing import List, Optional, Union
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_lowercase : Optional[Any] = logging.get_logger(__name__)
_lowercase : List[str] = {
"huggingface/informer-tourism-monthly": (
"https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json"
),
# See all Informer models at https://huggingface.co/models?filter=informer
}
class _UpperCamelCase ( __snake_case ):
"""simple docstring"""
lowerCAmelCase = 'informer'
lowerCAmelCase = {
'hidden_size': 'd_model',
'num_attention_heads': 'encoder_attention_heads',
'num_hidden_layers': 'encoder_layers',
}
def __init__( self , a__ = None , a__ = None , a__ = "student_t" , a__ = "nll" , a__ = 1 , a__ = None , a__ = "mean" , a__ = 0 , a__ = 0 , a__ = 0 , a__ = 0 , a__ = None , a__ = None , a__ = 64 , a__ = 32 , a__ = 32 , a__ = 2 , a__ = 2 , a__ = 2 , a__ = 2 , a__ = True , a__ = "gelu" , a__ = 0.05 , a__ = 0.1 , a__ = 0.1 , a__ = 0.1 , a__ = 0.1 , a__ = 100 , a__ = 0.02 , a__=True , a__ = "prob" , a__ = 5 , a__ = True , **a__ , ) -> Union[str, Any]:
# time series specific configuration
A = prediction_length
A = context_length or prediction_length
A = distribution_output
A = loss
A = input_size
A = num_time_features
A = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7]
A = scaling
A = num_dynamic_real_features
A = num_static_real_features
A = num_static_categorical_features
# set cardinality
if cardinality and num_static_categorical_features > 0:
if len(a__ ) != num_static_categorical_features:
raise ValueError(
"""The cardinality should be a list of the same length as `num_static_categorical_features`""" )
A = cardinality
else:
A = [0]
# set embedding_dimension
if embedding_dimension and num_static_categorical_features > 0:
if len(a__ ) != num_static_categorical_features:
raise ValueError(
"""The embedding dimension should be a list of the same length as `num_static_categorical_features`""" )
A = embedding_dimension
else:
A = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality]
A = num_parallel_samples
# Transformer architecture configuration
A = input_size * len(self.lags_sequence ) + self._number_of_features
A = d_model
A = encoder_attention_heads
A = decoder_attention_heads
A = encoder_ffn_dim
A = decoder_ffn_dim
A = encoder_layers
A = decoder_layers
A = dropout
A = attention_dropout
A = activation_dropout
A = encoder_layerdrop
A = decoder_layerdrop
A = activation_function
A = init_std
A = use_cache
# Informer
A = attention_type
A = sampling_factor
A = distil
super().__init__(is_encoder_decoder=a__ , **a__ )
@property
def _UpperCAmelCase ( self ) -> int:
return (
sum(self.embedding_dimension )
+ self.num_dynamic_real_features
+ self.num_time_features
+ self.num_static_real_features
+ self.input_size * 2 # the log1p(abs(loc)) and log(scale) features
)
| 546 | 1 |
import json
import os
import unittest
from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer
from ...test_tokenization_common import TokenizerTesterMixin
class UpperCAmelCase_ ( _lowercase , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ : int = CTRLTokenizer
UpperCAmelCase__ : List[Any] = False
UpperCAmelCase__ : Any = False
def __lowercase ( self ) -> List[str]:
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
_a : Optional[int] = ['''adapt''', '''re@@''', '''a@@''', '''apt''', '''c@@''', '''t''', '''<unk>''']
_a : List[str] = dict(zip(A__ , range(len(A__ ) ) ) )
_a : str = ['''#version: 0.2''', '''a p''', '''ap t</w>''', '''r e''', '''a d''', '''ad apt</w>''', '''''']
_a : str = {'''unk_token''': '''<unk>'''}
_a : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
_a : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp:
fp.write(json.dumps(A__ ) + '''\n''' )
with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp:
fp.write('''\n'''.join(A__ ) )
def __lowercase ( self , **_a ) -> Dict:
kwargs.update(self.special_tokens_map )
return CTRLTokenizer.from_pretrained(self.tmpdirname , **A__ )
def __lowercase ( self , _a ) -> Optional[Any]:
_a : Any = '''adapt react readapt apt'''
_a : Any = '''adapt react readapt apt'''
return input_text, output_text
def __lowercase ( self ) -> Any:
_a : Dict = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map )
_a : Any = '''adapt react readapt apt'''
_a : Optional[int] = '''adapt re@@ a@@ c@@ t re@@ adapt apt'''.split()
_a : Optional[Any] = tokenizer.tokenize(A__ )
self.assertListEqual(A__ , A__ )
_a : str = tokens + [tokenizer.unk_token]
_a : List[str] = [0, 1, 2, 4, 5, 1, 0, 3, 6]
self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , A__ )
| 14 |
'''simple docstring'''
import argparse
import torch
from huggingface_hub import hf_hub_download
from transformers import AutoTokenizer, RobertaPreLayerNormConfig, RobertaPreLayerNormForMaskedLM
from transformers.utils import logging
logging.set_verbosity_info()
__lowerCamelCase : Dict = logging.get_logger(__name__)
def UpperCAmelCase_ ( lowerCAmelCase_ , lowerCAmelCase_ ):
"""simple docstring"""
lowercase = RobertaPreLayerNormConfig.from_pretrained(
lowerCAmelCase_ , architectures=["RobertaPreLayerNormForMaskedLM"] )
# convert state_dict
lowercase = torch.load(hf_hub_download(repo_id=lowerCAmelCase_ , filename="pytorch_model.bin" ) )
lowercase = {}
for tensor_key, tensor_value in original_state_dict.items():
# The transformer implementation gives the model a unique name, rather than overwiriting 'roberta'
if tensor_key.startswith("roberta." ):
lowercase = "roberta_prelayernorm." + tensor_key[len("roberta." ) :]
# The original implementation contains weights which are not used, remove them from the state_dict
if tensor_key.endswith(".self.LayerNorm.weight" ) or tensor_key.endswith(".self.LayerNorm.bias" ):
continue
lowercase = tensor_value
lowercase = RobertaPreLayerNormForMaskedLM.from_pretrained(
pretrained_model_name_or_path=lowerCAmelCase_ , config=lowerCAmelCase_ , state_dict=lowerCAmelCase_ )
model.save_pretrained(lowerCAmelCase_ )
# convert tokenizer
lowercase = AutoTokenizer.from_pretrained(lowerCAmelCase_ )
tokenizer.save_pretrained(lowerCAmelCase_ )
if __name__ == "__main__":
__lowerCamelCase : Union[str, Any] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--checkpoint-repo",
default=None,
type=str,
required=True,
help="Path the official PyTorch dump, e.g. 'andreasmadsen/efficient_mlm_m0.40'.",
)
parser.add_argument(
"--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
)
__lowerCamelCase : str = parser.parse_args()
convert_roberta_prelayernorm_checkpoint_to_pytorch(args.checkpoint_repo, args.pytorch_dump_folder_path)
| 310 | 0 |
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import rescale, resize, to_channel_dimension_format
from ...image_utils import (
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
if is_vision_available():
import PIL
a_ : str = logging.get_logger(__name__)
def _SCREAMING_SNAKE_CASE ( snake_case_ : str , snake_case_ : Tuple ):
__magic_name__ = b.T
__magic_name__ = np.sum(np.square(__lowerCAmelCase ) , axis=1 )
__magic_name__ = np.sum(np.square(__lowerCAmelCase ) , axis=0 )
__magic_name__ = np.matmul(__lowerCAmelCase , __lowerCAmelCase )
__magic_name__ = aa[:, None] - 2 * ab + ba[None, :]
return d
def _SCREAMING_SNAKE_CASE ( snake_case_ : Optional[int] , snake_case_ : int ):
__magic_name__ = x.reshape(-1 , 3 )
__magic_name__ = squared_euclidean_distance(__lowerCAmelCase , __lowerCAmelCase )
return np.argmin(__lowerCAmelCase , axis=1 )
class SCREAMING_SNAKE_CASE_ ( __UpperCAmelCase ):
"""simple docstring"""
_a = ["""pixel_values"""]
def __init__( self , A = None , A = True , A = None , A = PILImageResampling.BILINEAR , A = True , A = True , **A , ) -> List[Any]:
'''simple docstring'''
super().__init__(**lowerCAmelCase_ )
__magic_name__ = size if size is not None else {'''height''': 2_56, '''width''': 2_56}
__magic_name__ = get_size_dict(lowerCAmelCase_ )
__magic_name__ = np.array(lowerCAmelCase_ ) if clusters is not None else None
__magic_name__ = do_resize
__magic_name__ = size
__magic_name__ = resample
__magic_name__ = do_normalize
__magic_name__ = do_color_quantize
def __A ( self , A , A , A = PILImageResampling.BILINEAR , A = None , **A , ) -> Tuple:
'''simple docstring'''
__magic_name__ = get_size_dict(lowerCAmelCase_ )
if "height" not in size or "width" not in size:
raise ValueError(F'Size dictionary must contain both height and width keys. Got {size.keys()}' )
return resize(
lowerCAmelCase_ , size=(size['''height'''], size['''width''']) , resample=lowerCAmelCase_ , data_format=lowerCAmelCase_ , **lowerCAmelCase_ )
def __A ( self , A , A = None , ) -> Tuple:
'''simple docstring'''
__magic_name__ = rescale(image=lowerCAmelCase_ , scale=1 / 1_27.5 , data_format=lowerCAmelCase_ )
__magic_name__ = image - 1
return image
def __A ( self , A , A = None , A = None , A = None , A = None , A = None , A = None , A = None , A = ChannelDimension.FIRST , **A , ) -> List[Any]:
'''simple docstring'''
__magic_name__ = do_resize if do_resize is not None else self.do_resize
__magic_name__ = size if size is not None else self.size
__magic_name__ = get_size_dict(lowerCAmelCase_ )
__magic_name__ = resample if resample is not None else self.resample
__magic_name__ = do_normalize if do_normalize is not None else self.do_normalize
__magic_name__ = do_color_quantize if do_color_quantize is not None else self.do_color_quantize
__magic_name__ = clusters if clusters is not None else self.clusters
__magic_name__ = np.array(lowerCAmelCase_ )
__magic_name__ = make_list_of_images(lowerCAmelCase_ )
if not valid_images(lowerCAmelCase_ ):
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_color_quantize and clusters is None:
raise ValueError('''Clusters must be specified if do_color_quantize is True.''' )
# All transformations expect numpy arrays.
__magic_name__ = [to_numpy_array(lowerCAmelCase_ ) for image in images]
if do_resize:
__magic_name__ = [self.resize(image=lowerCAmelCase_ , size=lowerCAmelCase_ , resample=lowerCAmelCase_ ) for image in images]
if do_normalize:
__magic_name__ = [self.normalize(image=lowerCAmelCase_ ) for image in images]
if do_color_quantize:
__magic_name__ = [to_channel_dimension_format(lowerCAmelCase_ , ChannelDimension.LAST ) for image in images]
# color quantize from (batch_size, height, width, 3) to (batch_size, height, width)
__magic_name__ = np.array(lowerCAmelCase_ )
__magic_name__ = color_quantize(lowerCAmelCase_ , lowerCAmelCase_ ).reshape(images.shape[:-1] )
# flatten to (batch_size, height*width)
__magic_name__ = images.shape[0]
__magic_name__ = images.reshape(lowerCAmelCase_ , -1 )
# We need to convert back to a list of images to keep consistent behaviour across processors.
__magic_name__ = list(lowerCAmelCase_ )
else:
__magic_name__ = [to_channel_dimension_format(lowerCAmelCase_ , lowerCAmelCase_ ) for image in images]
__magic_name__ = {'''input_ids''': images}
return BatchFeature(data=lowerCAmelCase_ , tensor_type=lowerCAmelCase_ ) | 712 |
import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile
import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load
try:
import torch
a_ : str = True
except ImportError:
a_ : Optional[int] = False
try:
from torch.hub import _get_torch_home
a_ : Optional[Any] = _get_torch_home()
except ImportError:
a_ : List[Any] = os.path.expanduser(
os.getenv('TORCH_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch'))
)
a_ : Any = os.path.join(torch_cache_home, 'transformers')
a_ : Any = 'https://cdn.huggingface.co'
a_ : Any = 'https://s3.amazonaws.com/models.huggingface.co/bert'
a_ : int = '/'.join(str(Path(__file__).resolve()).split('/')[:-1])
a_ : Any = os.path.join(PATH, 'config.yaml')
a_ : Any = os.path.join(PATH, 'attributes.txt')
a_ : Any = os.path.join(PATH, 'objects.txt')
a_ : List[Any] = os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', default_cache_path)
a_ : Any = os.getenv('PYTORCH_TRANSFORMERS_CACHE', PYTORCH_PRETRAINED_BERT_CACHE)
a_ : Optional[int] = os.getenv('TRANSFORMERS_CACHE', PYTORCH_TRANSFORMERS_CACHE)
a_ : int = 'pytorch_model.bin'
a_ : Union[str, Any] = 'config.yaml'
def _SCREAMING_SNAKE_CASE ( snake_case_ : Union[str, Any]=OBJECTS , snake_case_ : str=ATTRIBUTES ):
__magic_name__ = []
with open(snake_case_ ) as f:
for object in f.readlines():
vg_classes.append(object.split(''',''' )[0].lower().strip() )
__magic_name__ = []
with open(snake_case_ ) as f:
for object in f.readlines():
vg_attrs.append(object.split(''',''' )[0].lower().strip() )
return vg_classes, vg_attrs
def _SCREAMING_SNAKE_CASE ( snake_case_ : int ):
__magic_name__ = OrderedDict()
with open(snake_case_ , '''rb''' ) as f:
__magic_name__ = pkl.load(snake_case_ )['''model''']
for k in copy.deepcopy(list(ckp.keys() ) ):
__magic_name__ = ckp.pop(snake_case_ )
if isinstance(snake_case_ , np.ndarray ):
__magic_name__ = torch.tensor(snake_case_ )
else:
assert isinstance(snake_case_ , torch.tensor ), type(snake_case_ )
__magic_name__ = v
return r
class SCREAMING_SNAKE_CASE_ :
"""simple docstring"""
_a = {}
def __init__( self , A , A = "root" , A=0 ) -> List[str]:
'''simple docstring'''
__magic_name__ = name
__magic_name__ = level
__magic_name__ = {}
for k, v in dictionary.items():
if v is None:
raise ValueError()
__magic_name__ = copy.deepcopy(A )
__magic_name__ = copy.deepcopy(A )
if isinstance(A , A ):
__magic_name__ = Config(A , name=A , level=level + 1 )
__magic_name__ = v
setattr(self , A , A )
__magic_name__ = d
def __repr__( self ) -> Union[str, Any]:
'''simple docstring'''
return str(list((self._pointer.keys()) ) )
def __setattr__( self , A , A ) -> Tuple:
'''simple docstring'''
__magic_name__ = val
__magic_name__ = val
__magic_name__ = key.split('''.''' )
__magic_name__ = len(A ) - 1
__magic_name__ = self._pointer
if len(A ) > 1:
for i, l in enumerate(A ):
if hasattr(self , A ) and isinstance(getattr(self , A ) , A ):
setattr(getattr(self , A ) , '''.'''.join(levels[i:] ) , A )
if l == last_level:
__magic_name__ = val
else:
__magic_name__ = pointer[l]
def __A ( self ) -> List[Any]:
'''simple docstring'''
return self._pointer
def __A ( self , A , A ) -> Any:
'''simple docstring'''
with open(F'{file_name}' , '''w''' ) as stream:
dump(A , A )
def __A ( self , A , A ) -> List[Any]:
'''simple docstring'''
with open(F'{file_name}' , '''w''' ) as stream:
json.dump(A , A )
@staticmethod
def __A ( A ) -> Optional[Any]:
'''simple docstring'''
with open(A ) as stream:
__magic_name__ = load(A , Loader=A )
return data
def __str__( self ) -> List[Any]:
'''simple docstring'''
__magic_name__ = ''' '''
if self._name != "root":
__magic_name__ = F'{t * (self._level-1)}{self._name}:\n'
else:
__magic_name__ = ''''''
__magic_name__ = self._level
for i, (k, v) in enumerate(self._pointer.items() ):
if isinstance(A , A ):
r += F'{t * (self._level)}{v}\n'
self._level += 1
else:
r += F'{t * (self._level)}{k}: {v} ({type(A ).__name__})\n'
__magic_name__ = level
return r[:-1]
@classmethod
def __A ( cls , A , **A ) -> int:
'''simple docstring'''
__magic_name__ , __magic_name__ = cls.get_config_dict(A , **A )
return cls(A )
@classmethod
def __A ( cls , A , **A ) -> Union[str, Any]:
'''simple docstring'''
__magic_name__ = kwargs.pop('''cache_dir''' , A )
__magic_name__ = kwargs.pop('''force_download''' , A )
__magic_name__ = kwargs.pop('''resume_download''' , A )
__magic_name__ = kwargs.pop('''proxies''' , A )
__magic_name__ = kwargs.pop('''local_files_only''' , A )
if os.path.isdir(A ):
__magic_name__ = os.path.join(A , A )
elif os.path.isfile(A ) or is_remote_url(A ):
__magic_name__ = pretrained_model_name_or_path
else:
__magic_name__ = hf_bucket_url(A , filename=A , use_cdn=A )
try:
# Load from URL or cache if already cached
__magic_name__ = cached_path(
A , cache_dir=A , force_download=A , proxies=A , resume_download=A , local_files_only=A , )
# Load config dict
if resolved_config_file is None:
raise EnvironmentError
__magic_name__ = Config.load_yaml(A )
except EnvironmentError:
__magic_name__ = '''Can\'t load config for'''
raise EnvironmentError(A )
if resolved_config_file == config_file:
print('''loading configuration file from path''' )
else:
print('''loading configuration file cache''' )
return Config.load_yaml(A ), kwargs
def _SCREAMING_SNAKE_CASE ( snake_case_ : Tuple ):
__magic_name__ = torch.load('''dump.pt''' , map_location=in_tensor.device )
__magic_name__ = in_tensor.numpy()
__magic_name__ = out_tensor.numpy()[0]
print(na.shape , na[0, 0, :5] )
print(na.shape , na[0, 0, :5] )
assert np.allclose(snake_case_ , snake_case_ , rtol=0.01 , atol=0.1 ), (
f'{sum([1 for x in np.isclose(snake_case_ , snake_case_ , rtol=0.01 , atol=0.1 ).flatten() if x is False] )/len(na.flatten() )*100:.4f} %'
" element-wise mismatch"
)
raise Exception('''tensors are all good''' )
# Hugging face functions below
def _SCREAMING_SNAKE_CASE ( snake_case_ : List[Any] ):
__magic_name__ = urlparse(snake_case_ )
return parsed.scheme in ("http", "https")
def _SCREAMING_SNAKE_CASE ( snake_case_ : str , snake_case_ : str , snake_case_ : Optional[Any]=True ):
__magic_name__ = CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
__magic_name__ = '''/''' not in model_id
if legacy_format:
return f'{endpoint}/{model_id}-{filename}'
else:
return f'{endpoint}/{model_id}/{filename}'
def _SCREAMING_SNAKE_CASE ( snake_case_ : str , snake_case_ : Tuple , snake_case_ : List[str]=None , snake_case_ : Dict=0 , snake_case_ : Tuple=None , ):
__magic_name__ = '''python/{}'''.format(sys.version.split()[0] )
if _torch_available:
ua += "; torch/{}".format(torch.__version__ )
if isinstance(snake_case_ , snake_case_ ):
ua += "; " + "; ".join('''{}/{}'''.format(snake_case_ , snake_case_ ) for k, v in user_agent.items() )
elif isinstance(snake_case_ , snake_case_ ):
ua += "; " + user_agent
__magic_name__ = {'''user-agent''': ua}
if resume_size > 0:
__magic_name__ = '''bytes=%d-''' % (resume_size,)
__magic_name__ = requests.get(snake_case_ , stream=snake_case_ , proxies=snake_case_ , headers=snake_case_ )
if response.status_code == 416: # Range not satisfiable
return
__magic_name__ = response.headers.get('''Content-Length''' )
__magic_name__ = resume_size + int(snake_case_ ) if content_length is not None else None
__magic_name__ = tqdm(
unit='''B''' , unit_scale=snake_case_ , total=snake_case_ , initial=snake_case_ , desc='''Downloading''' , )
for chunk in response.iter_content(chunk_size=1024 ):
if chunk: # filter out keep-alive new chunks
progress.update(len(snake_case_ ) )
temp_file.write(snake_case_ )
progress.close()
def _SCREAMING_SNAKE_CASE ( snake_case_ : Any , snake_case_ : Dict=None , snake_case_ : int=False , snake_case_ : List[Any]=None , snake_case_ : Tuple=10 , snake_case_ : int=False , snake_case_ : Any=None , snake_case_ : Tuple=False , ):
if cache_dir is None:
__magic_name__ = TRANSFORMERS_CACHE
if isinstance(snake_case_ , snake_case_ ):
__magic_name__ = str(snake_case_ )
os.makedirs(snake_case_ , exist_ok=snake_case_ )
__magic_name__ = None
if not local_files_only:
try:
__magic_name__ = requests.head(snake_case_ , allow_redirects=snake_case_ , proxies=snake_case_ , timeout=snake_case_ )
if response.status_code == 200:
__magic_name__ = response.headers.get('''ETag''' )
except (EnvironmentError, requests.exceptions.Timeout):
# etag is already None
pass
__magic_name__ = url_to_filename(snake_case_ , snake_case_ )
# get cache path to put the file
__magic_name__ = os.path.join(snake_case_ , snake_case_ )
# etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
# try to get the last downloaded one
if etag is None:
if os.path.exists(snake_case_ ):
return cache_path
else:
__magic_name__ = [
file
for file in fnmatch.filter(os.listdir(snake_case_ ) , filename + '''.*''' )
if not file.endswith('''.json''' ) and not file.endswith('''.lock''' )
]
if len(snake_case_ ) > 0:
return os.path.join(snake_case_ , matching_files[-1] )
else:
# If files cannot be found and local_files_only=True,
# the models might've been found if local_files_only=False
# Notify the user about that
if local_files_only:
raise ValueError(
'''Cannot find the requested files in the cached path and outgoing traffic has been'''
''' disabled. To enable model look-ups and downloads online, set \'local_files_only\''''
''' to False.''' )
return None
# From now on, etag is not None.
if os.path.exists(snake_case_ ) and not force_download:
return cache_path
# Prevent parallel downloads of the same file with a lock.
__magic_name__ = cache_path + '''.lock'''
with FileLock(snake_case_ ):
# If the download just completed while the lock was activated.
if os.path.exists(snake_case_ ) and not force_download:
# Even if returning early like here, the lock will be released.
return cache_path
if resume_download:
__magic_name__ = cache_path + '''.incomplete'''
@contextmanager
def _resumable_file_manager():
with open(snake_case_ , '''a+b''' ) as f:
yield f
__magic_name__ = _resumable_file_manager
if os.path.exists(snake_case_ ):
__magic_name__ = os.stat(snake_case_ ).st_size
else:
__magic_name__ = 0
else:
__magic_name__ = partial(tempfile.NamedTemporaryFile , dir=snake_case_ , delete=snake_case_ )
__magic_name__ = 0
# Download to temporary file, then copy to cache dir once finished.
# Otherwise you get corrupt cache entries if the download gets interrupted.
with temp_file_manager() as temp_file:
print(
'''%s not found in cache or force_download set to True, downloading to %s''' , snake_case_ , temp_file.name , )
http_get(
snake_case_ , snake_case_ , proxies=snake_case_ , resume_size=snake_case_ , user_agent=snake_case_ , )
os.replace(temp_file.name , snake_case_ )
__magic_name__ = {'''url''': url, '''etag''': etag}
__magic_name__ = cache_path + '''.json'''
with open(snake_case_ , '''w''' ) as meta_file:
json.dump(snake_case_ , snake_case_ )
return cache_path
def _SCREAMING_SNAKE_CASE ( snake_case_ : Optional[int] , snake_case_ : List[Any]=None ):
__magic_name__ = url.encode('''utf-8''' )
__magic_name__ = shaaaa(snake_case_ )
__magic_name__ = url_hash.hexdigest()
if etag:
__magic_name__ = etag.encode('''utf-8''' )
__magic_name__ = shaaaa(snake_case_ )
filename += "." + etag_hash.hexdigest()
if url.endswith('''.h5''' ):
filename += ".h5"
return filename
def _SCREAMING_SNAKE_CASE ( snake_case_ : str , snake_case_ : str=None , snake_case_ : Tuple=False , snake_case_ : Union[str, Any]=None , snake_case_ : List[Any]=False , snake_case_ : Union[str, Any]=None , snake_case_ : List[str]=False , snake_case_ : Optional[int]=False , snake_case_ : Optional[int]=False , ):
if cache_dir is None:
__magic_name__ = TRANSFORMERS_CACHE
if isinstance(snake_case_ , snake_case_ ):
__magic_name__ = str(snake_case_ )
if isinstance(snake_case_ , snake_case_ ):
__magic_name__ = str(snake_case_ )
if is_remote_url(snake_case_ ):
# URL, so get it from the cache (downloading if necessary)
__magic_name__ = get_from_cache(
snake_case_ , cache_dir=snake_case_ , force_download=snake_case_ , proxies=snake_case_ , resume_download=snake_case_ , user_agent=snake_case_ , local_files_only=snake_case_ , )
elif os.path.exists(snake_case_ ):
# File, and it exists.
__magic_name__ = url_or_filename
elif urlparse(snake_case_ ).scheme == "":
# File, but it doesn't exist.
raise EnvironmentError('''file {} not found'''.format(snake_case_ ) )
else:
# Something unknown
raise ValueError('''unable to parse {} as a URL or as a local path'''.format(snake_case_ ) )
if extract_compressed_file:
if not is_zipfile(snake_case_ ) and not tarfile.is_tarfile(snake_case_ ):
return output_path
# Path where we extract compressed archives
# We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
__magic_name__ , __magic_name__ = os.path.split(snake_case_ )
__magic_name__ = output_file.replace('''.''' , '''-''' ) + '''-extracted'''
__magic_name__ = os.path.join(snake_case_ , snake_case_ )
if os.path.isdir(snake_case_ ) and os.listdir(snake_case_ ) and not force_extract:
return output_path_extracted
# Prevent parallel extractions
__magic_name__ = output_path + '''.lock'''
with FileLock(snake_case_ ):
shutil.rmtree(snake_case_ , ignore_errors=snake_case_ )
os.makedirs(snake_case_ )
if is_zipfile(snake_case_ ):
with ZipFile(snake_case_ , '''r''' ) as zip_file:
zip_file.extractall(snake_case_ )
zip_file.close()
elif tarfile.is_tarfile(snake_case_ ):
__magic_name__ = tarfile.open(snake_case_ )
tar_file.extractall(snake_case_ )
tar_file.close()
else:
raise EnvironmentError('''Archive format of {} could not be identified'''.format(snake_case_ ) )
return output_path_extracted
return output_path
def _SCREAMING_SNAKE_CASE ( snake_case_ : Dict , snake_case_ : int="," ):
assert isinstance(snake_case_ , snake_case_ )
if os.path.isfile(snake_case_ ):
with open(snake_case_ ) as f:
__magic_name__ = eval(f.read() )
else:
__magic_name__ = requests.get(snake_case_ )
try:
__magic_name__ = requests.json()
except Exception:
__magic_name__ = req.content.decode()
assert data is not None, "could not connect"
try:
__magic_name__ = eval(snake_case_ )
except Exception:
__magic_name__ = data.split('''\n''' )
req.close()
return data
def _SCREAMING_SNAKE_CASE ( snake_case_ : Optional[int] ):
__magic_name__ = requests.get(snake_case_ )
__magic_name__ = np.array(Image.open(BytesIO(response.content ) ) )
return img
def _SCREAMING_SNAKE_CASE ( snake_case_ : Union[str, Any] ):
__magic_name__ = url.split('''/''' )[-1]
if fn not in os.listdir(os.getcwd() ):
wget.download(snake_case_ )
with open(snake_case_ , '''rb''' ) as stream:
__magic_name__ = pkl.load(snake_case_ )
__magic_name__ = weights.pop('''model''' )
__magic_name__ = {}
for k, v in model.items():
__magic_name__ = torch.from_numpy(snake_case_ )
if "running_var" in k:
__magic_name__ = torch.tensor([0] )
__magic_name__ = k.replace('''running_var''' , '''num_batches_tracked''' )
__magic_name__ = zero
return new
def _SCREAMING_SNAKE_CASE ( ):
print(f'{os.path.abspath(os.path.join(snake_case_ , os.pardir ) )}/demo.ipynb' )
def _SCREAMING_SNAKE_CASE ( snake_case_ : str , snake_case_ : Tuple="RGB" ):
assert isinstance(snake_case_ , snake_case_ )
if os.path.isfile(snake_case_ ):
__magic_name__ = cva.imread(snake_case_ )
else:
__magic_name__ = get_image_from_url(snake_case_ )
assert img is not None, f'could not connect to: {im}'
__magic_name__ = cva.cvtColor(snake_case_ , cva.COLOR_BGR2RGB )
if input_format == "RGB":
__magic_name__ = img[:, :, ::-1]
return img
def _SCREAMING_SNAKE_CASE ( snake_case_ : Union[str, Any] , snake_case_ : Dict=1 ):
return (images[i : i + batch] for i in range(0 , len(snake_case_ ) , snake_case_ )) | 678 | 0 |
'''simple docstring'''
from __future__ import annotations
from random import random
class lowerCAmelCase :
def __init__( self , __SCREAMING_SNAKE_CASE = None ) -> Any:
'''simple docstring'''
__snake_case = value
__snake_case = random()
__snake_case = None
__snake_case = None
def __repr__( self ) -> str:
'''simple docstring'''
from pprint import pformat
if self.left is None and self.right is None:
return F'''\'{self.value}: {self.prior:.5}\''''
else:
return pformat(
{F'''{self.value}: {self.prior:.5}''': (self.left, self.right)} , indent=1 )
def __str__( self ) -> str:
'''simple docstring'''
__snake_case = str(self.value ) + ''' '''
__snake_case = str(self.left or '''''' )
__snake_case = str(self.right or '''''' )
return value + left + right
def _UpperCamelCase (_lowerCamelCase : Node | None , _lowerCamelCase : int )-> tuple[Node | None, Node | None]:
'''simple docstring'''
if root is None: # None tree is split into 2 Nones
return None, None
elif root.value is None:
return None, None
else:
if value < root.value:
__snake_case , __snake_case = split(root.left , _lowerCamelCase )
return left, root
else:
__snake_case , __snake_case = split(root.right , _lowerCamelCase )
return root, right
def _UpperCamelCase (_lowerCamelCase : Node | None , _lowerCamelCase : Node | None )-> Node | None:
'''simple docstring'''
if (not left) or (not right): # If one node is None, return the other
return left or right
elif left.prior < right.prior:
__snake_case = merge(left.right , _lowerCamelCase )
return left
else:
__snake_case = merge(_lowerCamelCase , right.left )
return right
def _UpperCamelCase (_lowerCamelCase : Node | None , _lowerCamelCase : int )-> Node | None:
'''simple docstring'''
__snake_case = Node(_lowerCamelCase )
__snake_case , __snake_case = split(_lowerCamelCase , _lowerCamelCase )
return merge(merge(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase )
def _UpperCamelCase (_lowerCamelCase : Node | None , _lowerCamelCase : int )-> Node | None:
'''simple docstring'''
__snake_case , __snake_case = split(_lowerCamelCase , value - 1 )
__snake_case , __snake_case = split(_lowerCamelCase , _lowerCamelCase )
return merge(_lowerCamelCase , _lowerCamelCase )
def _UpperCamelCase (_lowerCamelCase : Node | None )-> None:
'''simple docstring'''
if not root: # None
return
else:
inorder(root.left )
print(root.value , end=''',''' )
inorder(root.right )
def _UpperCamelCase (_lowerCamelCase : Node | None , _lowerCamelCase : str )-> Node | None:
'''simple docstring'''
for arg in args.split():
if arg[0] == "+":
__snake_case = insert(_lowerCamelCase , int(arg[1:] ) )
elif arg[0] == "-":
__snake_case = erase(_lowerCamelCase , int(arg[1:] ) )
else:
print('''Unknown command''' )
return root
def _UpperCamelCase ()-> None:
'''simple docstring'''
__snake_case = None
print(
'''enter numbers to create a tree, + value to add value into treap, '''
'''- value to erase all nodes with value. \'q\' to quit. ''' )
__snake_case = input()
while args != "q":
__snake_case = interact_treap(_lowerCamelCase , _lowerCamelCase )
print(_lowerCamelCase )
__snake_case = input()
print('''good by!''' )
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 24 |
'''simple docstring'''
def _UpperCamelCase (_lowerCamelCase : Optional[Any] )-> Dict:
'''simple docstring'''
__snake_case = []
__snake_case = []
__snake_case = {
'''^''': 3,
'''*''': 2,
'''/''': 2,
'''%''': 2,
'''+''': 1,
'''-''': 1,
} # Priority of each operator
__snake_case = len(_lowerCamelCase ) if (len(_lowerCamelCase ) > 7) else 7
# Print table header for output
print(
'''Symbol'''.center(8 ) , '''Stack'''.center(_lowerCamelCase ) , '''Postfix'''.center(_lowerCamelCase ) , sep=''' | ''' , )
print('''-''' * (print_width * 3 + 7) )
for x in infix:
if x.isalpha() or x.isdigit():
post_fix.append(_lowerCamelCase ) # if x is Alphabet / Digit, add it to Postfix
elif x == "(":
stack.append(_lowerCamelCase ) # if x is "(" push to Stack
elif x == ")": # if x is ")" pop stack until "(" is encountered
while stack[-1] != "(":
post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix
stack.pop()
else:
if len(_lowerCamelCase ) == 0:
stack.append(_lowerCamelCase ) # If stack is empty, push x to stack
else: # while priority of x is not > priority of element in the stack
while len(_lowerCamelCase ) > 0 and priority[x] <= priority[stack[-1]]:
post_fix.append(stack.pop() ) # pop stack & add to Postfix
stack.append(_lowerCamelCase ) # push x to stack
print(
x.center(8 ) , (''''''.join(_lowerCamelCase )).ljust(_lowerCamelCase ) , (''''''.join(_lowerCamelCase )).ljust(_lowerCamelCase ) , sep=''' | ''' , ) # Output in tabular format
while len(_lowerCamelCase ) > 0: # while stack is not empty
post_fix.append(stack.pop() ) # pop stack & add to Postfix
print(
''' '''.center(8 ) , (''''''.join(_lowerCamelCase )).ljust(_lowerCamelCase ) , (''''''.join(_lowerCamelCase )).ljust(_lowerCamelCase ) , sep=''' | ''' , ) # Output in tabular format
return "".join(_lowerCamelCase ) # return Postfix as str
def _UpperCamelCase (_lowerCamelCase : Optional[Any] )-> str:
'''simple docstring'''
__snake_case = list(infix[::-1] ) # reverse the infix equation
for i in range(len(_lowerCamelCase ) ):
if infix[i] == "(":
__snake_case = ''')''' # change "(" to ")"
elif infix[i] == ")":
__snake_case = '''(''' # change ")" to "("
return (infix_2_postfix(''''''.join(_lowerCamelCase ) ))[
::-1
] # call infix_2_postfix on Infix, return reverse of Postfix
if __name__ == "__main__":
UpperCAmelCase_ : Dict = input('''\nEnter an Infix Equation = ''') # Input an Infix equation
UpperCAmelCase_ : Optional[Any] = ''''''.join(Infix.split()) # Remove spaces from the input
print('''\n\t''', Infix, '''(Infix) -> ''', infix_2_prefix(Infix), '''(Prefix)''')
| 24 | 1 |
'''simple docstring'''
from typing import Optional
import numpy as np
import torch
from torch import nn
from transformers import GPTaConfig, GPTaLMHeadModel
from transformers.modeling_utils import ModuleUtilsMixin
from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin
class SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
snake_case__ = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
@register_to_config
def __init__( self : Optional[int] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[int] = None , __SCREAMING_SNAKE_CASE : int = 5_0257 , __SCREAMING_SNAKE_CASE : int = 1024 , __SCREAMING_SNAKE_CASE : int = 768 , __SCREAMING_SNAKE_CASE : int = 12 , __SCREAMING_SNAKE_CASE : int = 12 , __SCREAMING_SNAKE_CASE : Optional[int] = None , __SCREAMING_SNAKE_CASE : str = "gelu_new" , __SCREAMING_SNAKE_CASE : float = 0.1 , __SCREAMING_SNAKE_CASE : float = 0.1 , __SCREAMING_SNAKE_CASE : float = 0.1 , __SCREAMING_SNAKE_CASE : float = 1e-5 , __SCREAMING_SNAKE_CASE : float = 0.02 , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : bool = True , __SCREAMING_SNAKE_CASE : bool = False , __SCREAMING_SNAKE_CASE : bool = False , ) -> List[Any]:
super().__init__()
a_ : Optional[Any] = prefix_length
if prefix_inner_dim != n_embd and prefix_hidden_dim is None:
raise ValueError(
f'`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and'
f' `n_embd`: {n_embd} are not equal.' )
a_ : str = prefix_inner_dim
a_ : Optional[Any] = prefix_hidden_dim
a_ : List[str] = (
nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim )
if self.prefix_hidden_dim is not None
else nn.Identity()
)
a_ : List[Any] = (
nn.Linear(self.prefix_hidden_dim , __SCREAMING_SNAKE_CASE ) if self.prefix_hidden_dim is not None else nn.Identity()
)
a_ : Union[str, Any] = GPTaConfig(
vocab_size=__SCREAMING_SNAKE_CASE , n_positions=__SCREAMING_SNAKE_CASE , n_embd=__SCREAMING_SNAKE_CASE , n_layer=__SCREAMING_SNAKE_CASE , n_head=__SCREAMING_SNAKE_CASE , n_inner=__SCREAMING_SNAKE_CASE , activation_function=__SCREAMING_SNAKE_CASE , resid_pdrop=__SCREAMING_SNAKE_CASE , embd_pdrop=__SCREAMING_SNAKE_CASE , attn_pdrop=__SCREAMING_SNAKE_CASE , layer_norm_epsilon=__SCREAMING_SNAKE_CASE , initializer_range=__SCREAMING_SNAKE_CASE , scale_attn_weights=__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE , scale_attn_by_inverse_layer_idx=__SCREAMING_SNAKE_CASE , reorder_and_upcast_attn=__SCREAMING_SNAKE_CASE , )
a_ : Tuple = GPTaLMHeadModel(__SCREAMING_SNAKE_CASE )
def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : torch.Tensor , __SCREAMING_SNAKE_CASE : torch.Tensor , __SCREAMING_SNAKE_CASE : Optional[torch.Tensor] = None , __SCREAMING_SNAKE_CASE : Optional[torch.Tensor] = None , ) -> List[Any]:
a_ : Any = self.transformer.transformer.wte(__SCREAMING_SNAKE_CASE )
a_ : Dict = self.encode_prefix(__SCREAMING_SNAKE_CASE )
a_ : Tuple = self.decode_prefix(__SCREAMING_SNAKE_CASE )
a_ : List[str] = torch.cat((prefix_embeds, embedding_text) , dim=1 )
if labels is not None:
a_ : List[str] = self.get_dummy_token(input_ids.shape[0] , input_ids.device )
a_ : int = torch.cat((dummy_token, input_ids) , dim=1 )
a_ : Dict = self.transformer(inputs_embeds=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE )
if self.prefix_hidden_dim is not None:
return out, hidden
else:
return out
def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : torch.device ) -> torch.Tensor:
return torch.zeros(__SCREAMING_SNAKE_CASE , self.prefix_length , dtype=torch.intaa , device=__SCREAMING_SNAKE_CASE )
def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : List[str] ) -> Any:
return self.encode_prefix(__SCREAMING_SNAKE_CASE )
@torch.no_grad()
def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ) -> Dict:
a_ : Dict = torch.split(__SCREAMING_SNAKE_CASE , 1 , dim=0 )
a_ : str = []
a_ : Optional[int] = []
for feature in features:
a_ : str = self.decode_prefix(feature.to(__SCREAMING_SNAKE_CASE ) ) # back to the clip feature
# Only support beam search for now
a_ , a_ : List[Any] = self.generate_beam(
input_embeds=__SCREAMING_SNAKE_CASE , device=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE )
generated_tokens.append(output_tokens[0] )
generated_seq_lengths.append(seq_lengths[0] )
a_ : Dict = torch.stack(__SCREAMING_SNAKE_CASE )
a_ : List[str] = torch.stack(__SCREAMING_SNAKE_CASE )
return generated_tokens, generated_seq_lengths
@torch.no_grad()
def SCREAMING_SNAKE_CASE ( self : Tuple , __SCREAMING_SNAKE_CASE : str=None , __SCREAMING_SNAKE_CASE : List[Any]=None , __SCREAMING_SNAKE_CASE : List[Any]=None , __SCREAMING_SNAKE_CASE : int = 5 , __SCREAMING_SNAKE_CASE : int = 67 , __SCREAMING_SNAKE_CASE : float = 1.0 , __SCREAMING_SNAKE_CASE : Optional[int] = None , ) -> Dict:
a_ : int = eos_token_id
a_ : Dict = None
a_ : Dict = None
a_ : List[Any] = torch.ones(__SCREAMING_SNAKE_CASE , device=__SCREAMING_SNAKE_CASE , dtype=torch.int )
a_ : Any = torch.zeros(__SCREAMING_SNAKE_CASE , device=__SCREAMING_SNAKE_CASE , dtype=torch.bool )
if input_embeds is not None:
a_ : Tuple = input_embeds
else:
a_ : Dict = self.transformer.transformer.wte(__SCREAMING_SNAKE_CASE )
for i in range(__SCREAMING_SNAKE_CASE ):
a_ : Tuple = self.transformer(inputs_embeds=__SCREAMING_SNAKE_CASE )
a_ : Tuple = outputs.logits
a_ : Union[str, Any] = logits[:, -1, :] / (temperature if temperature > 0 else 1.0)
a_ : Optional[Any] = logits.softmax(-1 ).log()
if scores is None:
a_ , a_ : Optional[Any] = logits.topk(__SCREAMING_SNAKE_CASE , -1 )
a_ : Dict = generated.expand(__SCREAMING_SNAKE_CASE , *generated.shape[1:] )
a_ , a_ : List[str] = next_tokens.permute(1 , 0 ), scores.squeeze(0 )
if tokens is None:
a_ : Optional[int] = next_tokens
else:
a_ : int = tokens.expand(__SCREAMING_SNAKE_CASE , *tokens.shape[1:] )
a_ : Tuple = torch.cat((tokens, next_tokens) , dim=1 )
else:
a_ : List[Any] = -float(np.inf )
a_ : Tuple = 0
a_ : List[Any] = scores[:, None] + logits
seq_lengths[~is_stopped] += 1
a_ : str = scores_sum / seq_lengths[:, None]
a_ , a_ : List[str] = scores_sum_average.view(-1 ).topk(__SCREAMING_SNAKE_CASE , -1 )
a_ : str = next_tokens // scores_sum.shape[1]
a_ : int = seq_lengths[next_tokens_source]
a_ : Tuple = next_tokens % scores_sum.shape[1]
a_ : List[str] = next_tokens.unsqueeze(1 )
a_ : Tuple = tokens[next_tokens_source]
a_ : Dict = torch.cat((tokens, next_tokens) , dim=1 )
a_ : Tuple = generated[next_tokens_source]
a_ : int = scores_sum_average * seq_lengths
a_ : int = is_stopped[next_tokens_source]
a_ : Optional[int] = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 )
a_ : Optional[Any] = torch.cat((generated, next_token_embed) , dim=1 )
a_ : List[str] = is_stopped + next_tokens.eq(__SCREAMING_SNAKE_CASE ).squeeze()
if is_stopped.all():
break
a_ : Optional[Any] = scores / seq_lengths
a_ : str = scores.argsort(descending=__SCREAMING_SNAKE_CASE )
# tokens tensors are already padded to max_seq_length
a_ : List[str] = [tokens[i] for i in order]
a_ : str = torch.stack(__SCREAMING_SNAKE_CASE , dim=0 )
a_ : List[Any] = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype )
return output_texts, seq_lengths
| 666 |
'''simple docstring'''
import requests
from bsa import BeautifulSoup
def _UpperCAmelCase ( __A : str , __A : dict ):
a_ : Tuple = BeautifulSoup(requests.get(__A , params=__A ).content , '''html.parser''' )
a_ : List[str] = soup.find('''div''' , attrs={'''class''': '''gs_ri'''} )
a_ : List[str] = div.find('''div''' , attrs={'''class''': '''gs_fl'''} ).find_all('''a''' )
return anchors[2].get_text()
if __name__ == "__main__":
__lowerCAmelCase = {
'title': (
'Precisely geometry controlled microsupercapacitors for ultrahigh areal '
'capacitance, volumetric capacitance, and energy density'
),
'journal': 'Chem. Mater.',
'volume': 30,
'pages': '3979-3990',
'year': 2_018,
'hl': 'en',
}
print(get_citation('https://scholar.google.com/scholar_lookup', params=params))
| 666 | 1 |
import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union
import pandas as pd
import pyarrow as pa
import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal
snake_case = datasets.utils.logging.get_logger(__name__)
snake_case = ['names', 'prefix']
snake_case = ['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols']
snake_case = ['encoding_errors', 'on_bad_lines']
snake_case = ['date_format']
@dataclass
class SCREAMING_SNAKE_CASE ( datasets.BuilderConfig ):
'''simple docstring'''
UpperCamelCase_ : Optional[Any] = ''','''
UpperCamelCase_ : str = None
UpperCamelCase_ : List[str] = '''infer'''
UpperCamelCase_ : List[Any] = None
UpperCamelCase_ : str = None
UpperCamelCase_ : Any = None
UpperCamelCase_ : List[Any] = None
UpperCamelCase_ : List[Any] = None
UpperCamelCase_ : List[Any] = True
UpperCamelCase_ : Tuple = None
UpperCamelCase_ : Tuple = None
UpperCamelCase_ : Tuple = None
UpperCamelCase_ : Optional[int] = None
UpperCamelCase_ : Any = False
UpperCamelCase_ : Tuple = None
UpperCamelCase_ : Dict = None
UpperCamelCase_ : Any = None
UpperCamelCase_ : List[Any] = True
UpperCamelCase_ : Union[str, Any] = True
UpperCamelCase_ : Optional[int] = False
UpperCamelCase_ : Dict = True
UpperCamelCase_ : List[Any] = None
UpperCamelCase_ : List[str] = '''.'''
UpperCamelCase_ : Any = None
UpperCamelCase_ : List[str] = '''"'''
UpperCamelCase_ : Union[str, Any] = 0
UpperCamelCase_ : List[str] = None
UpperCamelCase_ : Optional[Any] = None
UpperCamelCase_ : List[str] = None
UpperCamelCase_ : Optional[Any] = None
UpperCamelCase_ : Optional[Any] = True
UpperCamelCase_ : int = True
UpperCamelCase_ : str = 0
UpperCamelCase_ : str = True
UpperCamelCase_ : List[Any] = False
UpperCamelCase_ : str = None
UpperCamelCase_ : List[Any] = 1_0_0_0_0
UpperCamelCase_ : Tuple = None
UpperCamelCase_ : List[Any] = '''strict'''
UpperCamelCase_ : Any = '''error'''
UpperCamelCase_ : Tuple = None
def _A ( self : Any ):
if self.delimiter is not None:
SCREAMING_SNAKE_CASE : Union[str, Any] = self.delimiter
if self.column_names is not None:
SCREAMING_SNAKE_CASE : Union[str, Any] = self.column_names
@property
def _A ( self : Optional[Any] ):
SCREAMING_SNAKE_CASE : List[str] = {
"sep": self.sep,
"header": self.header,
"names": self.names,
"index_col": self.index_col,
"usecols": self.usecols,
"prefix": self.prefix,
"mangle_dupe_cols": self.mangle_dupe_cols,
"engine": self.engine,
"converters": self.converters,
"true_values": self.true_values,
"false_values": self.false_values,
"skipinitialspace": self.skipinitialspace,
"skiprows": self.skiprows,
"nrows": self.nrows,
"na_values": self.na_values,
"keep_default_na": self.keep_default_na,
"na_filter": self.na_filter,
"verbose": self.verbose,
"skip_blank_lines": self.skip_blank_lines,
"thousands": self.thousands,
"decimal": self.decimal,
"lineterminator": self.lineterminator,
"quotechar": self.quotechar,
"quoting": self.quoting,
"escapechar": self.escapechar,
"comment": self.comment,
"encoding": self.encoding,
"dialect": self.dialect,
"error_bad_lines": self.error_bad_lines,
"warn_bad_lines": self.warn_bad_lines,
"skipfooter": self.skipfooter,
"doublequote": self.doublequote,
"memory_map": self.memory_map,
"float_precision": self.float_precision,
"chunksize": self.chunksize,
"encoding_errors": self.encoding_errors,
"on_bad_lines": self.on_bad_lines,
"date_format": self.date_format,
}
# some kwargs must not be passed if they don't have a default value
# some others are deprecated and we can also not pass them if they are the default value
for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , a__ ):
del pd_read_csv_kwargs[pd_read_csv_parameter]
# Remove 2.0 new arguments
if not (datasets.config.PANDAS_VERSION.major >= 2):
for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
del pd_read_csv_kwargs[pd_read_csv_parameter]
# Remove 1.3 new arguments
if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
del pd_read_csv_kwargs[pd_read_csv_parameter]
return pd_read_csv_kwargs
class SCREAMING_SNAKE_CASE ( datasets.ArrowBasedBuilder ):
'''simple docstring'''
UpperCamelCase_ : Union[str, Any] = CsvConfig
def _A ( self : Optional[int] ):
return datasets.DatasetInfo(features=self.config.features )
def _A ( self : int , UpperCAmelCase_ : List[str] ):
if not self.config.data_files:
raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}''' )
SCREAMING_SNAKE_CASE : int = dl_manager.download_and_extract(self.config.data_files )
if isinstance(a__ , (str, list, tuple) ):
SCREAMING_SNAKE_CASE : Any = data_files
if isinstance(a__ , a__ ):
SCREAMING_SNAKE_CASE : Dict = [files]
SCREAMING_SNAKE_CASE : Dict = [dl_manager.iter_files(a__ ) for file in files]
return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"files": files} )]
SCREAMING_SNAKE_CASE : int = []
for split_name, files in data_files.items():
if isinstance(a__ , a__ ):
SCREAMING_SNAKE_CASE : Any = [files]
SCREAMING_SNAKE_CASE : Dict = [dl_manager.iter_files(a__ ) for file in files]
splits.append(datasets.SplitGenerator(name=a__ , gen_kwargs={"files": files} ) )
return splits
def _A ( self : Any , UpperCAmelCase_ : pa.Table ):
if self.config.features is not None:
SCREAMING_SNAKE_CASE : Any = self.config.features.arrow_schema
if all(not require_storage_cast(a__ ) for feature in self.config.features.values() ):
# cheaper cast
SCREAMING_SNAKE_CASE : Any = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=a__ )
else:
# more expensive cast; allows str <-> int/float or str to Audio for example
SCREAMING_SNAKE_CASE : str = table_cast(a__ , a__ )
return pa_table
def _A ( self : Any , UpperCAmelCase_ : Tuple ):
SCREAMING_SNAKE_CASE : int = self.config.features.arrow_schema if self.config.features else None
# dtype allows reading an int column as str
SCREAMING_SNAKE_CASE : Any = (
{
name: dtype.to_pandas_dtype() if not require_storage_cast(a__ ) else object
for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() )
}
if schema is not None
else None
)
for file_idx, file in enumerate(itertools.chain.from_iterable(a__ ) ):
SCREAMING_SNAKE_CASE : Dict = pd.read_csv(a__ , iterator=a__ , dtype=a__ , **self.config.pd_read_csv_kwargs )
try:
for batch_idx, df in enumerate(a__ ):
SCREAMING_SNAKE_CASE : List[Any] = pa.Table.from_pandas(a__ )
# Uncomment for debugging (will print the Arrow table size and elements)
# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
yield (file_idx, batch_idx), self._cast_table(a__ )
except ValueError as e:
logger.error(f'''Failed to read file \'{file}\' with error {type(a__ )}: {e}''' )
raise
| 62 |
'''simple docstring'''
import pickle
import shutil
import tempfile
import unittest
from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin
a__ : str = get_tests_dir('fixtures/test_sentencepiece.model')
@require_sentencepiece
@require_tokenizers
class lowerCAmelCase__ ( UpperCAmelCase_ , unittest.TestCase ):
'''simple docstring'''
_lowerCamelCase =XGLMTokenizer
_lowerCamelCase =XGLMTokenizerFast
_lowerCamelCase =True
_lowerCamelCase =True
def __snake_case ( self : Optional[int] ):
super().setUp()
# We have a SentencePiece fixture for testing
UpperCAmelCase = XGLMTokenizer(a__ , keep_accents=a__ )
tokenizer.save_pretrained(self.tmpdirname )
def __snake_case ( self : List[Any] ):
UpperCAmelCase = '''<pad>'''
UpperCAmelCase = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(a__ ) , a__ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(a__ ) , a__ )
def __snake_case ( self : Tuple ):
UpperCAmelCase = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , '''<s>''' )
self.assertEqual(vocab_keys[1] , '''<pad>''' )
self.assertEqual(len(a__ ) , 1008 )
def __snake_case ( self : List[Any] ):
self.assertEqual(self.get_tokenizer().vocab_size , 1008 )
def __snake_case ( self : Optional[Any] ):
UpperCAmelCase = XGLMTokenizer(a__ , keep_accents=a__ )
UpperCAmelCase = tokenizer.tokenize('''This is a test''' )
self.assertListEqual(a__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(a__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , )
UpperCAmelCase = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' )
self.assertListEqual(
a__ , [
SPIECE_UNDERLINE + '''I''',
SPIECE_UNDERLINE + '''was''',
SPIECE_UNDERLINE + '''b''',
'''or''',
'''n''',
SPIECE_UNDERLINE + '''in''',
SPIECE_UNDERLINE + '''''',
'''9''',
'''2''',
'''0''',
'''0''',
'''0''',
''',''',
SPIECE_UNDERLINE + '''and''',
SPIECE_UNDERLINE + '''this''',
SPIECE_UNDERLINE + '''is''',
SPIECE_UNDERLINE + '''f''',
'''al''',
'''s''',
'''é''',
'''.''',
] , )
UpperCAmelCase = tokenizer.convert_tokens_to_ids(a__ )
self.assertListEqual(
a__ , [
value + tokenizer.fairseq_offset
for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]
] , )
UpperCAmelCase = tokenizer.convert_ids_to_tokens(a__ )
self.assertListEqual(
a__ , [
SPIECE_UNDERLINE + '''I''',
SPIECE_UNDERLINE + '''was''',
SPIECE_UNDERLINE + '''b''',
'''or''',
'''n''',
SPIECE_UNDERLINE + '''in''',
SPIECE_UNDERLINE + '''''',
'''<unk>''',
'''2''',
'''0''',
'''0''',
'''0''',
''',''',
SPIECE_UNDERLINE + '''and''',
SPIECE_UNDERLINE + '''this''',
SPIECE_UNDERLINE + '''is''',
SPIECE_UNDERLINE + '''f''',
'''al''',
'''s''',
'''<unk>''',
'''.''',
] , )
@cached_property
def __snake_case ( self : Optional[Any] ):
return XGLMTokenizer.from_pretrained('''facebook/xglm-564M''' )
def __snake_case ( self : Optional[int] ):
with tempfile.NamedTemporaryFile() as f:
shutil.copyfile(a__ , f.name )
UpperCAmelCase = XGLMTokenizer(f.name , keep_accents=a__ )
UpperCAmelCase = pickle.dumps(a__ )
pickle.loads(a__ )
def __snake_case ( self : Tuple ):
if not self.test_rust_tokenizer:
return
UpperCAmelCase = self.get_tokenizer()
UpperCAmelCase = self.get_rust_tokenizer()
UpperCAmelCase = '''I was born in 92000, and this is falsé.'''
UpperCAmelCase = tokenizer.tokenize(a__ )
UpperCAmelCase = rust_tokenizer.tokenize(a__ )
self.assertListEqual(a__ , a__ )
UpperCAmelCase = tokenizer.encode(a__ , add_special_tokens=a__ )
UpperCAmelCase = rust_tokenizer.encode(a__ , add_special_tokens=a__ )
self.assertListEqual(a__ , a__ )
UpperCAmelCase = self.get_rust_tokenizer()
UpperCAmelCase = tokenizer.encode(a__ )
UpperCAmelCase = rust_tokenizer.encode(a__ )
self.assertListEqual(a__ , a__ )
@slow
def __snake_case ( self : int ):
UpperCAmelCase = '''Hello World!'''
UpperCAmelCase = [2, 31227, 4447, 35]
self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) )
@slow
def __snake_case ( self : List[str] ):
UpperCAmelCase = (
'''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will'''
''' add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth'''
)
# fmt: off
UpperCAmelCase = [2, 1018, 67, 11, 1988, 2617, 5631, 278, 11, 3407, 48, 71630, 28085, 4, 3234, 157, 13, 6, 5, 6, 4, 3526, 768, 15, 659, 57, 298, 3983, 864, 129, 21, 6, 5, 13675, 377, 652, 7580, 10341, 155, 2817, 422, 1666, 7, 1674, 53, 113, 202277, 17892, 33, 60, 87, 4, 3234, 157, 61, 2667, 52376, 19, 88, 23, 735]
# fmt: on
self.assertListEqual(a__ , self.big_tokenizer.encode(a__ ) )
@slow
def __snake_case ( self : Any ):
# fmt: off
UpperCAmelCase = {
'''input_ids''': [[2, 108825, 1163, 15, 88010, 473, 15898, 157, 13672, 1857, 312, 8, 238021, 1163, 53, 13672, 1857, 312, 8, 53283, 182396, 8, 18566, 16, 36733, 4101, 8, 230, 244017, 122553, 7, 15, 132597, 4, 293, 12511, 7610, 4, 3414, 132597, 9, 4, 32361, 362, 4, 734, 28512, 32569, 18, 4, 32361, 26096, 14982, 73, 18715, 21433, 235261, 15, 492, 12427, 16, 53, 18715, 21433, 65454, 15, 23659, 563, 16, 278, 597, 2843, 595, 7931, 182396, 64186, 22, 886, 595, 132981, 53, 25540, 3449, 43982, 39901, 5951, 878, 330, 4, 27694, 80269, 312, 53, 6517, 11780, 611, 20408, 5], [2, 6, 132597, 67, 42897, 33, 592, 8, 163729, 25540, 361, 136997, 109514, 173230, 7, 501, 60, 102913, 196, 5631, 235, 63243, 473, 6, 231757, 74, 5277, 7905, 53, 3095, 37317, 22, 454, 183874, 5], [2, 268, 31298, 46530, 6, 132935, 43831, 7, 597, 32, 24, 3688, 9865, 5]],
'''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=a__ , model_name='''facebook/xglm-564M''' , padding=a__ , )
| 51 | 0 |
'''simple docstring'''
import os
from argparse import ArgumentParser
from typing import List
import torch.utils.data
from datasets import Dataset, IterableDataset
from datasets.distributed import split_dataset_by_node
a : List[str] = 4
a : List[str] = 3
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
pass
def __UpperCAmelCase ( _UpperCAmelCase : List[str] ) -> Any:
for shard in shards:
for i in range(UpperCAmelCase__ ):
yield {"i": i, "shard": shard}
def __UpperCAmelCase ( ) -> List[str]:
__snake_case = int(os.environ["RANK"] )
__snake_case = int(os.environ["WORLD_SIZE"] )
__snake_case = ArgumentParser()
parser.add_argument("--streaming" , type=UpperCAmelCase__ )
parser.add_argument("--local_rank" , type=UpperCAmelCase__ )
parser.add_argument("--num_workers" , type=UpperCAmelCase__ , default=0 )
__snake_case = parser.parse_args()
__snake_case = args.streaming
__snake_case = args.num_workers
__snake_case = {"shards": [F'''shard_{shard_idx}''' for shard_idx in range(UpperCAmelCase__ )]}
__snake_case = IterableDataset.from_generator(UpperCAmelCase__ , gen_kwargs=UpperCAmelCase__ )
if not streaming:
__snake_case = Dataset.from_list(list(UpperCAmelCase__ ) )
__snake_case = split_dataset_by_node(UpperCAmelCase__ , rank=UpperCAmelCase__ , world_size=UpperCAmelCase__ )
__snake_case = torch.utils.data.DataLoader(UpperCAmelCase__ , num_workers=UpperCAmelCase__ )
__snake_case = NUM_SHARDS * NUM_ITEMS_PER_SHARD
__snake_case = full_size // world_size
expected_local_size += int(rank < (full_size % world_size) )
__snake_case = sum(1 for _ in dataloader )
if local_size != expected_local_size:
raise FailedTestError(F'''local_size {local_size} != expected_local_size {expected_local_size}''' )
if __name__ == "__main__":
main()
| 715 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_torch_available,
)
a : str = {
'''configuration_gpt_bigcode''': ['''GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTBigCodeConfig'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : int = [
'''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 : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 680 | 0 |
from __future__ import annotations
def a__ ( lowercase__ , lowercase__ ):
'''simple docstring'''
UpperCAmelCase_ , UpperCAmelCase_ =position
UpperCAmelCase_ =[
(y + 1, x + 2),
(y - 1, x + 2),
(y + 1, x - 2),
(y - 1, x - 2),
(y + 2, x + 1),
(y + 2, x - 1),
(y - 2, x + 1),
(y - 2, x - 1),
]
UpperCAmelCase_ =[]
for position in positions:
UpperCAmelCase_ , UpperCAmelCase_ =position
if 0 <= y_test < n and 0 <= x_test < n:
permissible_positions.append(lowercase__ )
return permissible_positions
def a__ ( lowercase__ ):
'''simple docstring'''
return not any(elem == 0 for row in board for elem in row )
def a__ ( lowercase__ , lowercase__ , lowercase__ ):
'''simple docstring'''
if is_complete(lowercase__ ):
return True
for position in get_valid_pos(lowercase__ , len(lowercase__ ) ):
UpperCAmelCase_ , UpperCAmelCase_ =position
if board[y][x] == 0:
UpperCAmelCase_ =curr + 1
if open_knight_tour_helper(lowercase__ , lowercase__ , curr + 1 ):
return True
UpperCAmelCase_ =0
return False
def a__ ( lowercase__ ):
'''simple docstring'''
UpperCAmelCase_ =[[0 for i in range(lowercase__ )] for j in range(lowercase__ )]
for i in range(lowercase__ ):
for j in range(lowercase__ ):
UpperCAmelCase_ =1
if open_knight_tour_helper(lowercase__ , (i, j) , 1 ):
return board
UpperCAmelCase_ =0
UpperCAmelCase_ =F'Open Kight Tour cannot be performed on a board of size {n}'
raise ValueError(lowercase__ )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 54 |
import tempfile
import unittest
from transformers import AutoModelForSeqaSeqLM, AutoTokenizer
from transformers.testing_utils import (
is_torch_available,
require_optimum,
require_torch,
slow,
)
if is_torch_available():
import torch
@require_torch
@require_optimum
@slow
class lowerCamelCase ( unittest.TestCase ):
def snake_case__ ( self :List[Any] ) -> Optional[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = '''hf-internal-testing/tiny-random-t5'''
SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(lowercase )
SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained(lowercase )
SCREAMING_SNAKE_CASE = tokenizer('''This is me''' , return_tensors='''pt''' )
SCREAMING_SNAKE_CASE = model.to_bettertransformer()
self.assertTrue(any('''BetterTransformer''' in mod.__class__.__name__ for _, mod in model.named_modules() ) )
SCREAMING_SNAKE_CASE = model.generate(**lowercase )
SCREAMING_SNAKE_CASE = model.reverse_bettertransformer()
self.assertFalse(any('''BetterTransformer''' in mod.__class__.__name__ for _, mod in model.named_modules() ) )
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(lowercase )
SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained(lowercase )
self.assertFalse(
any('''BetterTransformer''' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) )
SCREAMING_SNAKE_CASE = model_reloaded.generate(**lowercase )
self.assertTrue(torch.allclose(lowercase , lowercase ) )
def snake_case__ ( self :Union[str, Any] ) -> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = '''hf-internal-testing/tiny-random-t5'''
SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained(lowercase )
SCREAMING_SNAKE_CASE = model.to_bettertransformer()
with tempfile.TemporaryDirectory() as tmpdirname:
with self.assertRaises(lowercase ):
model.save_pretrained(lowercase )
SCREAMING_SNAKE_CASE = model.reverse_bettertransformer()
model.save_pretrained(lowercase ) | 201 | 0 |
"""simple docstring"""
from math import factorial, radians
def _snake_case ( _snake_case : float , _snake_case : int = 18 , _snake_case : int = 10 ):
lowerCAmelCase : Optional[int] = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0)
# Converting from degrees to radians
lowerCAmelCase : Any = radians(_snake_case )
lowerCAmelCase : Any = angle_in_radians
lowerCAmelCase : List[Any] = 3
lowerCAmelCase : Optional[int] = -1
for _ in range(_snake_case ):
result += (b * (angle_in_radians**a)) / factorial(_snake_case )
lowerCAmelCase : str = -b # One positive term and the next will be negative and so on...
a += 2 # Increased by 2 for every term.
return round(_snake_case , _snake_case )
if __name__ == "__main__":
__import__('''doctest''').testmod()
| 706 |
"""simple docstring"""
import time
import unittest
from transformers import is_torch_available
from transformers.testing_utils import require_torch, torch_device
from ..test_modeling_common import ids_tensor
if is_torch_available():
import torch
from transformers.generation import (
MaxLengthCriteria,
MaxNewTokensCriteria,
MaxTimeCriteria,
StoppingCriteriaList,
validate_stopping_criteria,
)
@require_torch
class snake_case_( unittest.TestCase ):
def lowerCamelCase__ ( self : int , UpperCamelCase_ : int ):
lowerCAmelCase : str = 3
lowerCAmelCase : Tuple = 2_5_0
lowerCAmelCase : Optional[Any] = ids_tensor((batch_size, length) , UpperCamelCase_ )
lowerCAmelCase : Optional[Any] = torch.ones((batch_size, length) , device=UpperCamelCase_ , dtype=torch.float ) / length
return input_ids, scores
def lowerCamelCase__ ( self : Optional[Any] ):
lowerCAmelCase, lowerCAmelCase : Optional[int] = self._get_tensors(5 )
lowerCAmelCase : Union[str, Any] = StoppingCriteriaList(
[
MaxLengthCriteria(max_length=1_0 ),
MaxTimeCriteria(max_time=0.1 ),
] )
self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
lowerCAmelCase, lowerCAmelCase : List[str] = self._get_tensors(9 )
self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
lowerCAmelCase, lowerCAmelCase : Any = self._get_tensors(1_0 )
self.assertTrue(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
def lowerCamelCase__ ( self : Optional[Any] ):
lowerCAmelCase : Optional[Any] = MaxLengthCriteria(max_length=1_0 )
lowerCAmelCase, lowerCAmelCase : Optional[Any] = self._get_tensors(5 )
self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
lowerCAmelCase, lowerCAmelCase : List[str] = self._get_tensors(9 )
self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
lowerCAmelCase, lowerCAmelCase : str = self._get_tensors(1_0 )
self.assertTrue(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
def lowerCamelCase__ ( self : List[Any] ):
lowerCAmelCase : Optional[Any] = MaxNewTokensCriteria(start_length=5 , max_new_tokens=5 )
lowerCAmelCase, lowerCAmelCase : Optional[int] = self._get_tensors(5 )
self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
lowerCAmelCase, lowerCAmelCase : Union[str, Any] = self._get_tensors(9 )
self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
lowerCAmelCase, lowerCAmelCase : str = self._get_tensors(1_0 )
self.assertTrue(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
lowerCAmelCase : Dict = StoppingCriteriaList([criteria] )
self.assertEqual(criteria_list.max_length , 1_0 )
def lowerCamelCase__ ( self : Union[str, Any] ):
lowerCAmelCase, lowerCAmelCase : Tuple = self._get_tensors(5 )
lowerCAmelCase : List[str] = MaxTimeCriteria(max_time=0.1 )
self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
lowerCAmelCase : List[str] = MaxTimeCriteria(max_time=0.1 , initial_timestamp=time.time() - 0.2 )
self.assertTrue(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
def lowerCamelCase__ ( self : str ):
validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(1_0 )] ) , 1_0 )
with self.assertWarns(UpperCamelCase_ ):
validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(1_0 )] ) , 1_1 )
lowerCAmelCase : str = validate_stopping_criteria(StoppingCriteriaList() , 1_1 )
self.assertEqual(len(UpperCamelCase_ ) , 1 )
| 637 | 0 |
import unittest
from transformers import MobileBertConfig, is_torch_available
from transformers.models.auto import get_values
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 (
MODEL_FOR_PRETRAINING_MAPPING,
MobileBertForMaskedLM,
MobileBertForMultipleChoice,
MobileBertForNextSentencePrediction,
MobileBertForPreTraining,
MobileBertForQuestionAnswering,
MobileBertForSequenceClassification,
MobileBertForTokenClassification,
MobileBertModel,
)
class UpperCAmelCase :
def __init__( self : str , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : List[Any]=13 , lowerCAmelCase : Dict=7 , lowerCAmelCase : List[Any]=True , lowerCAmelCase : int=True , lowerCAmelCase : Dict=True , lowerCAmelCase : int=True , lowerCAmelCase : Dict=99 , lowerCAmelCase : Any=64 , lowerCAmelCase : int=32 , lowerCAmelCase : Union[str, Any]=5 , lowerCAmelCase : Tuple=4 , lowerCAmelCase : Optional[int]=37 , lowerCAmelCase : List[str]="gelu" , lowerCAmelCase : Tuple=0.1 , lowerCAmelCase : Any=0.1 , lowerCAmelCase : List[Any]=512 , lowerCAmelCase : List[Any]=16 , lowerCAmelCase : List[str]=2 , lowerCAmelCase : Tuple=0.02 , lowerCAmelCase : Union[str, Any]=3 , lowerCAmelCase : str=4 , lowerCAmelCase : List[str]=None , ):
lowercase : Optional[int] = parent
lowercase : Tuple = batch_size
lowercase : Dict = seq_length
lowercase : List[str] = is_training
lowercase : Dict = use_input_mask
lowercase : str = use_token_type_ids
lowercase : Dict = use_labels
lowercase : List[str] = vocab_size
lowercase : int = hidden_size
lowercase : Optional[int] = embedding_size
lowercase : str = num_hidden_layers
lowercase : str = num_attention_heads
lowercase : Optional[int] = intermediate_size
lowercase : Dict = hidden_act
lowercase : Any = hidden_dropout_prob
lowercase : Optional[int] = attention_probs_dropout_prob
lowercase : str = max_position_embeddings
lowercase : Tuple = type_vocab_size
lowercase : List[Any] = type_sequence_label_size
lowercase : Any = initializer_range
lowercase : int = num_labels
lowercase : str = num_choices
lowercase : int = scope
def _lowerCAmelCase ( self : str ):
lowercase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
lowercase : Tuple = None
if self.use_input_mask:
lowercase : List[Any] = random_attention_mask([self.batch_size, self.seq_length] )
lowercase : Tuple = None
if self.use_token_type_ids:
lowercase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
lowercase : Tuple = None
lowercase : Optional[int] = None
lowercase : Any = None
if self.use_labels:
lowercase : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size )
lowercase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
lowercase : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices )
lowercase : Optional[Any] = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def _lowerCAmelCase ( self : Optional[int] ):
return MobileBertConfig(
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 , embedding_size=self.embedding_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 _lowerCAmelCase ( self : Optional[int] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : List[Any] , lowerCAmelCase : int , lowerCAmelCase : str , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Dict ):
lowercase : List[Any] = MobileBertModel(config=SCREAMING_SNAKE_CASE__ )
model.to(SCREAMING_SNAKE_CASE__ )
model.eval()
lowercase : Any = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ )
lowercase : str = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ )
lowercase : Any = model(SCREAMING_SNAKE_CASE__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) )
def _lowerCAmelCase ( self : List[Any] , lowerCAmelCase : List[str] , lowerCAmelCase : int , lowerCAmelCase : Optional[int] , lowerCAmelCase : Optional[int] , lowerCAmelCase : Dict , lowerCAmelCase : Tuple , lowerCAmelCase : str ):
lowercase : Tuple = MobileBertForMaskedLM(config=SCREAMING_SNAKE_CASE__ )
model.to(SCREAMING_SNAKE_CASE__ )
model.eval()
lowercase : 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.vocab_size) )
def _lowerCAmelCase ( self : Optional[Any] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Dict , lowerCAmelCase : Tuple , lowerCAmelCase : int , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Optional[Any] ):
lowercase : Union[str, Any] = MobileBertForNextSentencePrediction(config=SCREAMING_SNAKE_CASE__ )
model.to(SCREAMING_SNAKE_CASE__ )
model.eval()
lowercase : 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, 2) )
def _lowerCAmelCase ( self : Optional[Any] , lowerCAmelCase : Tuple , lowerCAmelCase : Dict , lowerCAmelCase : Dict , lowerCAmelCase : int , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Dict , lowerCAmelCase : List[str] ):
lowercase : List[str] = MobileBertForPreTraining(config=SCREAMING_SNAKE_CASE__ )
model.to(SCREAMING_SNAKE_CASE__ )
model.eval()
lowercase : List[Any] = model(
SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , next_sentence_label=SCREAMING_SNAKE_CASE__ , )
self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) )
def _lowerCAmelCase ( self : Any , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Dict , lowerCAmelCase : List[Any] , lowerCAmelCase : Tuple , lowerCAmelCase : Optional[int] , lowerCAmelCase : int ):
lowercase : str = MobileBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE__ )
model.to(SCREAMING_SNAKE_CASE__ )
model.eval()
lowercase : Dict = 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 _lowerCAmelCase ( self : Union[str, Any] , lowerCAmelCase : str , lowerCAmelCase : Dict , lowerCAmelCase : Dict , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : int , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Optional[int] ):
lowercase : Union[str, Any] = self.num_labels
lowercase : int = MobileBertForSequenceClassification(SCREAMING_SNAKE_CASE__ )
model.to(SCREAMING_SNAKE_CASE__ )
model.eval()
lowercase : 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.num_labels) )
def _lowerCAmelCase ( self : List[Any] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Tuple , lowerCAmelCase : str , lowerCAmelCase : Optional[Any] , lowerCAmelCase : List[str] , lowerCAmelCase : Tuple , lowerCAmelCase : Optional[Any] ):
lowercase : Optional[Any] = self.num_labels
lowercase : Optional[int] = MobileBertForTokenClassification(config=SCREAMING_SNAKE_CASE__ )
model.to(SCREAMING_SNAKE_CASE__ )
model.eval()
lowercase : str = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def _lowerCAmelCase ( self : Any , lowerCAmelCase : Any , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : int , lowerCAmelCase : List[Any] , lowerCAmelCase : List[Any] , lowerCAmelCase : Dict ):
lowercase : Dict = self.num_choices
lowercase : List[str] = MobileBertForMultipleChoice(config=SCREAMING_SNAKE_CASE__ )
model.to(SCREAMING_SNAKE_CASE__ )
model.eval()
lowercase : Union[str, Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
lowercase : Union[str, Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
lowercase : Optional[int] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
lowercase : Tuple = 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 _lowerCAmelCase ( self : Optional[int] ):
lowercase : Dict = self.prepare_config_and_inputs()
(
lowercase
) : int = config_and_inputs
lowercase : Tuple = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
return config, inputs_dict
@require_torch
class UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase , unittest.TestCase ):
a__: Optional[int] = (
(
MobileBertModel,
MobileBertForMaskedLM,
MobileBertForMultipleChoice,
MobileBertForNextSentencePrediction,
MobileBertForPreTraining,
MobileBertForQuestionAnswering,
MobileBertForSequenceClassification,
MobileBertForTokenClassification,
)
if is_torch_available()
else ()
)
a__: List[Any] = (
{
"""feature-extraction""": MobileBertModel,
"""fill-mask""": MobileBertForMaskedLM,
"""question-answering""": MobileBertForQuestionAnswering,
"""text-classification""": MobileBertForSequenceClassification,
"""token-classification""": MobileBertForTokenClassification,
"""zero-shot""": MobileBertForSequenceClassification,
}
if is_torch_available()
else {}
)
a__: Any = True
def _lowerCAmelCase ( self : Any , lowerCAmelCase : Optional[Any] , lowerCAmelCase : int , lowerCAmelCase : str=False ):
lowercase : Optional[int] = super()._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_labels=SCREAMING_SNAKE_CASE__ )
if return_labels:
if model_class in get_values(SCREAMING_SNAKE_CASE__ ):
lowercase : List[str] = torch.zeros(
(self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ )
lowercase : Dict = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ )
return inputs_dict
def _lowerCAmelCase ( self : Union[str, Any] ):
lowercase : List[str] = MobileBertModelTester(self )
lowercase : int = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , hidden_size=37 )
def _lowerCAmelCase ( self : Union[str, Any] ):
self.config_tester.run_common_tests()
def _lowerCAmelCase ( self : Any ):
lowercase : Optional[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_model(*SCREAMING_SNAKE_CASE__ )
def _lowerCAmelCase ( self : int ):
lowercase : List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_masked_lm(*SCREAMING_SNAKE_CASE__ )
def _lowerCAmelCase ( self : Dict ):
lowercase : Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_multiple_choice(*SCREAMING_SNAKE_CASE__ )
def _lowerCAmelCase ( self : Optional[int] ):
lowercase : Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*SCREAMING_SNAKE_CASE__ )
def _lowerCAmelCase ( self : Optional[Any] ):
lowercase : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_pretraining(*SCREAMING_SNAKE_CASE__ )
def _lowerCAmelCase ( self : Tuple ):
lowercase : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_question_answering(*SCREAMING_SNAKE_CASE__ )
def _lowerCAmelCase ( self : Any ):
lowercase : List[str] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_sequence_classification(*SCREAMING_SNAKE_CASE__ )
def _lowerCAmelCase ( self : List[str] ):
lowercase : Optional[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_token_classification(*SCREAMING_SNAKE_CASE__ )
def lowerCamelCase_ ( UpperCAmelCase_ : Union[str, Any] ):
return torch.tensor(
__A , dtype=torch.long , device=__A , )
snake_case__ = 1e-3
@require_torch
@require_sentencepiece
@require_tokenizers
class UpperCAmelCase ( unittest.TestCase ):
@slow
def _lowerCAmelCase ( self : Union[str, Any] ):
lowercase : Any = MobileBertModel.from_pretrained('''google/mobilebert-uncased''' ).to(SCREAMING_SNAKE_CASE__ )
lowercase : int = _long_tensor([[101, 7110, 1005, 1056, 2023, 1_1333, 1_7413, 1029, 102]] )
with torch.no_grad():
lowercase : str = model(SCREAMING_SNAKE_CASE__ )[0]
lowercase : List[Any] = torch.Size((1, 9, 512) )
self.assertEqual(output.shape , SCREAMING_SNAKE_CASE__ )
lowercase : Optional[int] = torch.tensor(
[
[
[-2.473_6526E07, 8.269_1656E04, 1.652_1838E05],
[-5.754_1704E-01, 3.905_6022E00, 4.401_1507E00],
[2.604_7359E00, 1.567_7652E00, -1.732_4188E-01],
]
] , device=SCREAMING_SNAKE_CASE__ , )
# MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a
# ~1 difference, it's therefore not a good idea to measure using addition.
# Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the
# result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE
lowercase : Union[str, Any] = torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE )
lowercase : str = torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE )
self.assertTrue(lower_bound and upper_bound )
| 583 |
'''simple docstring'''
from __future__ import annotations
from typing import Any
def lowerCAmelCase_ ( __A : list ):
'''simple docstring'''
if not postfix_notation:
return 0
snake_case: List[str] = {'+', '-', '*', '/'}
snake_case: list[Any] = []
for token in postfix_notation:
if token in operations:
snake_case , snake_case: 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(__A ) )
return stack.pop()
if __name__ == "__main__":
import doctest
doctest.testmod() | 329 | 0 |
"""simple docstring"""
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
if TYPE_CHECKING:
from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType
_snake_case = logging.get_logger(__name__)
_snake_case = {
'''microsoft/deberta-v2-xlarge''': '''https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json''',
'''microsoft/deberta-v2-xxlarge''': '''https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json''',
'''microsoft/deberta-v2-xlarge-mnli''': (
'''https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json'''
),
'''microsoft/deberta-v2-xxlarge-mnli''': (
'''https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json'''
),
}
class _a ( _UpperCAmelCase ):
a_ : int = 'deberta-v2'
def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : List[str]=12_81_00 , SCREAMING_SNAKE_CASE__ : Optional[Any]=15_36 , SCREAMING_SNAKE_CASE__ : Dict=24 , SCREAMING_SNAKE_CASE__ : Tuple=24 , SCREAMING_SNAKE_CASE__ : Optional[int]=61_44 , SCREAMING_SNAKE_CASE__ : str="gelu" , SCREAMING_SNAKE_CASE__ : List[str]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=5_12 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : Dict=0.02 , SCREAMING_SNAKE_CASE__ : str=1e-7 , SCREAMING_SNAKE_CASE__ : List[str]=False , SCREAMING_SNAKE_CASE__ : Optional[Any]=-1 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : str="gelu" , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ):
super().__init__(**__UpperCamelCase )
lowerCamelCase__ = hidden_size
lowerCamelCase__ = num_hidden_layers
lowerCamelCase__ = num_attention_heads
lowerCamelCase__ = intermediate_size
lowerCamelCase__ = hidden_act
lowerCamelCase__ = hidden_dropout_prob
lowerCamelCase__ = attention_probs_dropout_prob
lowerCamelCase__ = max_position_embeddings
lowerCamelCase__ = type_vocab_size
lowerCamelCase__ = initializer_range
lowerCamelCase__ = relative_attention
lowerCamelCase__ = max_relative_positions
lowerCamelCase__ = pad_token_id
lowerCamelCase__ = position_biased_input
# Backwards compatibility
if type(__UpperCamelCase ) == str:
lowerCamelCase__ = [x.strip() for x in pos_att_type.lower().split('|' )]
lowerCamelCase__ = pos_att_type
lowerCamelCase__ = vocab_size
lowerCamelCase__ = layer_norm_eps
lowerCamelCase__ = kwargs.get('pooler_hidden_size' , __UpperCamelCase )
lowerCamelCase__ = pooler_dropout
lowerCamelCase__ = pooler_hidden_act
class _a ( _UpperCAmelCase ):
@property
def _UpperCamelCase ( self : int ):
if self.task == "multiple-choice":
lowerCamelCase__ = {0: 'batch', 1: 'choice', 2: 'sequence'}
else:
lowerCamelCase__ = {0: 'batch', 1: 'sequence'}
if self._config.type_vocab_size > 0:
return OrderedDict(
[('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis)] )
else:
return OrderedDict([('input_ids', dynamic_axis), ('attention_mask', dynamic_axis)] )
@property
def _UpperCamelCase ( self : Union[str, Any] ):
return 12
def _UpperCamelCase ( self : Any , SCREAMING_SNAKE_CASE__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional["TensorType"] = None , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : "PreTrainedTokenizerBase" = None , ):
lowerCamelCase__ = super().generate_dummy_inputs(preprocessor=__UpperCamelCase , framework=__UpperCamelCase )
if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs:
del dummy_inputs["token_type_ids"]
return dummy_inputs
| 719 |
"""simple docstring"""
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_funnel import FunnelTokenizer
_snake_case = logging.get_logger(__name__)
_snake_case = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
_snake_case = [
"small",
"small-base",
"medium",
"medium-base",
"intermediate",
"intermediate-base",
"large",
"large-base",
"xlarge",
"xlarge-base",
]
_snake_case = {
"vocab_file": {
"funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt",
"funnel-transformer/small-base": "https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt",
"funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt",
"funnel-transformer/medium-base": (
"https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt"
),
"funnel-transformer/intermediate": (
"https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt"
),
"funnel-transformer/intermediate-base": (
"https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt"
),
"funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt",
"funnel-transformer/large-base": "https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt",
"funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt",
"funnel-transformer/xlarge-base": (
"https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt"
),
},
"tokenizer_file": {
"funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json",
"funnel-transformer/small-base": (
"https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json"
),
"funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json",
"funnel-transformer/medium-base": (
"https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json"
),
"funnel-transformer/intermediate": (
"https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json"
),
"funnel-transformer/intermediate-base": (
"https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json"
),
"funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json",
"funnel-transformer/large-base": (
"https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json"
),
"funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json",
"funnel-transformer/xlarge-base": (
"https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json"
),
},
}
_snake_case = {f"""funnel-transformer/{name}""": 512 for name in _model_names}
_snake_case = {f"""funnel-transformer/{name}""": {"do_lower_case": True} for name in _model_names}
class _a ( SCREAMING_SNAKE_CASE_ ):
a_ : List[str] = VOCAB_FILES_NAMES
a_ : List[str] = PRETRAINED_VOCAB_FILES_MAP
a_ : Optional[int] = PRETRAINED_INIT_CONFIGURATION
a_ : List[str] = FunnelTokenizer
a_ : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
a_ : int = 2
def __init__( self : int , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Any="<unk>" , SCREAMING_SNAKE_CASE__ : List[Any]="<sep>" , SCREAMING_SNAKE_CASE__ : int="<pad>" , SCREAMING_SNAKE_CASE__ : Tuple="<cls>" , SCREAMING_SNAKE_CASE__ : Tuple="<mask>" , SCREAMING_SNAKE_CASE__ : Any="<s>" , SCREAMING_SNAKE_CASE__ : Tuple="</s>" , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Any=True , SCREAMING_SNAKE_CASE__ : str=None , SCREAMING_SNAKE_CASE__ : int="##" , **SCREAMING_SNAKE_CASE__ : Any , ):
super().__init__(
SCREAMING_SNAKE_CASE__ , tokenizer_file=SCREAMING_SNAKE_CASE__ , do_lower_case=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__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , clean_text=SCREAMING_SNAKE_CASE__ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ , wordpieces_prefix=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
lowerCamelCase__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() )
if (
normalizer_state.get('lowercase' , SCREAMING_SNAKE_CASE__ ) != do_lower_case
or normalizer_state.get('strip_accents' , SCREAMING_SNAKE_CASE__ ) != strip_accents
or normalizer_state.get('handle_chinese_chars' , SCREAMING_SNAKE_CASE__ ) != tokenize_chinese_chars
):
lowerCamelCase__ = getattr(SCREAMING_SNAKE_CASE__ , normalizer_state.pop('type' ) )
lowerCamelCase__ = do_lower_case
lowerCamelCase__ = strip_accents
lowerCamelCase__ = tokenize_chinese_chars
lowerCamelCase__ = normalizer_class(**SCREAMING_SNAKE_CASE__ )
lowerCamelCase__ = do_lower_case
def _UpperCamelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any]=None ):
lowerCamelCase__ = [self.cls_token_id] + token_ids_a + [self.sep_token_id]
if token_ids_a:
output += token_ids_a + [self.sep_token_id]
return output
def _UpperCamelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ):
lowerCamelCase__ = [self.sep_token_id]
lowerCamelCase__ = [self.cls_token_id]
if token_ids_a is None:
return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0]
return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def _UpperCamelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ):
lowerCamelCase__ = self._tokenizer.model.save(SCREAMING_SNAKE_CASE__ , name=SCREAMING_SNAKE_CASE__ )
return tuple(SCREAMING_SNAKE_CASE__ )
| 659 | 0 |
from typing import TYPE_CHECKING
from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available
from ...utils import OptionalDependencyNotAvailable
__lowercase : Union[str, Any] = {'''configuration_dpt''': ['''DPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DPTConfig''']}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowercase : List[str] = ['''DPTFeatureExtractor''']
__lowercase : Dict = ['''DPTImageProcessor''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowercase : List[Any] = [
'''DPT_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''DPTForDepthEstimation''',
'''DPTForSemanticSegmentation''',
'''DPTModel''',
'''DPTPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_dpt import DPTFeatureExtractor
from .image_processing_dpt import DPTImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_dpt import (
DPT_PRETRAINED_MODEL_ARCHIVE_LIST,
DPTForDepthEstimation,
DPTForSemanticSegmentation,
DPTModel,
DPTPreTrainedModel,
)
else:
import sys
__lowercase : Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 36 |
import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from timm import create_model
from timm.data import resolve_data_config
from timm.data.transforms_factory import create_transform
from transformers import BitConfig, BitForImageClassification, BitImageProcessor
from transformers.image_utils import PILImageResampling
from transformers.utils import logging
logging.set_verbosity_info()
__lowercase : Any = logging.get_logger(__name__)
def lowercase ( __A : Optional[Any] ) -> Dict:
'''simple docstring'''
snake_case : Dict = """huggingface/label-files"""
snake_case : int = """imagenet-1k-id2label.json"""
snake_case : Tuple = json.load(open(hf_hub_download(__A , __A , repo_type="""dataset""" ) , """r""" ) )
snake_case : Any = {int(__A ): v for k, v in idalabel.items()}
snake_case : Dict = {v: k for k, v in idalabel.items()}
snake_case : Any = """std_conv""" if """bit""" in model_name else False
# note that when using BiT as backbone for ViT-hybrid checkpoints,
# one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same",
# config.conv_layer = "std_conv_same"
snake_case : List[Any] = BitConfig(
conv_layer=__A , num_labels=1000 , idalabel=__A , labelaid=__A , )
return config
def lowercase ( __A : Optional[int] ) -> Union[str, Any]:
'''simple docstring'''
if "stem.conv" in name:
snake_case : List[str] = name.replace("""stem.conv""" , """bit.embedder.convolution""" )
if "blocks" in name:
snake_case : List[str] = name.replace("""blocks""" , """layers""" )
if "head.fc" in name:
snake_case : Optional[int] = name.replace("""head.fc""" , """classifier.1""" )
if name.startswith("""norm""" ):
snake_case : Optional[Any] = """bit.""" + name
if "bit" not in name and "classifier" not in name:
snake_case : Tuple = """bit.encoder.""" + name
return name
def lowercase ( ) -> Optional[int]:
'''simple docstring'''
snake_case : int = """http://images.cocodataset.org/val2017/000000039769.jpg"""
snake_case : Optional[Any] = Image.open(requests.get(__A , stream=__A ).raw )
return im
@torch.no_grad()
def lowercase ( __A : Any , __A : Union[str, Any] , __A : str=False ) -> Optional[int]:
'''simple docstring'''
snake_case : str = get_config(__A )
# load original model from timm
snake_case : Tuple = create_model(__A , pretrained=__A )
timm_model.eval()
# load state_dict of original model
snake_case : List[str] = timm_model.state_dict()
for key in state_dict.copy().keys():
snake_case : List[Any] = state_dict.pop(__A )
snake_case : Union[str, Any] = val.squeeze() if """head""" in key else val
# load HuggingFace model
snake_case : List[Any] = BitForImageClassification(__A )
model.eval()
model.load_state_dict(__A )
# create image processor
snake_case : Dict = create_transform(**resolve_data_config({} , model=__A ) )
snake_case : Optional[Any] = transform.transforms
snake_case : List[Any] = {
"""bilinear""": PILImageResampling.BILINEAR,
"""bicubic""": PILImageResampling.BICUBIC,
"""nearest""": PILImageResampling.NEAREST,
}
snake_case : Union[str, Any] = BitImageProcessor(
do_resize=__A , size={"""shortest_edge""": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=__A , crop_size={"""height""": timm_transforms[1].size[0], """width""": timm_transforms[1].size[1]} , do_normalize=__A , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , )
snake_case : Dict = prepare_img()
snake_case : List[str] = transform(__A ).unsqueeze(0 )
snake_case : int = processor(__A , return_tensors="""pt""" ).pixel_values
# verify pixel values
assert torch.allclose(__A , __A )
# verify logits
with torch.no_grad():
snake_case : Optional[int] = model(__A )
snake_case : Dict = outputs.logits
print("""Logits:""" , logits[0, :3] )
print("""Predicted class:""" , model.config.idalabel[logits.argmax(-1 ).item()] )
snake_case : int = timm_model(__A )
assert timm_logits.shape == outputs.logits.shape
assert torch.allclose(__A , outputs.logits , atol=1E-3 )
print("""Looks ok!""" )
if pytorch_dump_folder_path is not None:
Path(__A ).mkdir(exist_ok=__A )
print(f"""Saving model {model_name} and processor to {pytorch_dump_folder_path}""" )
model.save_pretrained(__A )
processor.save_pretrained(__A )
if push_to_hub:
print(f"""Pushing model {model_name} and processor to the hub""" )
model.push_to_hub(f"""ybelkada/{model_name}""" )
processor.push_to_hub(f"""ybelkada/{model_name}""" )
if __name__ == "__main__":
__lowercase : List[str] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--model_name''',
default='''resnetv2_50x1_bitm''',
type=str,
help='''Name of the BiT timm model you\'d like to convert.''',
)
parser.add_argument(
'''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.'''
)
parser.add_argument(
'''--push_to_hub''',
action='''store_true''',
help='''Whether to push the model to the hub.''',
)
__lowercase : Union[str, Any] = parser.parse_args()
convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 36 | 1 |
"""simple docstring"""
import tempfile
import unittest
from make_student import create_student_by_copying_alternating_layers
from transformers import AutoConfig
from transformers.file_utils import cached_property
from transformers.testing_utils import require_torch
lowercase__ = "sshleifer/bart-tiny-random"
lowercase__ = "patrickvonplaten/t5-tiny-random"
@require_torch
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
@cached_property
def lowerCAmelCase__(self ):
'''simple docstring'''
return AutoConfig.from_pretrained(_lowercase )
def lowerCAmelCase__(self ):
'''simple docstring'''
__a : Any = create_student_by_copying_alternating_layers(_lowercase , tempfile.mkdtemp() , e=1 , d=1 )
self.assertEqual(student.config.num_hidden_layers , 1 )
def lowerCAmelCase__(self ):
'''simple docstring'''
__a : Tuple = create_student_by_copying_alternating_layers(_lowercase , tempfile.mkdtemp() , e=1 , d=_lowercase )
def lowerCAmelCase__(self ):
'''simple docstring'''
__a : Optional[int] = create_student_by_copying_alternating_layers(_lowercase , tempfile.mkdtemp() , e=1 , d=_lowercase )
self.assertEqual(student.config.encoder_layers , 1 )
self.assertEqual(student.config.decoder_layers , self.teacher_config.encoder_layers )
def lowerCAmelCase__(self ):
'''simple docstring'''
__a : Tuple = create_student_by_copying_alternating_layers(_lowercase , tempfile.mkdtemp() , e=1 , d=1 )
self.assertEqual(student.config.encoder_layers , 1 )
self.assertEqual(student.config.decoder_layers , 1 )
def lowerCAmelCase__(self ):
'''simple docstring'''
with self.assertRaises(_lowercase ):
create_student_by_copying_alternating_layers(_lowercase , tempfile.mkdtemp() , e=_lowercase , d=_lowercase )
| 721 |
"""simple docstring"""
import unittest
from knapsack import knapsack as k
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def lowerCAmelCase__(self ):
'''simple docstring'''
__a : str = 0
__a : Optional[Any] = [0]
__a : int = [0]
__a : str = len(_lowercase )
self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 0 )
__a : int = [60]
__a : Union[str, Any] = [10]
__a : Tuple = len(_lowercase )
self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 0 )
def lowerCAmelCase__(self ):
'''simple docstring'''
__a : int = 3
__a : str = [1, 2, 3]
__a : Optional[Any] = [3, 2, 1]
__a : int = len(_lowercase )
self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 5 )
def lowerCAmelCase__(self ):
'''simple docstring'''
__a : Dict = 50
__a : Tuple = [60, 100, 120]
__a : List[str] = [10, 20, 30]
__a : Union[str, Any] = len(_lowercase )
self.assertEqual(k.knapsack(_lowercase , _lowercase , _lowercase , _lowercase ) , 220 )
if __name__ == "__main__":
unittest.main()
| 63 | 0 |
'''simple docstring'''
import logging
import os
from typing import List, TextIO, Union
from conllu import parse_incr
from utils_ner import InputExample, Split, TokenClassificationTask
__magic_name__ = logging.getLogger(__name__)
class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__( self : int ,_a : Any=-1 ):
'''simple docstring'''
A_ : Dict = label_idx
def _a ( self : Dict ,_a : Any ,_a : str ):
'''simple docstring'''
if isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ):
A_ : int = mode.value
A_ : Optional[int] = os.path.join(_SCREAMING_SNAKE_CASE ,f'{mode}.txt' )
A_ : List[Any] = 1
A_ : Optional[int] = []
with open(_SCREAMING_SNAKE_CASE ,encoding="""utf-8""" ) as f:
A_ : str = []
A_ : Optional[int] = []
for line in f:
if line.startswith("""-DOCSTART-""" ) or line == "" or line == "\n":
if words:
examples.append(InputExample(guid=f'{mode}-{guid_index}' ,words=_SCREAMING_SNAKE_CASE ,labels=_SCREAMING_SNAKE_CASE ) )
guid_index += 1
A_ : Dict = []
A_ : Tuple = []
else:
A_ : Union[str, Any] = line.split(""" """ )
words.append(splits[0] )
if len(_SCREAMING_SNAKE_CASE ) > 1:
labels.append(splits[self.label_idx].replace("""\n""" ,"""""" ) )
else:
# Examples could have no label for mode = "test"
labels.append("""O""" )
if words:
examples.append(InputExample(guid=f'{mode}-{guid_index}' ,words=_SCREAMING_SNAKE_CASE ,labels=_SCREAMING_SNAKE_CASE ) )
return examples
def _a ( self : Any ,_a : int ,_a : Optional[int] ,_a : str ):
'''simple docstring'''
A_ : Dict = 0
for line in test_input_reader:
if line.startswith("""-DOCSTART-""" ) or line == "" or line == "\n":
writer.write(_SCREAMING_SNAKE_CASE )
if not preds_list[example_id]:
example_id += 1
elif preds_list[example_id]:
A_ : int = line.split()[0] + """ """ + preds_list[example_id].pop(0 ) + """\n"""
writer.write(_SCREAMING_SNAKE_CASE )
else:
logger.warning("""Maximum sequence length exceeded: No prediction for \'%s\'.""" ,line.split()[0] )
def _a ( self : str ,_a : Dict ):
'''simple docstring'''
if path:
with open(_SCREAMING_SNAKE_CASE ,"""r""" ) as f:
A_ : Union[str, Any] = f.read().splitlines()
if "O" not in labels:
A_ : List[str] = ["""O"""] + labels
return labels
else:
return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"]
class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__( self : Optional[Any] ):
'''simple docstring'''
super().__init__(label_idx=-2 )
def _a ( self : str ,_a : Tuple ):
'''simple docstring'''
if path:
with open(_SCREAMING_SNAKE_CASE ,"""r""" ) as f:
A_ : Optional[int] = f.read().splitlines()
if "O" not in labels:
A_ : List[str] = ["""O"""] + labels
return labels
else:
return [
"O",
"B-ADVP",
"B-INTJ",
"B-LST",
"B-PRT",
"B-NP",
"B-SBAR",
"B-VP",
"B-ADJP",
"B-CONJP",
"B-PP",
"I-ADVP",
"I-INTJ",
"I-LST",
"I-PRT",
"I-NP",
"I-SBAR",
"I-VP",
"I-ADJP",
"I-CONJP",
"I-PP",
]
class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def _a ( self : List[Any] ,_a : List[str] ,_a : Dict ):
'''simple docstring'''
if isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ):
A_ : Union[str, Any] = mode.value
A_ : List[Any] = os.path.join(_SCREAMING_SNAKE_CASE ,f'{mode}.txt' )
A_ : Tuple = 1
A_ : Optional[Any] = []
with open(_SCREAMING_SNAKE_CASE ,encoding="""utf-8""" ) as f:
for sentence in parse_incr(_SCREAMING_SNAKE_CASE ):
A_ : int = []
A_ : Optional[int] = []
for token in sentence:
words.append(token["""form"""] )
labels.append(token["""upos"""] )
assert len(_SCREAMING_SNAKE_CASE ) == len(_SCREAMING_SNAKE_CASE )
if words:
examples.append(InputExample(guid=f'{mode}-{guid_index}' ,words=_SCREAMING_SNAKE_CASE ,labels=_SCREAMING_SNAKE_CASE ) )
guid_index += 1
return examples
def _a ( self : List[str] ,_a : Optional[int] ,_a : Optional[Any] ,_a : Optional[int] ):
'''simple docstring'''
A_ : Optional[Any] = 0
for sentence in parse_incr(_SCREAMING_SNAKE_CASE ):
A_ : int = preds_list[example_id]
A_ : List[str] = """"""
for token in sentence:
out += f'{token["form"]} ({token["upos"]}|{s_p.pop(0 )}) '
out += "\n"
writer.write(_SCREAMING_SNAKE_CASE )
example_id += 1
def _a ( self : List[str] ,_a : Any ):
'''simple docstring'''
if path:
with open(_SCREAMING_SNAKE_CASE ,"""r""" ) as f:
return f.read().splitlines()
else:
return [
"ADJ",
"ADP",
"ADV",
"AUX",
"CCONJ",
"DET",
"INTJ",
"NOUN",
"NUM",
"PART",
"PRON",
"PROPN",
"PUNCT",
"SCONJ",
"SYM",
"VERB",
"X",
]
| 665 |
from __future__ import annotations
def lowerCAmelCase__ ( a__: str , a__: str ) -> bool:
'''simple docstring'''
_UpperCAmelCase = get_failure_array(a__ )
# 2) Step through text searching for pattern
_UpperCAmelCase , _UpperCAmelCase = 0, 0 # index into text, pattern
while i < len(a__ ):
if pattern[j] == text[i]:
if j == (len(a__ ) - 1):
return True
j += 1
# if this is a prefix in our pattern
# just go back far enough to continue
elif j > 0:
_UpperCAmelCase = failure[j - 1]
continue
i += 1
return False
def lowerCAmelCase__ ( a__: str ) -> list[int]:
'''simple docstring'''
_UpperCAmelCase = [0]
_UpperCAmelCase = 0
_UpperCAmelCase = 1
while j < len(a__ ):
if pattern[i] == pattern[j]:
i += 1
elif i > 0:
_UpperCAmelCase = failure[i - 1]
continue
j += 1
failure.append(a__ )
return failure
if __name__ == "__main__":
# Test 1)
lowerCAmelCase__ :List[Any] = '''abc1abc12'''
lowerCAmelCase__ :Optional[int] = '''alskfjaldsabc1abc1abc12k23adsfabcabc'''
lowerCAmelCase__ :int = '''alskfjaldsk23adsfabcabc'''
assert kmp(pattern, texta) and not kmp(pattern, texta)
# Test 2)
lowerCAmelCase__ :List[str] = '''ABABX'''
lowerCAmelCase__ :int = '''ABABZABABYABABX'''
assert kmp(pattern, text)
# Test 3)
lowerCAmelCase__ :int = '''AAAB'''
lowerCAmelCase__ :Any = '''ABAAAAAB'''
assert kmp(pattern, text)
# Test 4)
lowerCAmelCase__ :Union[str, Any] = '''abcdabcy'''
lowerCAmelCase__ :Any = '''abcxabcdabxabcdabcdabcy'''
assert kmp(pattern, text)
# Test 5)
lowerCAmelCase__ :List[Any] = '''aabaabaaa'''
assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
| 618 | 0 |
def lowerCAmelCase_ ( snake_case_,snake_case_ ):
return x if y == 0 else greatest_common_divisor(lowerCamelCase_,x % y )
def lowerCAmelCase_ ( snake_case_,snake_case_ ):
return (x * y) // greatest_common_divisor(lowerCamelCase_,lowerCamelCase_ )
def lowerCAmelCase_ ( snake_case_ = 20 ):
_A : Any = 1
for i in range(1,n + 1 ):
_A : List[Any] = lcm(lowerCamelCase_,lowerCamelCase_ )
return g
if __name__ == "__main__":
print(f"""{solution() = }""")
| 701 |
import gc
import unittest
from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline
from transformers.pipelines import PipelineException
from transformers.testing_utils import (
is_pipeline_test,
is_torch_available,
nested_simplify,
require_tf,
require_torch,
require_torch_gpu,
slow,
)
from .test_pipelines_common import ANY
@is_pipeline_test
class lowercase ( unittest.TestCase ):
_a = MODEL_FOR_MASKED_LM_MAPPING
_a = TF_MODEL_FOR_MASKED_LM_MAPPING
def a__ ( self ) -> Tuple:
super().tearDown()
# clean-up as much as possible GPU memory occupied by PyTorch
gc.collect()
if is_torch_available():
import torch
torch.cuda.empty_cache()
@require_tf
def a__ ( self ) -> Any:
_A : Optional[Any] = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , top_k=2 , framework="""tf""" )
_A : Optional[int] = unmasker("""My name is <mask>""" )
self.assertEqual(
nested_simplify(_a , decimals=6 ) , [
{"""sequence""": """My name is grouped""", """score""": 2.1e-05, """token""": 3_8015, """token_str""": """ grouped"""},
{"""sequence""": """My name is accuser""", """score""": 2.1e-05, """token""": 2_5506, """token_str""": """ accuser"""},
] , )
_A : Tuple = unmasker("""The largest city in France is <mask>""" )
self.assertEqual(
nested_simplify(_a , decimals=6 ) , [
{
"""sequence""": """The largest city in France is grouped""",
"""score""": 2.1e-05,
"""token""": 3_8015,
"""token_str""": """ grouped""",
},
{
"""sequence""": """The largest city in France is accuser""",
"""score""": 2.1e-05,
"""token""": 2_5506,
"""token_str""": """ accuser""",
},
] , )
_A : List[str] = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3 )
self.assertEqual(
nested_simplify(_a , decimals=6 ) , [
{"""sequence""": """My name is Clara""", """score""": 2e-05, """token""": 1_3606, """token_str""": """ Clara"""},
{"""sequence""": """My name is Patrick""", """score""": 2e-05, """token""": 3499, """token_str""": """ Patrick"""},
{"""sequence""": """My name is Te""", """score""": 1.9e-05, """token""": 2941, """token_str""": """ Te"""},
] , )
@require_torch
def a__ ( self ) -> str:
_A : Any = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , top_k=2 , framework="""pt""" )
_A : List[Any] = unmasker("""My name is <mask>""" )
self.assertEqual(
nested_simplify(_a , decimals=6 ) , [
{"""sequence""": """My name is Maul""", """score""": 2.2e-05, """token""": 3_5676, """token_str""": """ Maul"""},
{"""sequence""": """My name isELS""", """score""": 2.2e-05, """token""": 1_6416, """token_str""": """ELS"""},
] , )
_A : Optional[Any] = unmasker("""The largest city in France is <mask>""" )
self.assertEqual(
nested_simplify(_a , decimals=6 ) , [
{
"""sequence""": """The largest city in France is Maul""",
"""score""": 2.2e-05,
"""token""": 3_5676,
"""token_str""": """ Maul""",
},
{"""sequence""": """The largest city in France isELS""", """score""": 2.2e-05, """token""": 1_6416, """token_str""": """ELS"""},
] , )
_A : Optional[int] = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3 )
self.assertEqual(
nested_simplify(_a , decimals=6 ) , [
{"""sequence""": """My name is Patrick""", """score""": 2.1e-05, """token""": 3499, """token_str""": """ Patrick"""},
{"""sequence""": """My name is Te""", """score""": 2e-05, """token""": 2941, """token_str""": """ Te"""},
{"""sequence""": """My name is Clara""", """score""": 2e-05, """token""": 1_3606, """token_str""": """ Clara"""},
] , )
_A : str = unmasker("""My name is <mask> <mask>""" , top_k=2 )
self.assertEqual(
nested_simplify(_a , decimals=6 ) , [
[
{
"""score""": 2.2e-05,
"""token""": 3_5676,
"""token_str""": """ Maul""",
"""sequence""": """<s>My name is Maul<mask></s>""",
},
{"""score""": 2.2e-05, """token""": 1_6416, """token_str""": """ELS""", """sequence""": """<s>My name isELS<mask></s>"""},
],
[
{
"""score""": 2.2e-05,
"""token""": 3_5676,
"""token_str""": """ Maul""",
"""sequence""": """<s>My name is<mask> Maul</s>""",
},
{"""score""": 2.2e-05, """token""": 1_6416, """token_str""": """ELS""", """sequence""": """<s>My name is<mask>ELS</s>"""},
],
] , )
@require_torch_gpu
def a__ ( self ) -> Union[str, Any]:
_A : int = pipeline("""fill-mask""" , model="""hf-internal-testing/tiny-random-distilbert""" , device=0 , framework="""pt""" )
# convert model to fp16
pipe.model.half()
_A : Optional[Any] = pipe("""Paris is the [MASK] of France.""" )
# We actually don't care about the result, we just want to make sure
# it works, meaning the float16 tensor got casted back to float32
# for postprocessing.
self.assertIsInstance(_a , _a )
@slow
@require_torch
def a__ ( self ) -> Optional[int]:
_A : Optional[Any] = pipeline(task="""fill-mask""" , model="""distilroberta-base""" , top_k=2 , framework="""pt""" )
self.run_large_test(_a )
@slow
@require_tf
def a__ ( self ) -> Tuple:
_A : str = pipeline(task="""fill-mask""" , model="""distilroberta-base""" , top_k=2 , framework="""tf""" )
self.run_large_test(_a )
def a__ ( self , _a ) -> Tuple:
_A : Optional[int] = unmasker("""My name is <mask>""" )
self.assertEqual(
nested_simplify(_a ) , [
{"""sequence""": """My name is John""", """score""": 0.008, """token""": 610, """token_str""": """ John"""},
{"""sequence""": """My name is Chris""", """score""": 0.007, """token""": 1573, """token_str""": """ Chris"""},
] , )
_A : int = unmasker("""The largest city in France is <mask>""" )
self.assertEqual(
nested_simplify(_a ) , [
{
"""sequence""": """The largest city in France is Paris""",
"""score""": 0.251,
"""token""": 2201,
"""token_str""": """ Paris""",
},
{
"""sequence""": """The largest city in France is Lyon""",
"""score""": 0.214,
"""token""": 1_2790,
"""token_str""": """ Lyon""",
},
] , )
_A : Optional[Any] = unmasker("""My name is <mask>""" , targets=[""" Patrick""", """ Clara""", """ Teven"""] , top_k=3 )
self.assertEqual(
nested_simplify(_a ) , [
{"""sequence""": """My name is Patrick""", """score""": 0.005, """token""": 3499, """token_str""": """ Patrick"""},
{"""sequence""": """My name is Clara""", """score""": 0.000, """token""": 1_3606, """token_str""": """ Clara"""},
{"""sequence""": """My name is Te""", """score""": 0.000, """token""": 2941, """token_str""": """ Te"""},
] , )
@require_torch
def a__ ( self ) -> Tuple:
_A : List[str] = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , framework="""pt""" )
_A : str = None
_A : Union[str, Any] = None
self.run_pipeline_test(_a , [] )
@require_tf
def a__ ( self ) -> Union[str, Any]:
_A : Tuple = pipeline(task="""fill-mask""" , model="""sshleifer/tiny-distilroberta-base""" , framework="""tf""" )
_A : Any = None
_A : Dict = None
self.run_pipeline_test(_a , [] )
def a__ ( self , _a , _a , _a ) -> Any:
if tokenizer is None or tokenizer.mask_token_id is None:
self.skipTest("""The provided tokenizer has no mask token, (probably reformer or wav2vec2)""" )
_A : Optional[Any] = FillMaskPipeline(model=_a , tokenizer=_a )
_A : Tuple = [
F'''This is another {tokenizer.mask_token} test''',
]
return fill_masker, examples
def a__ ( self , _a , _a ) -> Dict:
_A : Dict = fill_masker.tokenizer
_A : List[str] = fill_masker.model
_A : List[str] = fill_masker(
F'''This is a {tokenizer.mask_token}''' , )
self.assertEqual(
_a , [
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
] , )
_A : Optional[Any] = fill_masker([F'''This is a {tokenizer.mask_token}'''] )
self.assertEqual(
_a , [
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
] , )
_A : List[str] = fill_masker([F'''This is a {tokenizer.mask_token}''', F'''Another {tokenizer.mask_token} great test.'''] )
self.assertEqual(
_a , [
[
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
],
[
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
],
] , )
with self.assertRaises(_a ):
fill_masker([None] )
# No mask_token is not supported
with self.assertRaises(_a ):
fill_masker("""This is""" )
self.run_test_top_k(_a , _a )
self.run_test_targets(_a , _a )
self.run_test_top_k_targets(_a , _a )
self.fill_mask_with_duplicate_targets_and_top_k(_a , _a )
self.fill_mask_with_multiple_masks(_a , _a )
def a__ ( self , _a , _a ) -> List[str]:
_A : int = tokenizer.get_vocab()
_A : str = sorted(vocab.keys() )[:2]
# Pipeline argument
_A : Tuple = FillMaskPipeline(model=_a , tokenizer=_a , targets=_a )
_A : Optional[int] = fill_masker(F'''This is a {tokenizer.mask_token}''' )
self.assertEqual(
_a , [
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
] , )
_A : List[str] = {vocab[el] for el in targets}
self.assertEqual({el["""token"""] for el in outputs} , _a )
_A : Union[str, Any] = [tokenizer.decode([x] ) for x in target_ids]
self.assertEqual({el["""token_str"""] for el in outputs} , set(_a ) )
# Call argument
_A : str = FillMaskPipeline(model=_a , tokenizer=_a )
_A : Optional[int] = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets=_a )
self.assertEqual(
_a , [
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
] , )
_A : int = {vocab[el] for el in targets}
self.assertEqual({el["""token"""] for el in outputs} , _a )
_A : Any = [tokenizer.decode([x] ) for x in target_ids]
self.assertEqual({el["""token_str"""] for el in outputs} , set(_a ) )
# Score equivalence
_A : int = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets=_a )
_A : Optional[int] = [top_mask["""token_str"""] for top_mask in outputs]
_A : Union[str, Any] = [top_mask["""score"""] for top_mask in outputs]
# For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`.
if set(_a ) == set(_a ):
_A : Tuple = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets=_a )
_A : Union[str, Any] = [top_mask["""score"""] for top_mask in unmasked_targets]
self.assertEqual(nested_simplify(_a ) , nested_simplify(_a ) )
# Raises with invalid
with self.assertRaises(_a ):
_A : str = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets=[] )
# For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised
if "" not in tokenizer.get_vocab():
with self.assertRaises(_a ):
_A : Optional[Any] = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets=[""""""] )
with self.assertRaises(_a ):
_A : int = fill_masker(F'''This is a {tokenizer.mask_token}''' , targets="""""" )
def a__ ( self , _a , _a ) -> Optional[Any]:
_A : str = FillMaskPipeline(model=_a , tokenizer=_a , top_k=2 )
_A : str = fill_masker(F'''This is a {tokenizer.mask_token}''' )
self.assertEqual(
_a , [
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
] , )
_A : Union[str, Any] = FillMaskPipeline(model=_a , tokenizer=_a )
_A : Union[str, Any] = fill_masker(F'''This is a {tokenizer.mask_token}''' , top_k=2 )
self.assertEqual(
_a , [
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
] , )
self.assertEqual(nested_simplify(_a ) , nested_simplify(_a ) )
def a__ ( self , _a , _a ) -> List[Any]:
_A : Union[str, Any] = tokenizer.get_vocab()
_A : int = FillMaskPipeline(model=_a , tokenizer=_a )
# top_k=2, ntargets=3
_A : List[str] = sorted(vocab.keys() )[:3]
_A : Tuple = fill_masker(F'''This is a {tokenizer.mask_token}''' , top_k=2 , targets=_a )
# If we use the most probably targets, and filter differently, we should still
# have the same results
_A : Any = [el["""token_str"""] for el in sorted(_a , key=lambda _a : x["score"] , reverse=_a )]
# For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`.
if set(_a ).issubset(_a ):
_A : Any = fill_masker(F'''This is a {tokenizer.mask_token}''' , top_k=3 , targets=_a )
# They should yield exactly the same result
self.assertEqual(nested_simplify(_a ) , nested_simplify(_a ) )
def a__ ( self , _a , _a ) -> str:
_A : Optional[int] = FillMaskPipeline(model=_a , tokenizer=_a )
_A : List[Any] = tokenizer.get_vocab()
# String duplicates + id duplicates
_A : Optional[Any] = sorted(vocab.keys() )[:3]
_A : Optional[Any] = [targets[0], targets[1], targets[0], targets[2], targets[1]]
_A : Union[str, Any] = fill_masker(F'''My name is {tokenizer.mask_token}''' , targets=_a , top_k=10 )
# The target list contains duplicates, so we can't output more
# than them
self.assertEqual(len(_a ) , 3 )
def a__ ( self , _a , _a ) -> Tuple:
_A : Any = FillMaskPipeline(model=_a , tokenizer=_a )
_A : Optional[Any] = fill_masker(
F'''This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}''' , top_k=2 )
self.assertEqual(
_a , [
[
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
],
[
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
],
[
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
{"""sequence""": ANY(_a ), """score""": ANY(_a ), """token""": ANY(_a ), """token_str""": ANY(_a )},
],
] , )
| 54 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.