code stringlengths 82 54.1k | code_codestyle int64 0 699 | style_context stringlengths 111 35.6k | style_context_codestyle int64 0 699 | label int64 0 1 |
|---|---|---|---|---|
'''simple docstring'''
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union
import numpy as np
import PIL
from PIL import Image
from ...utils import BaseOutput, is_torch_available, is_transformers_available
@dataclass
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = 42
__SCREAMING_SNAKE_CASE = 42
if is_transformers_available() and is_torch_available():
from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
| 69 |
'''simple docstring'''
import mpmath # for roots of unity
import numpy as np
class SCREAMING_SNAKE_CASE__ :
def __init__( self : Tuple , a_ : Optional[int]=None , a_ : int=None ):
"""simple docstring"""
__snake_case = list(poly_a or [0] )[:]
__snake_case = list(poly_b or [0] )[:]
# Remove leading zero coefficients
while self.polyA[-1] == 0:
self.polyA.pop()
__snake_case = len(self.polyA )
while self.polyB[-1] == 0:
self.polyB.pop()
__snake_case = len(self.polyB )
# Add 0 to make lengths equal a power of 2
__snake_case = int(
2 ** np.ceil(np.loga(len(self.polyA ) + len(self.polyB ) - 1 ) ) )
while len(self.polyA ) < self.c_max_length:
self.polyA.append(0 )
while len(self.polyB ) < self.c_max_length:
self.polyB.append(0 )
# A complex root used for the fourier transform
__snake_case = complex(mpmath.root(x=1 , n=self.c_max_length , k=1 ) )
# The product
__snake_case = self.__multiply()
def A ( self : Any , a_ : Optional[Any] ):
"""simple docstring"""
__snake_case = [[x] for x in self.polyA] if which == "A" else [[x] for x in self.polyB]
# Corner case
if len(a_ ) <= 1:
return dft[0]
#
__snake_case = self.c_max_length // 2
while next_ncol > 0:
__snake_case = [[] for i in range(a_ )]
__snake_case = self.root**next_ncol
# First half of next step
__snake_case = 1
for j in range(self.c_max_length // (next_ncol * 2) ):
for i in range(a_ ):
new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j] )
current_root *= root
# Second half of next step
__snake_case = 1
for j in range(self.c_max_length // (next_ncol * 2) ):
for i in range(a_ ):
new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j] )
current_root *= root
# Update
__snake_case = new_dft
__snake_case = next_ncol // 2
return dft[0]
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = self.__dft("A" )
__snake_case = self.__dft("B" )
__snake_case = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length )]]
del dft_a
del dft_b
# Corner Case
if len(inverce_c[0] ) <= 1:
return inverce_c[0]
# Inverse DFT
__snake_case = 2
while next_ncol <= self.c_max_length:
__snake_case = [[] for i in range(a_ )]
__snake_case = self.root ** (next_ncol // 2)
__snake_case = 1
# First half of next step
for j in range(self.c_max_length // next_ncol ):
for i in range(next_ncol // 2 ):
# Even positions
new_inverse_c[i].append(
(
inverce_c[i][j]
+ inverce_c[i][j + self.c_max_length // next_ncol]
)
/ 2 )
# Odd positions
new_inverse_c[i + next_ncol // 2].append(
(
inverce_c[i][j]
- inverce_c[i][j + self.c_max_length // next_ncol]
)
/ (2 * current_root) )
current_root *= root
# Update
__snake_case = new_inverse_c
next_ncol *= 2
# Unpack
__snake_case = [round(x[0].real , 8 ) + round(x[0].imag , 8 ) * 1j for x in inverce_c]
# Remove leading 0's
while inverce_c[-1] == 0:
inverce_c.pop()
return inverce_c
def __str__( self : Optional[int] ):
"""simple docstring"""
__snake_case = "A = " + " + ".join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.polyA[: self.len_A] ) )
__snake_case = "B = " + " + ".join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.polyB[: self.len_B] ) )
__snake_case = "A*B = " + " + ".join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.product ) )
return f'''{a}\n{b}\n{c}'''
# Unit tests
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 | 1 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> int:
assert isinstance(_UpperCAmelCase , _UpperCAmelCase ), F'''The input value of [n={number}] is not an integer'''
if number == 1:
return 2
elif number < 1:
__snake_case = F'''The input value of [n={number}] has to be > 0'''
raise ValueError(_UpperCAmelCase )
else:
__snake_case = sylvester(number - 1 )
__snake_case = num - 1
__snake_case = num
return lower * upper + 1
if __name__ == "__main__":
print(F'''The 8th number in Sylvester\'s sequence: {sylvester(8)}''')
| 69 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
a : List[Any] = {
'''configuration_table_transformer''': [
'''TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''TableTransformerConfig''',
'''TableTransformerOnnxConfig''',
]
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : Tuple = [
'''TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TableTransformerForObjectDetection''',
'''TableTransformerModel''',
'''TableTransformerPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_table_transformer import (
TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
TableTransformerConfig,
TableTransformerOnnxConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_table_transformer import (
TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TableTransformerForObjectDetection,
TableTransformerModel,
TableTransformerPreTrainedModel,
)
else:
import sys
a : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 69 | 1 |
'''simple docstring'''
import argparse
import os
import re
import numpy as np
import PIL
import torch
from timm import create_model
from torch.optim.lr_scheduler import OneCycleLR
from torch.utils.data import DataLoader, Dataset
from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor
from accelerate import Accelerator
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> int:
__snake_case = fname.split(os.path.sep )[-1]
return re.search(R"^(.*)_\d+\.jpg$" , _UpperCAmelCase ).groups()[0]
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def __init__( self : Optional[Any] , a_ : str , a_ : Union[str, Any]=None , a_ : str=None ):
"""simple docstring"""
__snake_case = file_names
__snake_case = image_transform
__snake_case = label_to_id
def __len__( self : str ):
"""simple docstring"""
return len(self.file_names )
def __getitem__( self : int , a_ : str ):
"""simple docstring"""
__snake_case = self.file_names[idx]
__snake_case = PIL.Image.open(a_ )
__snake_case = raw_image.convert("RGB" )
if self.image_transform is not None:
__snake_case = self.image_transform(a_ )
__snake_case = extract_label(a_ )
if self.label_to_id is not None:
__snake_case = self.label_to_id[label]
return {"image": image, "label": label}
def __UpperCAmelCase ( _UpperCAmelCase : Dict , _UpperCAmelCase : Dict ) -> List[Any]:
# Initialize accelerator
if args.with_tracking:
__snake_case = Accelerator(
cpu=args.cpu , mixed_precision=args.mixed_precision , log_with="all" , project_dir=args.project_dir )
else:
__snake_case = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
__snake_case = config["lr"]
__snake_case = int(config["num_epochs"] )
__snake_case = int(config["seed"] )
__snake_case = int(config["batch_size"] )
__snake_case = config["image_size"]
if not isinstance(_UpperCAmelCase , (list, tuple) ):
__snake_case = (image_size, image_size)
# Parse out whether we are saving every epoch or after a certain number of batches
if hasattr(args.checkpointing_steps , "isdigit" ):
if args.checkpointing_steps == "epoch":
__snake_case = args.checkpointing_steps
elif args.checkpointing_steps.isdigit():
__snake_case = int(args.checkpointing_steps )
else:
raise ValueError(
F'''Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.''' )
else:
__snake_case = None
# We need to initialize the trackers we use, and also store our configuration
if args.with_tracking:
__snake_case = os.path.split(_UpperCAmelCase )[-1].split("." )[0]
accelerator.init_trackers(_UpperCAmelCase , _UpperCAmelCase )
# Grab all the image filenames
__snake_case = [os.path.join(args.data_dir , _UpperCAmelCase ) for fname in os.listdir(args.data_dir ) if fname.endswith(".jpg" )]
# Build the label correspondences
__snake_case = [extract_label(_UpperCAmelCase ) for fname in file_names]
__snake_case = list(set(_UpperCAmelCase ) )
id_to_label.sort()
__snake_case = {lbl: i for i, lbl in enumerate(_UpperCAmelCase )}
# Set the seed before splitting the data.
np.random.seed(_UpperCAmelCase )
torch.manual_seed(_UpperCAmelCase )
torch.cuda.manual_seed_all(_UpperCAmelCase )
# Split our filenames between train and validation
__snake_case = np.random.permutation(len(_UpperCAmelCase ) )
__snake_case = int(0.8 * len(_UpperCAmelCase ) )
__snake_case = random_perm[:cut]
__snake_case = random_perm[cut:]
# For training we use a simple RandomResizedCrop
__snake_case = Compose([RandomResizedCrop(_UpperCAmelCase , scale=(0.5, 1.0) ), ToTensor()] )
__snake_case = PetsDataset(
[file_names[i] for i in train_split] , image_transform=_UpperCAmelCase , label_to_id=_UpperCAmelCase )
# For evaluation, we use a deterministic Resize
__snake_case = Compose([Resize(_UpperCAmelCase ), ToTensor()] )
__snake_case = PetsDataset([file_names[i] for i in eval_split] , image_transform=_UpperCAmelCase , label_to_id=_UpperCAmelCase )
# Instantiate dataloaders.
__snake_case = DataLoader(_UpperCAmelCase , shuffle=_UpperCAmelCase , batch_size=_UpperCAmelCase , num_workers=4 )
__snake_case = DataLoader(_UpperCAmelCase , shuffle=_UpperCAmelCase , batch_size=_UpperCAmelCase , num_workers=4 )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
__snake_case = create_model("resnet50d" , pretrained=_UpperCAmelCase , num_classes=len(_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).
__snake_case = model.to(accelerator.device )
# Freezing the base model
for param in model.parameters():
__snake_case = False
for param in model.get_classifier().parameters():
__snake_case = True
# We normalize the batches of images to be a bit faster.
__snake_case = torch.tensor(model.default_cfg["mean"] )[None, :, None, None].to(accelerator.device )
__snake_case = torch.tensor(model.default_cfg["std"] )[None, :, None, None].to(accelerator.device )
# Instantiate optimizer
__snake_case = torch.optim.Adam(params=model.parameters() , lr=lr / 25 )
# Instantiate learning rate scheduler
__snake_case = OneCycleLR(optimizer=_UpperCAmelCase , max_lr=_UpperCAmelCase , epochs=_UpperCAmelCase , steps_per_epoch=len(_UpperCAmelCase ) )
# 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.
__snake_case , __snake_case , __snake_case , __snake_case , __snake_case = accelerator.prepare(
_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
# We need to keep track of how many total steps we have iterated over
__snake_case = 0
# We also need to keep track of the starting epoch so files are named properly
__snake_case = 0
# Potentially load in the weights and states from a previous save
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
accelerator.print(F'''Resumed from checkpoint: {args.resume_from_checkpoint}''' )
accelerator.load_state(args.resume_from_checkpoint )
__snake_case = os.path.basename(args.resume_from_checkpoint )
else:
# Get the most recent checkpoint
__snake_case = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()]
dirs.sort(key=os.path.getctime )
__snake_case = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
# Extract `epoch_{i}` or `step_{i}`
__snake_case = os.path.splitext(_UpperCAmelCase )[0]
if "epoch" in training_difference:
__snake_case = int(training_difference.replace("epoch_" , "" ) ) + 1
__snake_case = None
else:
__snake_case = int(training_difference.replace("step_" , "" ) )
__snake_case = resume_step // len(_UpperCAmelCase )
resume_step -= starting_epoch * len(_UpperCAmelCase )
# Now we train the model
for epoch in range(_UpperCAmelCase , _UpperCAmelCase ):
model.train()
if args.with_tracking:
__snake_case = 0
if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
# We need to skip steps until we reach the resumed step
__snake_case = accelerator.skip_first_batches(_UpperCAmelCase , _UpperCAmelCase )
overall_step += resume_step
else:
# After the first iteration though, we need to go back to the original dataloader
__snake_case = train_dataloader
for batch in active_dataloader:
# We could avoid this line since we set the accelerator with `device_placement=True`.
__snake_case = {k: v.to(accelerator.device ) for k, v in batch.items()}
__snake_case = (batch["image"] - mean) / std
__snake_case = model(_UpperCAmelCase )
__snake_case = torch.nn.functional.cross_entropy(_UpperCAmelCase , batch["label"] )
# We keep track of the loss at each epoch
if args.with_tracking:
total_loss += loss.detach().float()
accelerator.backward(_UpperCAmelCase )
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
overall_step += 1
if isinstance(_UpperCAmelCase , _UpperCAmelCase ):
__snake_case = F'''step_{overall_step}'''
if overall_step % checkpointing_steps == 0:
if args.output_dir is not None:
__snake_case = os.path.join(args.output_dir , _UpperCAmelCase )
accelerator.save_state(_UpperCAmelCase )
model.eval()
__snake_case = 0
__snake_case = 0
for step, batch in enumerate(_UpperCAmelCase ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
__snake_case = {k: v.to(accelerator.device ) for k, v in batch.items()}
__snake_case = (batch["image"] - mean) / std
with torch.no_grad():
__snake_case = model(_UpperCAmelCase )
__snake_case = outputs.argmax(dim=-1 )
__snake_case , __snake_case = accelerator.gather_for_metrics((predictions, batch["label"]) )
__snake_case = predictions == references
num_elems += accurate_preds.shape[0]
accurate += accurate_preds.long().sum()
__snake_case = accurate.item() / num_elems
# Use accelerator.print to print only on the main process.
accelerator.print(F'''epoch {epoch}: {1_00 * eval_metric:.2f}''' )
if args.with_tracking:
accelerator.log(
{
"accuracy": 1_00 * eval_metric,
"train_loss": total_loss.item() / len(_UpperCAmelCase ),
"epoch": epoch,
} , step=_UpperCAmelCase , )
if checkpointing_steps == "epoch":
__snake_case = F'''epoch_{epoch}'''
if args.output_dir is not None:
__snake_case = os.path.join(args.output_dir , _UpperCAmelCase )
accelerator.save_state(_UpperCAmelCase )
if args.with_tracking:
accelerator.end_training()
def __UpperCAmelCase ( ) -> str:
__snake_case = argparse.ArgumentParser(description="Simple example of training script." )
parser.add_argument("--data_dir" , required=_UpperCAmelCase , help="The data folder on disk." )
parser.add_argument("--fp16" , action="store_true" , help="If passed, will use FP16 training." )
parser.add_argument(
"--mixed_precision" , type=_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." )
parser.add_argument(
"--checkpointing_steps" , type=_UpperCAmelCase , default=_UpperCAmelCase , help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch." , )
parser.add_argument(
"--output_dir" , type=_UpperCAmelCase , 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=_UpperCAmelCase , default=_UpperCAmelCase , help="If the training should continue from a checkpoint folder." , )
parser.add_argument(
"--with_tracking" , action="store_true" , help="Whether to load in all available experiment trackers from the environment and use them for logging." , )
parser.add_argument(
"--project_dir" , type=_UpperCAmelCase , default="logs" , help="Location on where to store experiment tracking logs` and relevent project information" , )
__snake_case = parser.parse_args()
__snake_case = {"lr": 3E-2, "num_epochs": 3, "seed": 42, "batch_size": 64, "image_size": 2_24}
training_function(_UpperCAmelCase , _UpperCAmelCase )
if __name__ == "__main__":
main()
| 69 |
'''simple docstring'''
import json
import os
import torch
from diffusers import UNetaDModel
os.makedirs('''hub/hopper-medium-v2/unet/hor32''', exist_ok=True)
os.makedirs('''hub/hopper-medium-v2/unet/hor128''', exist_ok=True)
os.makedirs('''hub/hopper-medium-v2/value_function''', exist_ok=True)
def __UpperCAmelCase ( _UpperCAmelCase : List[str] ) -> str:
if hor == 1_28:
__snake_case = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D")
__snake_case = (32, 1_28, 2_56)
__snake_case = ("UpResnetBlock1D", "UpResnetBlock1D")
elif hor == 32:
__snake_case = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D")
__snake_case = (32, 64, 1_28, 2_56)
__snake_case = ("UpResnetBlock1D", "UpResnetBlock1D", "UpResnetBlock1D")
__snake_case = torch.load(F'''/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch''' )
__snake_case = model.state_dict()
__snake_case = {
"down_block_types": down_block_types,
"block_out_channels": block_out_channels,
"up_block_types": up_block_types,
"layers_per_block": 1,
"use_timestep_embedding": True,
"out_block_type": "OutConv1DBlock",
"norm_num_groups": 8,
"downsample_each_block": False,
"in_channels": 14,
"out_channels": 14,
"extra_in_channels": 0,
"time_embedding_type": "positional",
"flip_sin_to_cos": False,
"freq_shift": 1,
"sample_size": 6_55_36,
"mid_block_type": "MidResTemporalBlock1D",
"act_fn": "mish",
}
__snake_case = UNetaDModel(**_UpperCAmelCase )
print(F'''length of state dict: {len(state_dict.keys() )}''' )
print(F'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' )
__snake_case = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) )
for k, v in mapping.items():
__snake_case = state_dict.pop(_UpperCAmelCase )
hf_value_function.load_state_dict(_UpperCAmelCase )
torch.save(hf_value_function.state_dict() , F'''hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin''' )
with open(F'''hub/hopper-medium-v2/unet/hor{hor}/config.json''' , "w" ) as f:
json.dump(_UpperCAmelCase , _UpperCAmelCase )
def __UpperCAmelCase ( ) -> List[Any]:
__snake_case = {
"in_channels": 14,
"down_block_types": ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D"),
"up_block_types": (),
"out_block_type": "ValueFunction",
"mid_block_type": "ValueFunctionMidBlock1D",
"block_out_channels": (32, 64, 1_28, 2_56),
"layers_per_block": 1,
"downsample_each_block": True,
"sample_size": 6_55_36,
"out_channels": 14,
"extra_in_channels": 0,
"time_embedding_type": "positional",
"use_timestep_embedding": True,
"flip_sin_to_cos": False,
"freq_shift": 1,
"norm_num_groups": 8,
"act_fn": "mish",
}
__snake_case = torch.load("/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch" )
__snake_case = model
__snake_case = UNetaDModel(**_UpperCAmelCase )
print(F'''length of state dict: {len(state_dict.keys() )}''' )
print(F'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' )
__snake_case = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) )
for k, v in mapping.items():
__snake_case = state_dict.pop(_UpperCAmelCase )
hf_value_function.load_state_dict(_UpperCAmelCase )
torch.save(hf_value_function.state_dict() , "hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin" )
with open("hub/hopper-medium-v2/value_function/config.json" , "w" ) as f:
json.dump(_UpperCAmelCase , _UpperCAmelCase )
if __name__ == "__main__":
unet(32)
# unet(128)
value_function()
| 69 | 1 |
'''simple docstring'''
from math import ceil
from typing import List, Optional, Union
import numpy as np
from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor
from ...utils import TensorType, logging
a : Dict = logging.get_logger(__name__)
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = ["""audio_values""", """audio_mask"""]
def __init__( self : List[str] , a_ : List[Any]=2_048 , a_ : str=1 , a_ : List[str]=[16, 16] , a_ : Optional[Any]=128 , a_ : Union[str, Any]=44_100 , a_ : Tuple=86 , a_ : Optional[int]=2_048 , a_ : Tuple=0.0 , **a_ : int , ):
"""simple docstring"""
super().__init__(
feature_size=a_ , sampling_rate=a_ , padding_value=a_ , **a_ , )
__snake_case = spectrogram_length
__snake_case = num_channels
__snake_case = patch_size
__snake_case = feature_size // self.patch_size[1]
__snake_case = n_fft
__snake_case = sampling_rate // hop_length_to_sampling_rate
__snake_case = sampling_rate
__snake_case = padding_value
__snake_case = mel_filter_bank(
num_frequency_bins=1 + n_fft // 2 , num_mel_filters=a_ , min_frequency=0.0 , max_frequency=22050.0 , sampling_rate=a_ , norm="slaney" , mel_scale="slaney" , ).T
def A ( self : Union[str, Any] , a_ : np.array ):
"""simple docstring"""
__snake_case = spectrogram(
a_ , window_function(self.n_fft , "hann" ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters.T , log_mel="dB" , db_range=80.0 , )
__snake_case = log_spec[:, :-1]
__snake_case = log_spec - 20.0
__snake_case = np.clip(log_spec / 40.0 , -2.0 , 0.0 ) + 1.0
return log_spec
def __call__( self : Union[str, Any] , a_ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , a_ : Optional[Union[str, TensorType]] = None , a_ : Optional[bool] = True , a_ : Optional[int] = None , a_ : bool = False , a_ : bool = False , **a_ : Tuple , ):
"""simple docstring"""
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
"This feature extractor is set to support sampling rate"
f''' of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled'''
f''' with {self.sampling_rate} and not {sampling_rate}.''' )
else:
logger.warning(
"It is strongly recommended to pass the `sampling_rate` argument to this function. "
"Failing to do so can result in silent errors that might be hard to debug." )
__snake_case = isinstance(a_ , 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}''' )
__snake_case = is_batched_numpy or (
isinstance(a_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) ))
)
if is_batched:
__snake_case = [np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech]
elif not is_batched and not isinstance(a_ , np.ndarray ):
__snake_case = np.asarray(a_ , dtype=np.floataa )
elif isinstance(a_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ):
__snake_case = raw_speech.astype(np.floataa )
# always return batch
if not is_batched:
__snake_case = [np.asarray([raw_speech] ).T]
# Convert audio signals to log mel spectrograms, truncate by time axis
__snake_case = [
self._np_extract_fbank_features(waveform.squeeze() ).T[: self.spectrogram_length] for waveform in raw_speech
]
if isinstance(audio_features[0] , a_ ):
__snake_case = [np.asarray(a_ , dtype=np.floataa ) for feature in audio_features]
# Create audio attention mask
__snake_case = max(
[ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len for feature in audio_features] ) # The maximum number of audio patches in a batch
if return_attention_mask:
__snake_case = [
(ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [1]
+ (max_patch_len - ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [0]
for feature in audio_features
]
__snake_case = np.array(a_ ).astype(np.floataa )
# convert into correct format for padding
__snake_case = max_patch_len // self.freq_len * self.patch_size[0] # The maximum audio size in a batch
__snake_case = np.ones([len(a_ ), 1, max_time_len, self.feature_size] ).astype(np.floataa )
__snake_case = padded_audio_features * self.padding_value
for i in range(len(a_ ) ):
__snake_case = audio_features[i]
__snake_case = feature
# return as BatchFeature
if return_attention_mask:
__snake_case = {"audio_values": padded_audio_features, "audio_mask": audio_mask}
else:
__snake_case = {"audio_values": padded_audio_features}
__snake_case = BatchFeature(data=a_ , tensor_type=a_ )
return encoded_inputs
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int = 1_00_00_00 ) -> int:
__snake_case = 1
__snake_case = 1
__snake_case = {1: 1}
for inputa in range(2 , _UpperCAmelCase ):
__snake_case = 0
__snake_case = inputa
while True:
if number in counters:
counter += counters[number]
break
if number % 2 == 0:
number //= 2
counter += 1
else:
__snake_case = (3 * number) + 1
counter += 1
if inputa not in counters:
__snake_case = counter
if counter > pre_counter:
__snake_case = inputa
__snake_case = counter
return largest_number
if __name__ == "__main__":
print(solution(int(input().strip())))
| 69 | 1 |
'''simple docstring'''
import importlib
import shutil
import threading
import warnings
from typing import List
import fsspec
import fsspec.asyn
from . import compression
from .hffilesystem import HfFileSystem
a : int = importlib.util.find_spec('''s3fs''') is not None
if _has_safs:
from .safilesystem import SaFileSystem # noqa: F401
a : List[compression.BaseCompressedFileFileSystem] = [
compression.BzaFileSystem,
compression.GzipFileSystem,
compression.LzaFileSystem,
compression.XzFileSystem,
compression.ZstdFileSystem,
]
# Register custom filesystems
for fs_class in COMPRESSION_FILESYSTEMS + [HfFileSystem]:
if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class:
warnings.warn(F'''A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.''')
fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True)
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> str:
if "://" in dataset_path:
__snake_case = dataset_path.split("://" )[1]
return dataset_path
def __UpperCAmelCase ( _UpperCAmelCase : fsspec.AbstractFileSystem ) -> bool:
if fs is not None and fs.protocol != "file":
return True
else:
return False
def __UpperCAmelCase ( _UpperCAmelCase : fsspec.AbstractFileSystem , _UpperCAmelCase : str , _UpperCAmelCase : str ) -> List[str]:
__snake_case = not is_remote_filesystem(_UpperCAmelCase )
if is_local:
# LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory
shutil.move(fs._strip_protocol(_UpperCAmelCase ) , fs._strip_protocol(_UpperCAmelCase ) )
else:
fs.mv(_UpperCAmelCase , _UpperCAmelCase , recursive=_UpperCAmelCase )
def __UpperCAmelCase ( ) -> None:
if hasattr(fsspec.asyn , "reset_lock" ):
# for future fsspec>2022.05.0
fsspec.asyn.reset_lock()
else:
__snake_case = None
__snake_case = None
__snake_case = threading.Lock()
| 69 |
'''simple docstring'''
from ...processing_utils import ProcessorMixin
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = """SpeechT5FeatureExtractor"""
__SCREAMING_SNAKE_CASE = """SpeechT5Tokenizer"""
def __init__( self : List[Any] , a_ : str , a_ : str ):
"""simple docstring"""
super().__init__(a_ , a_ )
def __call__( self : Dict , *a_ : Tuple , **a_ : List[str] ):
"""simple docstring"""
__snake_case = kwargs.pop("audio" , a_ )
__snake_case = kwargs.pop("text" , a_ )
__snake_case = kwargs.pop("text_target" , a_ )
__snake_case = kwargs.pop("audio_target" , a_ )
__snake_case = kwargs.pop("sampling_rate" , a_ )
if audio is not None and text is not None:
raise ValueError(
"Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?" )
if audio_target is not None and text_target is not None:
raise ValueError(
"Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?" )
if audio is None and audio_target is None and text is None and text_target is None:
raise ValueError(
"You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process." )
if audio is not None:
__snake_case = self.feature_extractor(a_ , *a_ , sampling_rate=a_ , **a_ )
elif text is not None:
__snake_case = self.tokenizer(a_ , **a_ )
else:
__snake_case = None
if audio_target is not None:
__snake_case = self.feature_extractor(audio_target=a_ , *a_ , sampling_rate=a_ , **a_ )
__snake_case = targets["input_values"]
elif text_target is not None:
__snake_case = self.tokenizer(a_ , **a_ )
__snake_case = targets["input_ids"]
else:
__snake_case = None
if inputs is None:
return targets
if targets is not None:
__snake_case = labels
__snake_case = targets.get("attention_mask" )
if decoder_attention_mask is not None:
__snake_case = decoder_attention_mask
return inputs
def A ( self : List[str] , *a_ : str , **a_ : Dict ):
"""simple docstring"""
__snake_case = kwargs.pop("input_values" , a_ )
__snake_case = kwargs.pop("input_ids" , a_ )
__snake_case = kwargs.pop("labels" , a_ )
if input_values is not None and input_ids is not None:
raise ValueError("Cannot process both `input_values` and `input_ids` inputs." )
if input_values is None and input_ids is None and labels is None:
raise ValueError(
"You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded." )
if input_values is not None:
__snake_case = self.feature_extractor.pad(a_ , *a_ , **a_ )
elif input_ids is not None:
__snake_case = self.tokenizer.pad(a_ , **a_ )
else:
__snake_case = None
if labels is not None:
if "input_ids" in labels or (isinstance(a_ , a_ ) and "input_ids" in labels[0]):
__snake_case = self.tokenizer.pad(a_ , **a_ )
__snake_case = targets["input_ids"]
else:
__snake_case = self.feature_extractor.feature_size
__snake_case = self.feature_extractor.num_mel_bins
__snake_case = self.feature_extractor.pad(a_ , *a_ , **a_ )
__snake_case = feature_size_hack
__snake_case = targets["input_values"]
else:
__snake_case = None
if inputs is None:
return targets
if targets is not None:
__snake_case = labels
__snake_case = targets.get("attention_mask" )
if decoder_attention_mask is not None:
__snake_case = decoder_attention_mask
return inputs
def A ( self : List[str] , *a_ : Any , **a_ : List[str] ):
"""simple docstring"""
return self.tokenizer.batch_decode(*a_ , **a_ )
def A ( self : Optional[int] , *a_ : Union[str, Any] , **a_ : str ):
"""simple docstring"""
return self.tokenizer.decode(*a_ , **a_ )
| 69 | 1 |
'''simple docstring'''
import json
import os
import unittest
from transformers.models.blenderbot_small.tokenization_blenderbot_small import (
VOCAB_FILES_NAMES,
BlenderbotSmallTokenizer,
)
from ...test_tokenization_common import TokenizerTesterMixin
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = BlenderbotSmallTokenizer
__SCREAMING_SNAKE_CASE = False
def A ( self : List[Any] ):
"""simple docstring"""
super().setUp()
__snake_case = ["__start__", "adapt", "act", "ap@@", "te", "__end__", "__unk__"]
__snake_case = dict(zip(a_ , range(len(a_ ) ) ) )
__snake_case = ["#version: 0.2", "a p", "t e</w>", "ap t</w>", "a d", "ad apt</w>", "a c", "ac t</w>", ""]
__snake_case = {"unk_token": "__unk__", "bos_token": "__start__", "eos_token": "__end__"}
__snake_case = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
__snake_case = 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 A ( self : List[str] , **a_ : Optional[Any] ):
"""simple docstring"""
kwargs.update(self.special_tokens_map )
return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **a_ )
def A ( self : Any , a_ : Any ):
"""simple docstring"""
__snake_case = "adapt act apte"
__snake_case = "adapt act apte"
return input_text, output_text
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map )
__snake_case = "adapt act apte"
__snake_case = ["adapt", "act", "ap@@", "te"]
__snake_case = tokenizer.tokenize(a_ )
self.assertListEqual(a_ , a_ )
__snake_case = [tokenizer.bos_token] + tokens + [tokenizer.eos_token]
__snake_case = [0, 1, 2, 3, 4, 5]
self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , a_ )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" )
assert tok("sam" ).input_ids == [1_384]
__snake_case = "I am a small frog."
__snake_case = tok([src_text] , padding=a_ , truncation=a_ )["input_ids"]
__snake_case = tok.batch_decode(a_ , skip_special_tokens=a_ , clean_up_tokenization_spaces=a_ )[0]
assert src_text != decoded # I wish it did!
assert decoded == "i am a small frog ."
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" )
__snake_case = "I am a small frog ."
__snake_case = "."
__snake_case = tok(a_ )["input_ids"]
__snake_case = tok(a_ )["input_ids"]
assert encoded[-1] == encoded_dot[0]
| 69 |
'''simple docstring'''
import re
from pathlib import Path
from unittest import TestCase
import pytest
@pytest.mark.integration
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def A ( self : Optional[Any] , a_ : str ):
"""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 A ( self : Any , a_ : str ):
"""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 A ( self : Optional[int] ):
"""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 A ( self : Optional[Any] ):
"""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.''' )
| 69 | 1 |
'''simple docstring'''
import copy
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
a : int = logging.get_logger(__name__)
a : Optional[Any] = {
'''ut/deta''': '''https://huggingface.co/ut/deta/resolve/main/config.json''',
}
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = """deta"""
__SCREAMING_SNAKE_CASE = {
"""hidden_size""": """d_model""",
"""num_attention_heads""": """encoder_attention_heads""",
}
def __init__( self : Optional[Any] , a_ : Union[str, Any]=None , a_ : Any=900 , a_ : Union[str, Any]=2_048 , a_ : Optional[int]=6 , a_ : str=2_048 , a_ : Any=8 , a_ : List[str]=6 , a_ : Optional[Any]=1_024 , a_ : Union[str, Any]=8 , a_ : str=0.0 , a_ : Tuple=True , a_ : Optional[int]="relu" , a_ : str=256 , a_ : int=0.1 , a_ : int=0.0 , a_ : Any=0.0 , a_ : List[str]=0.02 , a_ : List[str]=1.0 , a_ : Union[str, Any]=True , a_ : List[Any]=False , a_ : Any="sine" , a_ : List[Any]=5 , a_ : int=4 , a_ : str=4 , a_ : Any=True , a_ : Union[str, Any]=300 , a_ : List[Any]=True , a_ : Any=True , a_ : Dict=1 , a_ : Tuple=5 , a_ : Union[str, Any]=2 , a_ : List[Any]=1 , a_ : Optional[Any]=1 , a_ : Union[str, Any]=5 , a_ : int=2 , a_ : Dict=0.1 , a_ : Union[str, Any]=0.25 , **a_ : int , ):
"""simple docstring"""
if backbone_config is None:
logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." )
__snake_case = CONFIG_MAPPING["resnet"](out_features=["stage2", "stage3", "stage4"] )
else:
if isinstance(a_ , a_ ):
__snake_case = backbone_config.pop("model_type" )
__snake_case = CONFIG_MAPPING[backbone_model_type]
__snake_case = config_class.from_dict(a_ )
__snake_case = backbone_config
__snake_case = num_queries
__snake_case = max_position_embeddings
__snake_case = d_model
__snake_case = encoder_ffn_dim
__snake_case = encoder_layers
__snake_case = encoder_attention_heads
__snake_case = decoder_ffn_dim
__snake_case = decoder_layers
__snake_case = decoder_attention_heads
__snake_case = dropout
__snake_case = attention_dropout
__snake_case = activation_dropout
__snake_case = activation_function
__snake_case = init_std
__snake_case = init_xavier_std
__snake_case = encoder_layerdrop
__snake_case = auxiliary_loss
__snake_case = position_embedding_type
# deformable attributes
__snake_case = num_feature_levels
__snake_case = encoder_n_points
__snake_case = decoder_n_points
__snake_case = two_stage
__snake_case = two_stage_num_proposals
__snake_case = with_box_refine
__snake_case = assign_first_stage
if two_stage is True and with_box_refine is False:
raise ValueError("If two_stage is True, with_box_refine must be True." )
# Hungarian matcher
__snake_case = class_cost
__snake_case = bbox_cost
__snake_case = giou_cost
# Loss coefficients
__snake_case = mask_loss_coefficient
__snake_case = dice_loss_coefficient
__snake_case = bbox_loss_coefficient
__snake_case = giou_loss_coefficient
__snake_case = eos_coefficient
__snake_case = focal_alpha
super().__init__(is_encoder_decoder=a_ , **a_ )
@property
def A ( self : List[str] ):
"""simple docstring"""
return self.encoder_attention_heads
@property
def A ( self : int ):
"""simple docstring"""
return self.d_model
def A ( self : int ):
"""simple docstring"""
__snake_case = copy.deepcopy(self.__dict__ )
__snake_case = self.backbone_config.to_dict()
__snake_case = self.__class__.model_type
return output
| 69 |
'''simple docstring'''
import os
from shutil import copyfile
from typing import List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
a : Optional[Any] = logging.get_logger(__name__)
a : Dict = {'''vocab_file''': '''sentencepiece.model'''}
a : Tuple = {
'''vocab_file''': {
'''google/rembert''': '''https://huggingface.co/google/rembert/resolve/main/sentencepiece.model''',
},
}
a : str = {
'''google/rembert''': 256,
}
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES
__SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP
__SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__( self : Optional[Any] , a_ : int , a_ : Any=False , a_ : List[Any]=True , a_ : List[Any]=True , a_ : List[Any]="[CLS]" , a_ : List[Any]="[SEP]" , a_ : List[Any]="[UNK]" , a_ : str="[SEP]" , a_ : List[str]="[PAD]" , a_ : Optional[int]="[CLS]" , a_ : List[str]="[MASK]" , **a_ : str , ):
"""simple docstring"""
super().__init__(
do_lower_case=a_ , remove_space=a_ , keep_accents=a_ , bos_token=a_ , eos_token=a_ , unk_token=a_ , sep_token=a_ , pad_token=a_ , cls_token=a_ , mask_token=a_ , **a_ , )
__snake_case = do_lower_case
__snake_case = remove_space
__snake_case = keep_accents
__snake_case = vocab_file
__snake_case = spm.SentencePieceProcessor()
self.sp_model.Load(a_ )
@property
def A ( self : Optional[Any] ):
"""simple docstring"""
return len(self.sp_model )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = {self.convert_ids_to_tokens(a_ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self : Dict ):
"""simple docstring"""
__snake_case = self.__dict__.copy()
__snake_case = None
return state
def __setstate__( self : str , a_ : Optional[int] ):
"""simple docstring"""
__snake_case = d
__snake_case = spm.SentencePieceProcessor()
self.sp_model.Load(self.vocab_file )
def A ( self : Tuple , a_ : Optional[int] , a_ : int=False ):
"""simple docstring"""
__snake_case = self.sp_model.EncodeAsPieces(a_ )
return pieces
def A ( self : Any , a_ : Optional[Any] ):
"""simple docstring"""
return self.sp_model.PieceToId(a_ )
def A ( self : Optional[Any] , a_ : List[str] ):
"""simple docstring"""
return self.sp_model.IdToPiece(a_ )
def A ( self : Optional[Any] , a_ : int ):
"""simple docstring"""
__snake_case = self.sp_model.decode_pieces(a_ )
return out_string
def A ( self : Union[str, Any] , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
__snake_case = [self.sep_token_id]
__snake_case = [self.cls_token_id]
if token_ids_a is None:
return cls + token_ids_a + sep
return cls + token_ids_a + sep + token_ids_a + sep
def A ( self : List[str] , a_ : List[int] , a_ : Optional[List[int]] = None , a_ : bool = False ):
"""simple docstring"""
if already_has_special_tokens:
if token_ids_a is not None:
raise ValueError(
"You should not supply a second sequence if the provided sequence of "
"ids is already formatted with special tokens for the model." )
return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]
if token_ids_a is not None:
return [1] + ([0] * len(a_ )) + [1] + ([0] * len(a_ )) + [1]
return [1] + ([0] * len(a_ )) + [1]
def A ( self : Tuple , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
__snake_case = [self.sep_token_id]
__snake_case = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def A ( self : List[Any] , a_ : str , a_ : Optional[str] = None ):
"""simple docstring"""
if not os.path.isdir(a_ ):
logger.error("Vocabulary path ({}) should be a directory".format(a_ ) )
return
__snake_case = 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_ ):
copyfile(self.vocab_file , a_ )
return (out_vocab_file,)
| 69 | 1 |
'''simple docstring'''
import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel
from ...utils import logging
a : Union[str, Any] = logging.get_logger(__name__)
def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : int ) -> Any:
__snake_case = nn.functional.normalize(_UpperCAmelCase )
__snake_case = nn.functional.normalize(_UpperCAmelCase )
return torch.mm(_UpperCAmelCase , normalized_text_embeds.t() )
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = CLIPConfig
__SCREAMING_SNAKE_CASE = ["""CLIPEncoderLayer"""]
def __init__( self : List[str] , a_ : CLIPConfig ):
"""simple docstring"""
super().__init__(a_ )
__snake_case = CLIPVisionModel(config.vision_config )
__snake_case = nn.Linear(config.vision_config.hidden_size , config.projection_dim , bias=a_ )
__snake_case = nn.Parameter(torch.ones(17 , config.projection_dim ) , requires_grad=a_ )
__snake_case = nn.Parameter(torch.ones(3 , config.projection_dim ) , requires_grad=a_ )
__snake_case = nn.Parameter(torch.ones(17 ) , requires_grad=a_ )
__snake_case = nn.Parameter(torch.ones(3 ) , requires_grad=a_ )
@torch.no_grad()
def A ( self : Tuple , a_ : Optional[Any] , a_ : Tuple ):
"""simple docstring"""
__snake_case = self.vision_model(a_ )[1] # pooled_output
__snake_case = self.visual_projection(a_ )
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
__snake_case = cosine_distance(a_ , self.special_care_embeds ).cpu().float().numpy()
__snake_case = cosine_distance(a_ , self.concept_embeds ).cpu().float().numpy()
__snake_case = []
__snake_case = image_embeds.shape[0]
for i in range(a_ ):
__snake_case = {"special_scores": {}, "special_care": [], "concept_scores": {}, "bad_concepts": []}
# increase this value to create a stronger `nfsw` filter
# at the cost of increasing the possibility of filtering benign images
__snake_case = 0.0
for concept_idx in range(len(special_cos_dist[0] ) ):
__snake_case = special_cos_dist[i][concept_idx]
__snake_case = self.special_care_embeds_weights[concept_idx].item()
__snake_case = round(concept_cos - concept_threshold + adjustment , 3 )
if result_img["special_scores"][concept_idx] > 0:
result_img["special_care"].append({concept_idx, result_img["special_scores"][concept_idx]} )
__snake_case = 0.01
for concept_idx in range(len(cos_dist[0] ) ):
__snake_case = cos_dist[i][concept_idx]
__snake_case = self.concept_embeds_weights[concept_idx].item()
__snake_case = round(concept_cos - concept_threshold + adjustment , 3 )
if result_img["concept_scores"][concept_idx] > 0:
result_img["bad_concepts"].append(a_ )
result.append(a_ )
__snake_case = [len(res["bad_concepts"] ) > 0 for res in result]
return images, has_nsfw_concepts
@torch.no_grad()
def A ( self : List[Any] , a_ : torch.FloatTensor , a_ : torch.FloatTensor ):
"""simple docstring"""
__snake_case = self.vision_model(a_ )[1] # pooled_output
__snake_case = self.visual_projection(a_ )
__snake_case = cosine_distance(a_ , self.special_care_embeds )
__snake_case = cosine_distance(a_ , self.concept_embeds )
# increase this value to create a stronger `nsfw` filter
# at the cost of increasing the possibility of filtering benign images
__snake_case = 0.0
__snake_case = special_cos_dist - self.special_care_embeds_weights + adjustment
# special_scores = special_scores.round(decimals=3)
__snake_case = torch.any(special_scores > 0 , dim=1 )
__snake_case = special_care * 0.01
__snake_case = special_adjustment.unsqueeze(1 ).expand(-1 , cos_dist.shape[1] )
__snake_case = (cos_dist - self.concept_embeds_weights) + special_adjustment
# concept_scores = concept_scores.round(decimals=3)
__snake_case = torch.any(concept_scores > 0 , dim=1 )
return images, has_nsfw_concepts
| 69 |
'''simple docstring'''
import os
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from huggingface_hub import HfFolder, delete_repo
from huggingface_hub.file_download import http_get
from requests.exceptions import HTTPError
from transformers import (
AlbertTokenizer,
AutoTokenizer,
BertTokenizer,
BertTokenizerFast,
GPTaTokenizerFast,
is_tokenizers_available,
)
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers
from transformers.tokenization_utils import Trie
sys.path.append(str(Path(__file__).parent.parent / '''utils'''))
from test_module.custom_tokenization import CustomTokenizer # noqa E402
if is_tokenizers_available():
from test_module.custom_tokenization_fast import CustomTokenizerFast
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = mock.Mock()
__snake_case = 500
__snake_case = {}
__snake_case = HTTPError
__snake_case = {}
# Download this model to make sure it's in the cache.
__snake_case = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" )
# Under the mock environment we get a 500 error when trying to reach the tokenizer.
with mock.patch("requests.Session.request" , return_value=a_ ) as mock_head:
__snake_case = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" )
# This check we did call the fake head request
mock_head.assert_called()
@require_tokenizers
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = mock.Mock()
__snake_case = 500
__snake_case = {}
__snake_case = HTTPError
__snake_case = {}
# Download this model to make sure it's in the cache.
__snake_case = GPTaTokenizerFast.from_pretrained("gpt2" )
# Under the mock environment we get a 500 error when trying to reach the tokenizer.
with mock.patch("requests.Session.request" , return_value=a_ ) as mock_head:
__snake_case = GPTaTokenizerFast.from_pretrained("gpt2" )
# This check we did call the fake head request
mock_head.assert_called()
def A ( self : Optional[Any] ):
"""simple docstring"""
try:
__snake_case = tempfile.mktemp()
with open(a_ , "wb" ) as f:
http_get("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" , a_ )
__snake_case = AlbertTokenizer.from_pretrained(a_ )
finally:
os.remove(a_ )
# Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in
# the current folder and have the right name.
if os.path.isfile("tokenizer.json" ):
# We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it.
return
try:
with open("tokenizer.json" , "wb" ) as f:
http_get("https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json" , a_ )
__snake_case = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" )
# The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000
self.assertEqual(tokenizer.vocab_size , 1_000 )
# Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file.
finally:
os.remove("tokenizer.json" )
def A ( self : str ):
"""simple docstring"""
__snake_case = AlbertTokenizer.from_pretrained("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" )
@is_staging_test
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
__SCREAMING_SNAKE_CASE = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""]
@classmethod
def A ( cls : List[Any] ):
"""simple docstring"""
__snake_case = TOKEN
HfFolder.save_token(a_ )
@classmethod
def A ( cls : List[Any] ):
"""simple docstring"""
try:
delete_repo(token=cls._token , repo_id="test-tokenizer" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="valid_org/test-tokenizer-org" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="test-dynamic-tokenizer" )
except HTTPError:
pass
def A ( self : int ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = BertTokenizer(a_ )
tokenizer.push_to_hub("test-tokenizer" , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
# Reset repo
delete_repo(token=self._token , repo_id="test-tokenizer" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(a_ , repo_id="test-tokenizer" , push_to_hub=a_ , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
def A ( self : int ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = BertTokenizer(a_ )
tokenizer.push_to_hub("valid_org/test-tokenizer-org" , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
# Reset repo
delete_repo(token=self._token , repo_id="valid_org/test-tokenizer-org" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(
a_ , repo_id="valid_org/test-tokenizer-org" , push_to_hub=a_ , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
@require_tokenizers
def A ( self : List[str] ):
"""simple docstring"""
CustomTokenizer.register_for_auto_class()
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = CustomTokenizer(a_ )
# No fast custom tokenizer
tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token )
__snake_case = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=a_ )
# Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module
self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizer" )
# Fast and slow custom tokenizer
CustomTokenizerFast.register_for_auto_class()
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = BertTokenizerFast.from_pretrained(a_ )
bert_tokenizer.save_pretrained(a_ )
__snake_case = CustomTokenizerFast.from_pretrained(a_ )
tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token )
__snake_case = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=a_ )
# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizerFast" )
__snake_case = AutoTokenizer.from_pretrained(
f'''{USER}/test-dynamic-tokenizer''' , use_fast=a_ , trust_remote_code=a_ )
# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizer" )
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def A ( self : Optional[int] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("Hello 友達" )
self.assertEqual(trie.data , {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}} )
trie.add("Hello" )
trie.data
self.assertEqual(trie.data , {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}} )
def A ( self : str ):
"""simple docstring"""
__snake_case = Trie()
self.assertEqual(trie.split("[CLS] This is a extra_id_100" ) , ["[CLS] This is a extra_id_100"] )
trie.add("[CLS]" )
trie.add("extra_id_1" )
trie.add("extra_id_100" )
self.assertEqual(trie.split("[CLS] This is a extra_id_100" ) , ["[CLS]", " This is a ", "extra_id_100"] )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("A" )
self.assertEqual(trie.split("ABC" ) , ["A", "BC"] )
self.assertEqual(trie.split("BCA" ) , ["BC", "A"] )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("TOKEN]" )
trie.add("[SPECIAL_TOKEN]" )
self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] )
def A ( self : str ):
"""simple docstring"""
__snake_case = Trie()
trie.add("A" )
trie.add("P" )
trie.add("[SPECIAL_TOKEN]" )
self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] )
def A ( self : Optional[int] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("AB" )
trie.add("B" )
trie.add("C" )
self.assertEqual(trie.split("ABC" ) , ["AB", "C"] )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = Trie()
trie.add("ABC" )
trie.add("B" )
trie.add("CD" )
self.assertEqual(trie.split("ABCD" ) , ["ABC", "D"] )
def A ( self : Any ):
"""simple docstring"""
__snake_case = Trie()
__snake_case = trie.cut_text("ABC" , [0, 0, 2, 1, 2, 3] )
self.assertEqual(a_ , ["AB", "C"] )
| 69 | 1 |
'''simple docstring'''
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import GLPNImageProcessor
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def __init__( self : int , a_ : Any , a_ : Tuple=7 , a_ : Dict=3 , a_ : Any=18 , a_ : Tuple=30 , a_ : Optional[Any]=400 , a_ : Union[str, Any]=True , a_ : List[Any]=32 , a_ : int=True , ):
"""simple docstring"""
__snake_case = parent
__snake_case = batch_size
__snake_case = num_channels
__snake_case = image_size
__snake_case = min_resolution
__snake_case = max_resolution
__snake_case = do_resize
__snake_case = size_divisor
__snake_case = do_rescale
def A ( self : Tuple ):
"""simple docstring"""
return {
"do_resize": self.do_resize,
"size_divisor": self.size_divisor,
"do_rescale": self.do_rescale,
}
@require_torch
@require_vision
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = GLPNImageProcessor if is_vision_available() else None
def A ( self : Any ):
"""simple docstring"""
__snake_case = GLPNImageProcessingTester(self )
@property
def A ( self : List[str] ):
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(a_ , "do_resize" ) )
self.assertTrue(hasattr(a_ , "size_divisor" ) )
self.assertTrue(hasattr(a_ , "resample" ) )
self.assertTrue(hasattr(a_ , "do_rescale" ) )
def A ( self : List[str] ):
"""simple docstring"""
pass
def A ( self : Dict ):
"""simple docstring"""
__snake_case = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
__snake_case = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ )
for image in image_inputs:
self.assertIsInstance(a_ , Image.Image )
# Test not batched input (GLPNImageProcessor doesn't support batching)
__snake_case = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 )
self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
__snake_case = 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 (GLPNImageProcessor doesn't support batching)
__snake_case = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 )
self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
__snake_case = 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 (GLPNImageProcessor doesn't support batching)
__snake_case = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 )
self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> int:
assert (
isinstance(_UpperCAmelCase , _UpperCAmelCase ) and number_of_steps > 0
), F'''number_of_steps needs to be positive integer, your input {number_of_steps}'''
if number_of_steps == 1:
return 1
__snake_case , __snake_case = 1, 1
for _ in range(number_of_steps - 1 ):
__snake_case , __snake_case = current + previous, current
return current
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 | 1 |
'''simple docstring'''
from __future__ import annotations
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> list[int]:
__snake_case = 2
__snake_case = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(_UpperCAmelCase )
if n > 1:
factors.append(_UpperCAmelCase )
return factors
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> str:
return " ".join(
"".join(word[::-1] ) if len(_UpperCAmelCase ) > 4 else word for word in sentence.split() )
if __name__ == "__main__":
import doctest
doctest.testmod()
print(reverse_long_words('''Hey wollef sroirraw'''))
| 69 | 1 |
'''simple docstring'''
import enum
import shutil
import sys
a , a : List[str] = shutil.get_terminal_size()
a : str = {'''UP''': '''A''', '''DOWN''': '''B''', '''RIGHT''': '''C''', '''LEFT''': '''D'''}
class SCREAMING_SNAKE_CASE__ ( enum.Enum ):
__SCREAMING_SNAKE_CASE = 0
__SCREAMING_SNAKE_CASE = 1
def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : Tuple="" ) -> List[Any]:
sys.stdout.write(str(_UpperCAmelCase ) + end )
sys.stdout.flush()
def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : List[str]="" ) -> Optional[int]:
forceWrite(F'''\u001b[{color}m{content}\u001b[0m''' , _UpperCAmelCase )
def __UpperCAmelCase ( ) -> Union[str, Any]:
forceWrite("\r" )
def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : str ) -> Optional[Any]:
forceWrite(F'''\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}''' )
def __UpperCAmelCase ( ) -> int:
forceWrite(" " * TERMINAL_WIDTH )
reset_cursor()
def __UpperCAmelCase ( ) -> Optional[int]:
reset_cursor()
forceWrite("-" * TERMINAL_WIDTH )
| 69 |
'''simple docstring'''
import unittest
from transformers import MPNetConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
MPNetForMaskedLM,
MPNetForMultipleChoice,
MPNetForQuestionAnswering,
MPNetForSequenceClassification,
MPNetForTokenClassification,
MPNetModel,
)
class SCREAMING_SNAKE_CASE__ :
def __init__( self : str , a_ : Any , a_ : Union[str, Any]=13 , a_ : Any=7 , a_ : Any=True , a_ : Dict=True , a_ : Union[str, Any]=False , a_ : Tuple=True , a_ : str=99 , a_ : Tuple=64 , a_ : Tuple=5 , a_ : Union[str, Any]=4 , a_ : Dict=64 , a_ : Union[str, Any]="gelu" , a_ : Dict=0.1 , a_ : List[str]=0.1 , a_ : Dict=512 , a_ : Tuple=16 , a_ : str=2 , a_ : Any=0.02 , a_ : List[Any]=3 , a_ : Tuple=4 , a_ : Optional[int]=None , ):
"""simple docstring"""
__snake_case = parent
__snake_case = batch_size
__snake_case = seq_length
__snake_case = is_training
__snake_case = use_input_mask
__snake_case = use_token_type_ids
__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_act
__snake_case = hidden_dropout_prob
__snake_case = attention_probs_dropout_prob
__snake_case = max_position_embeddings
__snake_case = type_vocab_size
__snake_case = type_sequence_label_size
__snake_case = initializer_range
__snake_case = num_labels
__snake_case = num_choices
__snake_case = scope
def A ( self : int ):
"""simple docstring"""
return MPNetConfig.from_pretrained("microsoft/mpnet-base" )
def A ( self : str ):
"""simple docstring"""
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__snake_case = None
if self.use_input_mask:
__snake_case = random_attention_mask([self.batch_size, self.seq_length] )
__snake_case = None
__snake_case = None
__snake_case = None
if self.use_labels:
__snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__snake_case = ids_tensor([self.batch_size] , self.num_choices )
__snake_case = self.get_config()
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
def A ( self : List[str] ):
"""simple docstring"""
return MPNetConfig(
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 , initializer_range=self.initializer_range , )
def A ( self : Tuple , a_ : int , a_ : str , a_ : Optional[int] , a_ : List[Any] , a_ : str , a_ : Optional[Any] ):
"""simple docstring"""
__snake_case = MPNetModel(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , a_ )
__snake_case = model(a_ )
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 A ( self : Any , a_ : int , a_ : Tuple , a_ : str , a_ : int , a_ : str , a_ : List[Any] ):
"""simple docstring"""
__snake_case = MPNetForQuestionAnswering(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(
a_ , attention_mask=a_ , start_positions=a_ , end_positions=a_ , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def A ( self : Any , a_ : Any , a_ : int , a_ : Union[str, Any] , a_ : Dict , a_ : Optional[Any] , a_ : Any ):
"""simple docstring"""
__snake_case = self.num_labels
__snake_case = MPNetForSequenceClassification(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def A ( self : Optional[Any] , a_ : Any , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : List[Any] , a_ : List[Any] ):
"""simple docstring"""
__snake_case = self.num_choices
__snake_case = MPNetForMultipleChoice(config=a_ )
model.to(a_ )
model.eval()
__snake_case = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__snake_case = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__snake_case = model(
a_ , attention_mask=a_ , labels=a_ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def A ( self : Dict , a_ : List[str] , a_ : str , a_ : Union[str, Any] , a_ : str , a_ : Optional[int] , a_ : Optional[Any] ):
"""simple docstring"""
__snake_case = self.num_labels
__snake_case = MPNetForTokenClassification(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.prepare_config_and_inputs()
((__snake_case) , (__snake_case) , (__snake_case) , (__snake_case) , (__snake_case) , (__snake_case)) = config_and_inputs
__snake_case = {"input_ids": input_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = (
(
MPNetForMaskedLM,
MPNetForMultipleChoice,
MPNetForQuestionAnswering,
MPNetForSequenceClassification,
MPNetForTokenClassification,
MPNetModel,
)
if is_torch_available()
else ()
)
__SCREAMING_SNAKE_CASE = (
{
"""feature-extraction""": MPNetModel,
"""fill-mask""": MPNetForMaskedLM,
"""question-answering""": MPNetForQuestionAnswering,
"""text-classification""": MPNetForSequenceClassification,
"""token-classification""": MPNetForTokenClassification,
"""zero-shot""": MPNetForSequenceClassification,
}
if is_torch_available()
else {}
)
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = True
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = MPNetModelTester(self )
__snake_case = ConfigTester(self , config_class=a_ , hidden_size=37 )
def A ( self : List[Any] ):
"""simple docstring"""
self.config_tester.run_common_tests()
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_model(*a_ )
def A ( self : Dict ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_sequence_classification(*a_ )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_multiple_choice(*a_ )
def A ( self : int ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_token_classification(*a_ )
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_question_answering(*a_ )
@require_torch
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
@slow
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = MPNetModel.from_pretrained("microsoft/mpnet-base" )
__snake_case = torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] )
__snake_case = model(a_ )[0]
__snake_case = torch.Size((1, 11, 768) )
self.assertEqual(output.shape , a_ )
__snake_case = torch.tensor(
[[[-0.0550, 0.1943, -0.0740], [-0.0562, 0.2211, -0.0579], [-0.0437, 0.3337, -0.0641]]] )
# compare the actual values for a slice.
self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) )
| 69 | 1 |
'''simple docstring'''
import json
import os
import torch
from diffusers import UNetaDModel
os.makedirs('''hub/hopper-medium-v2/unet/hor32''', exist_ok=True)
os.makedirs('''hub/hopper-medium-v2/unet/hor128''', exist_ok=True)
os.makedirs('''hub/hopper-medium-v2/value_function''', exist_ok=True)
def __UpperCAmelCase ( _UpperCAmelCase : List[str] ) -> str:
if hor == 1_28:
__snake_case = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D")
__snake_case = (32, 1_28, 2_56)
__snake_case = ("UpResnetBlock1D", "UpResnetBlock1D")
elif hor == 32:
__snake_case = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D")
__snake_case = (32, 64, 1_28, 2_56)
__snake_case = ("UpResnetBlock1D", "UpResnetBlock1D", "UpResnetBlock1D")
__snake_case = torch.load(F'''/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch''' )
__snake_case = model.state_dict()
__snake_case = {
"down_block_types": down_block_types,
"block_out_channels": block_out_channels,
"up_block_types": up_block_types,
"layers_per_block": 1,
"use_timestep_embedding": True,
"out_block_type": "OutConv1DBlock",
"norm_num_groups": 8,
"downsample_each_block": False,
"in_channels": 14,
"out_channels": 14,
"extra_in_channels": 0,
"time_embedding_type": "positional",
"flip_sin_to_cos": False,
"freq_shift": 1,
"sample_size": 6_55_36,
"mid_block_type": "MidResTemporalBlock1D",
"act_fn": "mish",
}
__snake_case = UNetaDModel(**_UpperCAmelCase )
print(F'''length of state dict: {len(state_dict.keys() )}''' )
print(F'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' )
__snake_case = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) )
for k, v in mapping.items():
__snake_case = state_dict.pop(_UpperCAmelCase )
hf_value_function.load_state_dict(_UpperCAmelCase )
torch.save(hf_value_function.state_dict() , F'''hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin''' )
with open(F'''hub/hopper-medium-v2/unet/hor{hor}/config.json''' , "w" ) as f:
json.dump(_UpperCAmelCase , _UpperCAmelCase )
def __UpperCAmelCase ( ) -> List[Any]:
__snake_case = {
"in_channels": 14,
"down_block_types": ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D"),
"up_block_types": (),
"out_block_type": "ValueFunction",
"mid_block_type": "ValueFunctionMidBlock1D",
"block_out_channels": (32, 64, 1_28, 2_56),
"layers_per_block": 1,
"downsample_each_block": True,
"sample_size": 6_55_36,
"out_channels": 14,
"extra_in_channels": 0,
"time_embedding_type": "positional",
"use_timestep_embedding": True,
"flip_sin_to_cos": False,
"freq_shift": 1,
"norm_num_groups": 8,
"act_fn": "mish",
}
__snake_case = torch.load("/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch" )
__snake_case = model
__snake_case = UNetaDModel(**_UpperCAmelCase )
print(F'''length of state dict: {len(state_dict.keys() )}''' )
print(F'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' )
__snake_case = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) )
for k, v in mapping.items():
__snake_case = state_dict.pop(_UpperCAmelCase )
hf_value_function.load_state_dict(_UpperCAmelCase )
torch.save(hf_value_function.state_dict() , "hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin" )
with open("hub/hopper-medium-v2/value_function/config.json" , "w" ) as f:
json.dump(_UpperCAmelCase , _UpperCAmelCase )
if __name__ == "__main__":
unet(32)
# unet(128)
value_function()
| 69 |
'''simple docstring'''
# Logistic Regression from scratch
# In[62]:
# In[63]:
# importing all the required libraries
import numpy as np
from matplotlib import pyplot as plt
from sklearn import datasets
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> Optional[int]:
return 1 / (1 + np.exp(-z ))
def __UpperCAmelCase ( _UpperCAmelCase : Tuple , _UpperCAmelCase : Dict ) -> List[str]:
return (-y * np.log(_UpperCAmelCase ) - (1 - y) * np.log(1 - h )).mean()
def __UpperCAmelCase ( _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : List[Any] ) -> Optional[Any]:
__snake_case = np.dot(_UpperCAmelCase , _UpperCAmelCase )
return np.sum(y * scores - np.log(1 + np.exp(_UpperCAmelCase ) ) )
def __UpperCAmelCase ( _UpperCAmelCase : List[Any] , _UpperCAmelCase : str , _UpperCAmelCase : Dict , _UpperCAmelCase : List[str]=7_00_00 ) -> Union[str, Any]:
__snake_case = np.zeros(x.shape[1] )
for iterations in range(_UpperCAmelCase ):
__snake_case = np.dot(_UpperCAmelCase , _UpperCAmelCase )
__snake_case = sigmoid_function(_UpperCAmelCase )
__snake_case = np.dot(x.T , h - y ) / y.size
__snake_case = theta - alpha * gradient # updating the weights
__snake_case = np.dot(_UpperCAmelCase , _UpperCAmelCase )
__snake_case = sigmoid_function(_UpperCAmelCase )
__snake_case = cost_function(_UpperCAmelCase , _UpperCAmelCase )
if iterations % 1_00 == 0:
print(F'''loss: {j} \t''' ) # printing the loss after every 100 iterations
return theta
# In[68]:
if __name__ == "__main__":
a : int = datasets.load_iris()
a : int = iris.data[:, :2]
a : Optional[Any] = (iris.target != 0) * 1
a : Tuple = 0.1
a : List[str] = logistic_reg(alpha, x, y, max_iterations=70_000)
print('''theta: ''', theta) # printing the theta i.e our weights vector
def __UpperCAmelCase ( _UpperCAmelCase : Optional[int] ) -> Union[str, Any]:
return sigmoid_function(
np.dot(_UpperCAmelCase , _UpperCAmelCase ) ) # predicting the value of probability from the logistic regression algorithm
plt.figure(figsize=(10, 6))
plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color='''b''', label='''0''')
plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color='''r''', label='''1''')
((a) , (a)) : Any = (x[:, 0].min(), x[:, 0].max())
((a) , (a)) : Any = (x[:, 1].min(), x[:, 1].max())
((a) , (a)) : Any = np.meshgrid(np.linspace(xa_min, xa_max), np.linspace(xa_min, xa_max))
a : Optional[Any] = np.c_[xxa.ravel(), xxa.ravel()]
a : List[Any] = predict_prob(grid).reshape(xxa.shape)
plt.contour(xxa, xxa, probs, [0.5], linewidths=1, colors='''black''')
plt.legend()
plt.show()
| 69 | 1 |
'''simple docstring'''
from typing import Callable, Optional
from .. import Features
from ..packaged_modules.generator.generator import Generator
from .abc import AbstractDatasetInputStream
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def __init__( self : List[str] , a_ : Callable , a_ : Optional[Features] = None , a_ : str = None , a_ : bool = False , a_ : bool = False , a_ : Optional[dict] = None , a_ : Optional[int] = None , **a_ : str , ):
"""simple docstring"""
super().__init__(
features=a_ , cache_dir=a_ , keep_in_memory=a_ , streaming=a_ , num_proc=a_ , **a_ , )
__snake_case = Generator(
cache_dir=a_ , features=a_ , generator=a_ , gen_kwargs=a_ , **a_ , )
def A ( self : Dict ):
"""simple docstring"""
if self.streaming:
__snake_case = self.builder.as_streaming_dataset(split="train" )
# Build regular (map-style) dataset
else:
__snake_case = None
__snake_case = None
__snake_case = None
__snake_case = None
self.builder.download_and_prepare(
download_config=a_ , download_mode=a_ , verification_mode=a_ , base_path=a_ , num_proc=self.num_proc , )
__snake_case = self.builder.as_dataset(
split="train" , verification_mode=a_ , in_memory=self.keep_in_memory )
return dataset
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> bool:
return number & 1 == 0
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 | 1 |
'''simple docstring'''
import argparse
import torch
from torch import nn
from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration
def __UpperCAmelCase ( _UpperCAmelCase : List[str] ) -> Union[str, Any]:
__snake_case = [
"encoder.version",
"decoder.version",
"model.encoder.version",
"model.decoder.version",
"decoder.output_projection.weight",
"_float_tensor",
"encoder.embed_positions._float_tensor",
"decoder.embed_positions._float_tensor",
]
for k in ignore_keys:
state_dict.pop(_UpperCAmelCase , _UpperCAmelCase )
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] ) -> List[Any]:
__snake_case , __snake_case = emb.weight.shape
__snake_case = nn.Linear(_UpperCAmelCase , _UpperCAmelCase , bias=_UpperCAmelCase )
__snake_case = emb.weight.data
return lin_layer
def __UpperCAmelCase ( _UpperCAmelCase : List[str] ) -> List[Any]:
__snake_case = torch.load(_UpperCAmelCase , map_location="cpu" )
__snake_case = mam_aaa["args"] or mam_aaa["cfg"]["model"]
__snake_case = mam_aaa["model"]
remove_ignore_keys_(_UpperCAmelCase )
__snake_case = state_dict["encoder.embed_tokens.weight"].shape[0]
__snake_case = MaMaaaConfig(
vocab_size=_UpperCAmelCase , max_position_embeddings=10_24 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="relu" , )
__snake_case = state_dict["decoder.embed_tokens.weight"]
__snake_case = MaMaaaForConditionalGeneration(_UpperCAmelCase )
model.model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase )
__snake_case = make_linear_from_emb(model.model.shared )
return model
if __name__ == "__main__":
a : List[str] = argparse.ArgumentParser()
# Required parameters
parser.add_argument('''fairseq_path''', type=str, help='''path to a model.pt on local filesystem.''')
parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
a : Optional[int] = parser.parse_args()
a : List[Any] = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß)
model.save_pretrained(args.pytorch_dump_folder_path)
| 69 |
'''simple docstring'''
import argparse
from pathlib import Path
import torch
from transformers import OPTConfig, OPTModel
from transformers.utils import logging
logging.set_verbosity_info()
a : List[str] = logging.get_logger(__name__)
def __UpperCAmelCase ( _UpperCAmelCase : Dict ) -> Union[str, Any]:
__snake_case = torch.load(_UpperCAmelCase , map_location="cpu" )
if "model" in sd.keys():
__snake_case = torch.load(_UpperCAmelCase , map_location="cpu" )["model"]
# pop unnecessary weights
__snake_case = [
"decoder.version",
"decoder.output_projection.weight",
]
for key in keys_to_delete:
if key in sd:
sd.pop(_UpperCAmelCase )
__snake_case = {
"decoder.project_in_dim.weight": "decoder.project_in.weight",
"decoder.project_out_dim.weight": "decoder.project_out.weight",
"decoder.layer_norm.weight": "decoder.final_layer_norm.weight",
"decoder.layer_norm.bias": "decoder.final_layer_norm.bias",
}
for old_key, new_key in keys_to_rename.items():
if old_key in sd:
__snake_case = sd.pop(_UpperCAmelCase )
__snake_case = list(sd.keys() )
for key in keys:
if ".qkv_proj." in key:
__snake_case = sd[key]
# We split QKV in separate Q,K,V
__snake_case = key.replace(".qkv_proj." , ".q_proj." )
__snake_case = key.replace(".qkv_proj." , ".k_proj." )
__snake_case = key.replace(".qkv_proj." , ".v_proj." )
__snake_case = value.shape[0]
assert depth % 3 == 0
# `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming:
# https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97
__snake_case , __snake_case , __snake_case = torch.split(_UpperCAmelCase , depth // 3 , dim=0 )
__snake_case = q
__snake_case = k
__snake_case = v
del sd[key]
return sd
@torch.no_grad()
def __UpperCAmelCase ( _UpperCAmelCase : List[str] , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : int=None ) -> Any:
__snake_case = load_checkpoint(_UpperCAmelCase )
if config is not None:
__snake_case = OPTConfig.from_pretrained(_UpperCAmelCase )
else:
__snake_case = OPTConfig()
__snake_case = OPTModel(_UpperCAmelCase ).half().eval()
model.load_state_dict(_UpperCAmelCase )
# Check results
Path(_UpperCAmelCase ).mkdir(exist_ok=_UpperCAmelCase )
model.save_pretrained(_UpperCAmelCase )
if __name__ == "__main__":
a : int = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--fairseq_path''',
type=str,
help=(
'''path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:'''
''' https://huggingface.co/models?other=opt_metasq'''
),
)
parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
parser.add_argument('''--hf_config''', default=None, type=str, help='''Define HF config.''')
a : Optional[int] = parser.parse_args()
convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
| 69 | 1 |
'''simple docstring'''
import collections
import inspect
import unittest
from transformers import SwinvaConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _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 SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel
from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class SCREAMING_SNAKE_CASE__ :
def __init__( self : int , a_ : List[str] , a_ : Union[str, Any]=13 , a_ : Optional[int]=32 , a_ : int=2 , a_ : str=3 , a_ : Tuple=16 , a_ : Optional[Any]=[1, 2, 1] , a_ : int=[2, 2, 4] , a_ : List[Any]=2 , a_ : List[str]=2.0 , a_ : Optional[int]=True , a_ : Union[str, Any]=0.0 , a_ : Any=0.0 , a_ : Tuple=0.1 , a_ : Tuple="gelu" , a_ : List[str]=False , a_ : List[str]=True , a_ : Optional[Any]=0.02 , a_ : List[Any]=1e-5 , a_ : Optional[Any]=True , a_ : Any=None , a_ : Dict=True , a_ : Dict=10 , a_ : Dict=8 , ):
"""simple docstring"""
__snake_case = parent
__snake_case = batch_size
__snake_case = image_size
__snake_case = patch_size
__snake_case = num_channels
__snake_case = embed_dim
__snake_case = depths
__snake_case = num_heads
__snake_case = window_size
__snake_case = mlp_ratio
__snake_case = qkv_bias
__snake_case = hidden_dropout_prob
__snake_case = attention_probs_dropout_prob
__snake_case = drop_path_rate
__snake_case = hidden_act
__snake_case = use_absolute_embeddings
__snake_case = patch_norm
__snake_case = layer_norm_eps
__snake_case = initializer_range
__snake_case = is_training
__snake_case = scope
__snake_case = use_labels
__snake_case = type_sequence_label_size
__snake_case = encoder_stride
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
__snake_case = None
if self.use_labels:
__snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__snake_case = self.get_config()
return config, pixel_values, labels
def A ( self : List[str] ):
"""simple docstring"""
return SwinvaConfig(
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 , )
def A ( self : List[Any] , a_ : Any , a_ : Any , a_ : int ):
"""simple docstring"""
__snake_case = SwinvaModel(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ )
__snake_case = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1))
__snake_case = 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 A ( self : Optional[int] , a_ : Optional[Any] , a_ : Union[str, Any] , a_ : Dict ):
"""simple docstring"""
__snake_case = SwinvaForMaskedImageModeling(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ )
self.parent.assertEqual(
result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) )
# test greyscale images
__snake_case = 1
__snake_case = SwinvaForMaskedImageModeling(a_ )
model.to(a_ )
model.eval()
__snake_case = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
__snake_case = model(a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) )
def A ( self : List[Any] , a_ : List[Any] , a_ : Any , a_ : Optional[int] ):
"""simple docstring"""
__snake_case = self.type_sequence_label_size
__snake_case = SwinvaForImageClassification(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , labels=a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.prepare_config_and_inputs()
__snake_case , __snake_case , __snake_case = config_and_inputs
__snake_case = {"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = (
(SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else ()
)
__SCREAMING_SNAKE_CASE = (
{"""feature-extraction""": SwinvaModel, """image-classification""": SwinvaForImageClassification}
if is_torch_available()
else {}
)
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = False
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = SwinvaModelTester(self )
__snake_case = ConfigTester(self , config_class=a_ , embed_dim=37 )
def A ( self : List[Any] ):
"""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"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*a_ )
@unittest.skip(reason="Got `CUDA error: misaligned address` with PyTorch 2.0.0." )
def A ( self : Union[str, Any] ):
"""simple docstring"""
pass
@unittest.skip(reason="Swinv2 does not use inputs_embeds" )
def A ( self : str ):
"""simple docstring"""
pass
def A ( self : int ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__snake_case = model_class(a_ )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
__snake_case = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(a_ , nn.Linear ) )
def A ( self : List[str] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__snake_case = model_class(a_ )
__snake_case = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__snake_case = [*signature.parameters.keys()]
__snake_case = ["pixel_values"]
self.assertListEqual(arg_names[:1] , a_ )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = True
for model_class in self.all_model_classes:
__snake_case = True
__snake_case = False
__snake_case = True
__snake_case = model_class(a_ )
model.to(a_ )
model.eval()
with torch.no_grad():
__snake_case = model(**self._prepare_for_class(a_ , a_ ) )
__snake_case = outputs.attentions
__snake_case = len(self.model_tester.depths )
self.assertEqual(len(a_ ) , a_ )
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
__snake_case = True
__snake_case = config.window_size**2
__snake_case = model_class(a_ )
model.to(a_ )
model.eval()
with torch.no_grad():
__snake_case = model(**self._prepare_for_class(a_ , a_ ) )
__snake_case = outputs.attentions
self.assertEqual(len(a_ ) , a_ )
self.assertListEqual(
list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , )
__snake_case = len(a_ )
# Check attention is always last and order is fine
__snake_case = True
__snake_case = True
__snake_case = model_class(a_ )
model.to(a_ )
model.eval()
with torch.no_grad():
__snake_case = model(**self._prepare_for_class(a_ , a_ ) )
if hasattr(self.model_tester , "num_hidden_states_types" ):
__snake_case = self.model_tester.num_hidden_states_types
else:
# also another +1 for reshaped_hidden_states
__snake_case = 2
self.assertEqual(out_len + added_hidden_states , len(a_ ) )
__snake_case = outputs.attentions
self.assertEqual(len(a_ ) , a_ )
self.assertListEqual(
list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , )
def A ( self : List[Any] , a_ : Tuple , a_ : int , a_ : Any , a_ : Dict ):
"""simple docstring"""
__snake_case = model_class(a_ )
model.to(a_ )
model.eval()
with torch.no_grad():
__snake_case = model(**self._prepare_for_class(a_ , a_ ) )
__snake_case = outputs.hidden_states
__snake_case = getattr(
self.model_tester , "expected_num_hidden_layers" , len(self.model_tester.depths ) + 1 )
self.assertEqual(len(a_ ) , a_ )
# Swinv2 has a different seq_length
__snake_case = (
config.patch_size
if isinstance(config.patch_size , collections.abc.Iterable )
else (config.patch_size, config.patch_size)
)
__snake_case = (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] , )
__snake_case = outputs.reshaped_hidden_states
self.assertEqual(len(a_ ) , a_ )
__snake_case , __snake_case , __snake_case , __snake_case = reshaped_hidden_states[0].shape
__snake_case = (
reshaped_hidden_states[0].view(a_ , a_ , height * width ).permute(0 , 2 , 1 )
)
self.assertListEqual(
list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = (
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:
__snake_case = True
self.check_hidden_states_output(a_ , a_ , a_ , a_ )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
__snake_case = True
self.check_hidden_states_output(a_ , a_ , a_ , a_ )
def A ( self : int ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = 3
__snake_case = (
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)
)
__snake_case = (
config.patch_size
if isinstance(config.patch_size , collections.abc.Iterable )
else (config.patch_size, config.patch_size)
)
__snake_case = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
__snake_case = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])
for model_class in self.all_model_classes:
__snake_case = True
self.check_hidden_states_output(a_ , a_ , a_ , (padded_height, padded_width) )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
__snake_case = True
self.check_hidden_states_output(a_ , a_ , a_ , (padded_height, padded_width) )
def A ( self : Dict ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_image_modeling(*a_ )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*a_ )
@slow
def A ( self : List[Any] ):
"""simple docstring"""
for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__snake_case = SwinvaModel.from_pretrained(a_ )
self.assertIsNotNone(a_ )
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = _config_zero_init(a_ )
for model_class in self.all_model_classes:
__snake_case = model_class(config=a_ )
for name, param in model.named_parameters():
if "embeddings" not in name and "logit_scale" not in name and param.requires_grad:
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''' , )
@require_vision
@require_torch
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
@cached_property
def A ( self : Optional[int] ):
"""simple docstring"""
return (
AutoImageProcessor.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256" )
if is_vision_available()
else None
)
@slow
def A ( self : Any ):
"""simple docstring"""
__snake_case = SwinvaForImageClassification.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256" ).to(
a_ )
__snake_case = self.default_image_processor
__snake_case = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
__snake_case = image_processor(images=a_ , return_tensors="pt" ).to(a_ )
# forward pass
with torch.no_grad():
__snake_case = model(**a_ )
# verify the logits
__snake_case = torch.Size((1, 1_000) )
self.assertEqual(outputs.logits.shape , a_ )
__snake_case = torch.tensor([-0.3947, -0.4306, 0.0026] ).to(a_ )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , a_ , atol=1e-4 ) )
| 69 |
'''simple docstring'''
from typing import List, Optional
from ...configuration_utils import PretrainedConfig
from ...utils import logging
a : List[str] = logging.get_logger(__name__)
a : Tuple = {
'''huggingface/autoformer-tourism-monthly''': '''https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json''',
}
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = """autoformer"""
__SCREAMING_SNAKE_CASE = {
"""hidden_size""": """d_model""",
"""num_attention_heads""": """encoder_attention_heads""",
"""num_hidden_layers""": """encoder_layers""",
}
def __init__( self : List[Any] , a_ : Optional[int] = None , a_ : Optional[int] = None , a_ : str = "student_t" , a_ : str = "nll" , a_ : int = 1 , a_ : List[int] = [1, 2, 3, 4, 5, 6, 7] , a_ : bool = True , a_ : int = 0 , a_ : int = 0 , a_ : int = 0 , a_ : int = 0 , a_ : Optional[List[int]] = None , a_ : Optional[List[int]] = None , a_ : int = 64 , a_ : int = 2 , a_ : int = 2 , a_ : int = 2 , a_ : int = 2 , a_ : int = 32 , a_ : int = 32 , a_ : str = "gelu" , a_ : float = 0.1 , a_ : float = 0.1 , a_ : float = 0.1 , a_ : float = 0.1 , a_ : float = 0.1 , a_ : int = 100 , a_ : float = 0.02 , a_ : bool = True , a_ : Union[str, Any]=True , a_ : int = 10 , a_ : int = 25 , a_ : int = 3 , **a_ : Tuple , ):
"""simple docstring"""
__snake_case = prediction_length
__snake_case = context_length if context_length is not None else prediction_length
__snake_case = distribution_output
__snake_case = loss
__snake_case = input_size
__snake_case = num_time_features
__snake_case = lags_sequence
__snake_case = scaling
__snake_case = num_dynamic_real_features
__snake_case = num_static_real_features
__snake_case = num_static_categorical_features
if cardinality is not None 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`" )
__snake_case = cardinality
else:
__snake_case = [0]
if embedding_dimension is not None 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`" )
__snake_case = embedding_dimension
else:
__snake_case = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality]
__snake_case = num_parallel_samples
# Transformer architecture configuration
__snake_case = input_size * len(self.lags_sequence ) + self._number_of_features
__snake_case = d_model
__snake_case = encoder_attention_heads
__snake_case = decoder_attention_heads
__snake_case = encoder_ffn_dim
__snake_case = decoder_ffn_dim
__snake_case = encoder_layers
__snake_case = decoder_layers
__snake_case = dropout
__snake_case = attention_dropout
__snake_case = activation_dropout
__snake_case = encoder_layerdrop
__snake_case = decoder_layerdrop
__snake_case = activation_function
__snake_case = init_std
__snake_case = use_cache
# Autoformer
__snake_case = label_length
__snake_case = moving_average
__snake_case = autocorrelation_factor
super().__init__(is_encoder_decoder=a_ , **a_ )
@property
def A ( self : Optional[int] ):
"""simple docstring"""
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
)
| 69 | 1 |
'''simple docstring'''
from unittest import TestCase
from datasets import Dataset
from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters
def __UpperCAmelCase ( ) -> Dict:
__snake_case = {
"repo_name": ["test_repo1", "test_repo2", "test_repo3"],
"path": ["test_1.py", "test_2.py", "unit_test.py"],
"content": ["a " * 20, "a " * 30, "b " * 7],
}
__snake_case = Dataset.from_dict(_UpperCAmelCase )
return dataset
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def A ( self : Any ):
"""simple docstring"""
__snake_case = get_dataset()
__snake_case = make_duplicate_clusters(a_ , 0.85 )
self.assertEqual(len(duplicate_clusters[0] ) , 2 )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = get_dataset()
__snake_case , __snake_case = deduplicate_dataset(a_ )
self.assertEqual(len(a_ ) , 2 )
print(a_ )
self.assertEqual(duplicate_clusters[0][0]["copies"] , 2 )
self.assertEqual(duplicate_clusters[0][0]["is_extreme"] , a_ )
| 69 |
'''simple docstring'''
import unittest
from transformers import GPTSwaTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
a : List[Any] = get_tests_dir('''fixtures/test_sentencepiece_with_bytefallback.model''')
@require_sentencepiece
@require_tokenizers
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = GPTSwaTokenizer
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = True
__SCREAMING_SNAKE_CASE = False
def A ( self : int ):
"""simple docstring"""
super().setUp()
# We have a SentencePiece fixture for testing
__snake_case = GPTSwaTokenizer(a_ , eos_token="<unk>" , bos_token="<unk>" , pad_token="<unk>" )
tokenizer.save_pretrained(self.tmpdirname )
def A ( self : str , a_ : List[Any] ):
"""simple docstring"""
__snake_case = "This is a test"
__snake_case = "This is a test"
return input_text, output_text
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = "<s>"
__snake_case = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , "<unk>" )
self.assertEqual(vocab_keys[1] , "<s>" )
self.assertEqual(vocab_keys[-1] , "j" )
self.assertEqual(len(a_ ) , 2_000 )
def A ( self : Optional[int] ):
"""simple docstring"""
self.assertEqual(self.get_tokenizer().vocab_size , 2_000 )
def A ( self : Dict ):
"""simple docstring"""
__snake_case = GPTSwaTokenizer(a_ )
__snake_case = tokenizer.tokenize("This is a test" )
self.assertListEqual(a_ , ["▁This", "▁is", "▁a", "▁t", "est"] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , [465, 287, 265, 631, 842] )
__snake_case = tokenizer.tokenize("I was born in 92000, and this is falsé." )
# fmt: off
self.assertListEqual(
a_ , ["▁I", "▁was", "▁bor", "n", "▁in", "▁", "<0x39>", "2", "0", "0", "0", ",", "▁and", "▁this", "▁is", "▁f", "al", "s", "<0xC3>", "<0xA9>", "."] , )
# fmt: on
__snake_case = tokenizer.convert_tokens_to_ids(a_ )
self.assertListEqual(
a_ , [262, 272, 1_525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260] , )
__snake_case = tokenizer.convert_ids_to_tokens(a_ )
# fmt: off
self.assertListEqual(
a_ , ["▁I", "▁was", "▁bor", "n", "▁in", "▁", "<0x39>", "2", "0", "0", "0", ",", "▁and", "▁this", "▁is", "▁f", "al", "s", "<0xC3>", "<0xA9>", "."] )
# fmt: on
def A ( self : List[str] ):
"""simple docstring"""
__snake_case = GPTSwaTokenizer(a_ )
__snake_case = ["This is a test", "I was born in 92000, and this is falsé."]
__snake_case = [
[465, 287, 265, 631, 842],
[262, 272, 1_525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260],
]
# Test that encode_fast returns the same as tokenize + convert_tokens_to_ids
for text, expected_ids in zip(a_ , a_ ):
self.assertListEqual(tokenizer.encode_fast(a_ ) , a_ )
# Test that decode_fast returns the input text
for text, token_ids in zip(a_ , a_ ):
self.assertEqual(tokenizer.decode_fast(a_ ) , a_ )
@slow
def A ( self : Any ):
"""simple docstring"""
__snake_case = [
"<|python|>def fibonacci(n)\n if n < 0:\n print('Incorrect input')",
"Hey there, how are you doing this fine day?",
"This is a text with a trailing spaces followed by a dot .",
"Häj sväjs lillebrör! =)",
"Det är inget fel på Mr. Cool",
]
# fmt: off
__snake_case = {"input_ids": [[63_423, 5, 6_811, 14_954, 282, 816, 3_821, 63_466, 63_425, 63_462, 18, 63_978, 678, 301, 1_320, 63_423, 63_455, 63_458, 18, 63_982, 4_246, 3_940, 1_901, 47_789, 5_547, 18_994], [19_630, 1_100, 63_446, 1_342, 633, 544, 4_488, 593, 5_102, 2_416, 63_495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_652, 428, 268, 1_936, 515, 268, 58_593, 22_413, 9_106, 546, 268, 33_213, 63_979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [55_130, 63_450, 924, 63_449, 2_249, 4_062, 1_558, 318, 63_504, 21_498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2_827, 2_559, 332, 6_575, 63_443, 26_801, 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]], "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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [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], [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]]}
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=a_ , model_name="AI-Sweden/gpt-sw3-126m" , sequences=a_ , )
| 69 | 1 |
'''simple docstring'''
import json
import os
import shutil
import tempfile
import unittest
from transformers import BatchEncoding, CanineTokenizer
from transformers.testing_utils import require_tokenizers, require_torch
from transformers.tokenization_utils import AddedToken
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = CanineTokenizer
__SCREAMING_SNAKE_CASE = False
def A ( self : Union[str, Any] ):
"""simple docstring"""
super().setUp()
__snake_case = CanineTokenizer()
tokenizer.save_pretrained(self.tmpdirname )
@cached_property
def A ( self : List[Any] ):
"""simple docstring"""
return CanineTokenizer.from_pretrained("google/canine-s" )
def A ( self : List[Any] , **a_ : Optional[int] ):
"""simple docstring"""
__snake_case = self.tokenizer_class.from_pretrained(self.tmpdirname , **a_ )
__snake_case = 1_024
return tokenizer
@require_torch
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = self.canine_tokenizer
__snake_case = ["Life is like a box of chocolates.", "You never know what you're gonna get."]
# fmt: off
__snake_case = [57_344, 76, 105, 102, 101, 32, 105, 115, 32, 108, 105, 107, 101, 32, 97, 32, 98, 111, 120, 32, 111, 102, 32, 99, 104, 111, 99, 111, 108, 97, 116, 101, 115, 46, 57_345, 0, 0, 0, 0]
# fmt: on
__snake_case = tokenizer(a_ , padding=a_ , return_tensors="pt" )
self.assertIsInstance(a_ , a_ )
__snake_case = list(batch.input_ids.numpy()[0] )
self.assertListEqual(a_ , a_ )
self.assertEqual((2, 39) , batch.input_ids.shape )
self.assertEqual((2, 39) , batch.attention_mask.shape )
@require_torch
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.canine_tokenizer
__snake_case = ["Once there was a man.", "He wrote a test in HuggingFace Tranformers."]
__snake_case = tokenizer(a_ , padding=a_ , return_tensors="pt" )
# check if input_ids, attention_mask and token_type_ids are returned
self.assertIn("input_ids" , a_ )
self.assertIn("attention_mask" , a_ )
self.assertIn("token_type_ids" , a_ )
@require_torch
def A ( self : str ):
"""simple docstring"""
__snake_case = self.canine_tokenizer
__snake_case = [
"What's the weater?",
"It's about 25 degrees.",
]
__snake_case = tokenizer(
text_target=a_ , max_length=32 , padding="max_length" , truncation=a_ , return_tensors="pt" )
self.assertEqual(32 , targets["input_ids"].shape[1] )
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(f'''{tokenizer.__class__.__name__}''' ):
self.assertNotEqual(tokenizer.model_max_length , 42 )
# Now let's start the test
__snake_case = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(f'''{tokenizer.__class__.__name__}''' ):
# Isolate this from the other tests because we save additional tokens/etc
__snake_case = tempfile.mkdtemp()
__snake_case = " He is very happy, UNwant\u00E9d,running"
__snake_case = tokenizer.encode(a_ , add_special_tokens=a_ )
tokenizer.save_pretrained(a_ )
__snake_case = tokenizer.__class__.from_pretrained(a_ )
__snake_case = after_tokenizer.encode(a_ , add_special_tokens=a_ )
self.assertListEqual(a_ , a_ )
shutil.rmtree(a_ )
__snake_case = self.get_tokenizers(model_max_length=42 )
for tokenizer in tokenizers:
with self.subTest(f'''{tokenizer.__class__.__name__}''' ):
# Isolate this from the other tests because we save additional tokens/etc
__snake_case = tempfile.mkdtemp()
__snake_case = " He is very happy, UNwant\u00E9d,running"
__snake_case = tokenizer.additional_special_tokens
# We can add a new special token for Canine as follows:
__snake_case = chr(0xe0_07 )
additional_special_tokens.append(a_ )
tokenizer.add_special_tokens({"additional_special_tokens": additional_special_tokens} )
__snake_case = tokenizer.encode(a_ , add_special_tokens=a_ )
tokenizer.save_pretrained(a_ )
__snake_case = tokenizer.__class__.from_pretrained(a_ )
__snake_case = after_tokenizer.encode(a_ , add_special_tokens=a_ )
self.assertListEqual(a_ , a_ )
self.assertIn(a_ , after_tokenizer.additional_special_tokens )
self.assertEqual(after_tokenizer.model_max_length , 42 )
__snake_case = tokenizer.__class__.from_pretrained(a_ , model_max_length=43 )
self.assertEqual(tokenizer.model_max_length , 43 )
shutil.rmtree(a_ )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = self.get_tokenizers(do_lower_case=a_ )
for tokenizer in tokenizers:
with self.subTest(f'''{tokenizer.__class__.__name__}''' ):
__snake_case , __snake_case = self.get_clean_sequence(a_ )
# a special token for Canine can be defined as follows:
__snake_case = 0xe0_05
__snake_case = chr(a_ )
tokenizer.add_special_tokens({"cls_token": special_token} )
__snake_case = tokenizer.encode(a_ , add_special_tokens=a_ )
self.assertEqual(len(a_ ) , 1 )
__snake_case = tokenizer.decode(ids + encoded_special_token , clean_up_tokenization_spaces=a_ )
__snake_case = tokenizer.encode(a_ , add_special_tokens=a_ )
__snake_case = tokenizer.encode(a_ , add_special_tokens=a_ )
__snake_case = tokenizer.encode(a_ , add_special_tokens=a_ )
self.assertEqual(a_ , input_encoded + special_token_id )
__snake_case = tokenizer.decode(a_ , skip_special_tokens=a_ )
self.assertTrue(special_token not in decoded )
def A ( self : Any ):
"""simple docstring"""
__snake_case = self.get_tokenizers(do_lower_case=a_ )
for tokenizer in tokenizers:
with self.subTest(f'''{tokenizer.__class__.__name__}''' ):
__snake_case = chr(0xe0_05 )
__snake_case = chr(0xe0_06 )
# `add_tokens` method stores special tokens only in `tokenizer.unique_no_split_tokens`. (in tokenization_utils.py)
tokenizer.add_tokens([SPECIAL_TOKEN_1] , special_tokens=a_ )
# `add_special_tokens` method stores special tokens in `tokenizer.additional_special_tokens`,
# which also occur in `tokenizer.all_special_tokens`. (in tokenization_utils_base.py)
tokenizer.add_special_tokens({"additional_special_tokens": [SPECIAL_TOKEN_2]} )
__snake_case = tokenizer.tokenize(a_ )
__snake_case = tokenizer.tokenize(a_ )
self.assertEqual(len(a_ ) , 1 )
self.assertEqual(len(a_ ) , 1 )
self.assertEqual(token_a[0] , a_ )
self.assertEqual(token_a[0] , a_ )
@require_tokenizers
def A ( self : Dict ):
"""simple docstring"""
__snake_case = self.get_tokenizers(do_lower_case=a_ )
for tokenizer in tokenizers:
with self.subTest(f'''{tokenizer.__class__.__name__}''' ):
# a special token for Canine can be defined as follows:
__snake_case = 0xe0_06
__snake_case = chr(a_ )
__snake_case = AddedToken(a_ , lstrip=a_ )
tokenizer.add_special_tokens({"additional_special_tokens": [new_token]} )
with tempfile.TemporaryDirectory() as tmp_dir_name:
tokenizer.save_pretrained(a_ )
tokenizer.from_pretrained(a_ )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = []
if self.test_slow_tokenizer:
tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) )
if self.test_rust_tokenizer:
tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) )
for tokenizer_class, tokenizer_utils in tokenizer_list:
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer_utils.save_pretrained(a_ )
with open(os.path.join(a_ , "special_tokens_map.json" ) , encoding="utf-8" ) as json_file:
__snake_case = json.load(a_ )
with open(os.path.join(a_ , "tokenizer_config.json" ) , encoding="utf-8" ) as json_file:
__snake_case = json.load(a_ )
# a special token for Canine can be defined as follows:
__snake_case = 0xe0_06
__snake_case = chr(a_ )
__snake_case = [new_token_a]
__snake_case = [new_token_a]
with open(os.path.join(a_ , "special_tokens_map.json" ) , "w" , encoding="utf-8" ) as outfile:
json.dump(a_ , a_ )
with open(os.path.join(a_ , "tokenizer_config.json" ) , "w" , encoding="utf-8" ) as outfile:
json.dump(a_ , a_ )
# the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
# into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
# "special_tokens_map.json" files
__snake_case = tokenizer_class.from_pretrained(a_ , extra_ids=0 )
self.assertIn(a_ , tokenizer_without_change_in_init.additional_special_tokens )
# self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab
self.assertEqual(
[new_token_a] , tokenizer_without_change_in_init.convert_ids_to_tokens(
tokenizer_without_change_in_init.convert_tokens_to_ids([new_token_a] ) ) , )
__snake_case = 0xe0_07
__snake_case = chr(a_ )
# Now we test that we can change the value of additional_special_tokens in the from_pretrained
__snake_case = [AddedToken(a_ , lstrip=a_ )]
__snake_case = tokenizer_class.from_pretrained(
a_ , additional_special_tokens=a_ , extra_ids=0 )
self.assertIn(a_ , tokenizer.additional_special_tokens )
# self.assertIn(new_token_2,tokenizer.get_vocab()) # ByT5Tokenization no vocab
self.assertEqual(
[new_token_a] , tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids([new_token_a] ) ) )
@require_tokenizers
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.get_tokenizers(do_lower_case=a_ )
for tokenizer in tokenizers:
with self.subTest(f'''{tokenizer.__class__.__name__}''' ):
__snake_case = "hello world"
if self.space_between_special_tokens:
__snake_case = "[CLS] hello world [SEP]"
else:
__snake_case = input
__snake_case = tokenizer.encode(a_ , add_special_tokens=a_ )
__snake_case = tokenizer.decode(a_ , spaces_between_special_tokens=self.space_between_special_tokens )
self.assertIn(a_ , [output, output.lower()] )
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(f'''{tokenizer.__class__.__name__}''' ):
__snake_case = [
"bos_token",
"eos_token",
"unk_token",
"sep_token",
"pad_token",
"cls_token",
"mask_token",
]
__snake_case = "a"
__snake_case = ord(a_ )
for attr in attributes_list:
setattr(a_ , attr + "_id" , a_ )
self.assertEqual(getattr(a_ , a_ ) , a_ )
self.assertEqual(getattr(a_ , attr + "_id" ) , a_ )
setattr(a_ , attr + "_id" , a_ )
self.assertEqual(getattr(a_ , a_ ) , a_ )
self.assertEqual(getattr(a_ , attr + "_id" ) , a_ )
setattr(a_ , "additional_special_tokens_ids" , [] )
self.assertListEqual(getattr(a_ , "additional_special_tokens" ) , [] )
self.assertListEqual(getattr(a_ , "additional_special_tokens_ids" ) , [] )
__snake_case = 0xe0_06
__snake_case = chr(a_ )
setattr(a_ , "additional_special_tokens_ids" , [additional_special_token_id] )
self.assertListEqual(getattr(a_ , "additional_special_tokens" ) , [additional_special_token] )
self.assertListEqual(getattr(a_ , "additional_special_tokens_ids" ) , [additional_special_token_id] )
def A ( self : List[Any] ):
"""simple docstring"""
pass
def A ( self : Union[str, Any] ):
"""simple docstring"""
pass
def A ( self : Dict ):
"""simple docstring"""
pass
def A ( self : int ):
"""simple docstring"""
pass
def A ( self : Tuple ):
"""simple docstring"""
pass
def A ( self : Tuple ):
"""simple docstring"""
pass
def A ( self : Optional[int] ):
"""simple docstring"""
pass
def A ( self : Tuple ):
"""simple docstring"""
pass
| 69 |
'''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
a : Tuple = get_tests_dir('''fixtures''')
a : Dict = get_tests_dir('''fixtures/dummy_feature_extractor_config.json''')
a : int = get_tests_dir('''fixtures/dummy-config.json''')
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = 0
def A ( self : str ):
"""simple docstring"""
__snake_case = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h" )
self.assertIsInstance(a_ , a_ )
def A ( self : str ):
"""simple docstring"""
__snake_case = AutoFeatureExtractor.from_pretrained(a_ )
self.assertIsInstance(a_ , a_ )
def A ( self : str ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmpdirname:
__snake_case = WavaVecaConfig()
# remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
__snake_case = AutoFeatureExtractor.from_pretrained(a_ ).to_dict()
config_dict.pop("feature_extractor_type" )
__snake_case = WavaVecaFeatureExtractor(**a_ )
# save in new folder
model_config.save_pretrained(a_ )
config.save_pretrained(a_ )
__snake_case = AutoFeatureExtractor.from_pretrained(a_ )
# make sure private variable is not incorrectly saved
__snake_case = json.loads(config.to_json_string() )
self.assertTrue("_processor_class" not in dict_as_saved )
self.assertIsInstance(a_ , a_ )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = AutoFeatureExtractor.from_pretrained(a_ )
self.assertIsInstance(a_ , a_ )
def A ( self : Optional[Any] ):
"""simple docstring"""
with self.assertRaisesRegex(
a_ , "bert-base is not a local folder and is not a valid model identifier" ):
__snake_case = AutoFeatureExtractor.from_pretrained("bert-base" )
def A ( self : Dict ):
"""simple docstring"""
with self.assertRaisesRegex(
a_ , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ):
__snake_case = AutoFeatureExtractor.from_pretrained(a_ , revision="aaaaaa" )
def A ( self : Tuple ):
"""simple docstring"""
with self.assertRaisesRegex(
a_ , "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json." , ):
__snake_case = AutoFeatureExtractor.from_pretrained("hf-internal-testing/config-no-model" )
def A ( self : Tuple ):
"""simple docstring"""
with self.assertRaises(a_ ):
__snake_case = 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_ ):
__snake_case = AutoFeatureExtractor.from_pretrained(
"hf-internal-testing/test_dynamic_feature_extractor" , trust_remote_code=a_ )
__snake_case = 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_ )
__snake_case = AutoFeatureExtractor.from_pretrained(a_ , trust_remote_code=a_ )
self.assertEqual(reloaded_feature_extractor.__class__.__name__ , "NewFeatureExtractor" )
def A ( self : int ):
"""simple docstring"""
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
__snake_case = CustomFeatureExtractor.from_pretrained(a_ )
with tempfile.TemporaryDirectory() as tmp_dir:
feature_extractor.save_pretrained(a_ )
__snake_case = 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 A ( self : Dict ):
"""simple docstring"""
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = True
try:
AutoConfig.register("custom" , a_ )
AutoFeatureExtractor.register(a_ , a_ )
# If remote code is not set, the default is to use local
__snake_case = 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.
__snake_case = 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
__snake_case = 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]
| 69 | 1 |
'''simple docstring'''
import gc
import random
import unittest
import numpy as np
import torch
from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel
from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import floats_tensor, load_image, load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = ShapEImgaImgPipeline
__SCREAMING_SNAKE_CASE = ["""image"""]
__SCREAMING_SNAKE_CASE = ["""image"""]
__SCREAMING_SNAKE_CASE = [
"""num_images_per_prompt""",
"""num_inference_steps""",
"""generator""",
"""latents""",
"""guidance_scale""",
"""frame_size""",
"""output_type""",
"""return_dict""",
]
__SCREAMING_SNAKE_CASE = False
@property
def A ( self : int ):
"""simple docstring"""
return 32
@property
def A ( self : Optional[Any] ):
"""simple docstring"""
return 32
@property
def A ( self : str ):
"""simple docstring"""
return self.time_input_dim * 4
@property
def A ( self : Dict ):
"""simple docstring"""
return 8
@property
def A ( self : Optional[int] ):
"""simple docstring"""
torch.manual_seed(0 )
__snake_case = CLIPVisionConfig(
hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , )
__snake_case = CLIPVisionModel(a_ )
return model
@property
def A ( self : str ):
"""simple docstring"""
__snake_case = CLIPImageProcessor(
crop_size=224 , do_center_crop=a_ , do_normalize=a_ , do_resize=a_ , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , )
return image_processor
@property
def A ( self : Union[str, Any] ):
"""simple docstring"""
torch.manual_seed(0 )
__snake_case = {
"num_attention_heads": 2,
"attention_head_dim": 16,
"embedding_dim": self.time_input_dim,
"num_embeddings": 32,
"embedding_proj_dim": self.text_embedder_hidden_size,
"time_embed_dim": self.time_embed_dim,
"num_layers": 1,
"clip_embed_dim": self.time_input_dim * 2,
"additional_embeddings": 0,
"time_embed_act_fn": "gelu",
"norm_in_type": "layer",
"embedding_proj_norm_type": "layer",
"encoder_hid_proj_type": None,
"added_emb_type": None,
}
__snake_case = PriorTransformer(**a_ )
return model
@property
def A ( self : List[str] ):
"""simple docstring"""
torch.manual_seed(0 )
__snake_case = {
"param_shapes": (
(self.renderer_dim, 93),
(self.renderer_dim, 8),
(self.renderer_dim, 8),
(self.renderer_dim, 8),
),
"d_latent": self.time_input_dim,
"d_hidden": self.renderer_dim,
"n_output": 12,
"background": (
0.1,
0.1,
0.1,
),
}
__snake_case = ShapERenderer(**a_ )
return model
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = self.dummy_prior
__snake_case = self.dummy_image_encoder
__snake_case = self.dummy_image_processor
__snake_case = self.dummy_renderer
__snake_case = HeunDiscreteScheduler(
beta_schedule="exp" , num_train_timesteps=1_024 , prediction_type="sample" , use_karras_sigmas=a_ , clip_sample=a_ , clip_sample_range=1.0 , )
__snake_case = {
"prior": prior,
"image_encoder": image_encoder,
"image_processor": image_processor,
"renderer": renderer,
"scheduler": scheduler,
}
return components
def A ( self : Optional[int] , a_ : Union[str, Any] , a_ : int=0 ):
"""simple docstring"""
__snake_case = floats_tensor((1, 3, 64, 64) , rng=random.Random(a_ ) ).to(a_ )
if str(a_ ).startswith("mps" ):
__snake_case = torch.manual_seed(a_ )
else:
__snake_case = torch.Generator(device=a_ ).manual_seed(a_ )
__snake_case = {
"image": input_image,
"generator": generator,
"num_inference_steps": 1,
"frame_size": 32,
"output_type": "np",
}
return inputs
def A ( self : List[str] ):
"""simple docstring"""
__snake_case = "cpu"
__snake_case = self.get_dummy_components()
__snake_case = self.pipeline_class(**a_ )
__snake_case = pipe.to(a_ )
pipe.set_progress_bar_config(disable=a_ )
__snake_case = pipe(**self.get_dummy_inputs(a_ ) )
__snake_case = output.images[0]
__snake_case = image[0, -3:, -3:, -1]
assert image.shape == (20, 32, 32, 3)
__snake_case = np.array(
[
0.00039216,
0.00039216,
0.00039216,
0.00039216,
0.00039216,
0.00039216,
0.00039216,
0.00039216,
0.00039216,
] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def A ( self : List[Any] ):
"""simple docstring"""
self._test_inference_batch_consistent(batch_sizes=[1, 2] )
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = torch_device == "cpu"
__snake_case = True
self._test_inference_batch_single_identical(
batch_size=2 , test_max_difference=a_ , relax_max_difference=a_ , )
def A ( self : Any ):
"""simple docstring"""
__snake_case = self.get_dummy_components()
__snake_case = self.pipeline_class(**a_ )
__snake_case = pipe.to(a_ )
pipe.set_progress_bar_config(disable=a_ )
__snake_case = 1
__snake_case = 2
__snake_case = self.get_dummy_inputs(a_ )
for key in inputs.keys():
if key in self.batch_params:
__snake_case = batch_size * [inputs[key]]
__snake_case = pipe(**a_ , num_images_per_prompt=a_ )[0]
assert images.shape[0] == batch_size * num_images_per_prompt
@slow
@require_torch_gpu
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def A ( self : List[str] ):
"""simple docstring"""
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def A ( self : str ):
"""simple docstring"""
__snake_case = load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/shap_e/corgi.png" )
__snake_case = load_numpy(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
"/shap_e/test_shap_e_img2img_out.npy" )
__snake_case = ShapEImgaImgPipeline.from_pretrained("openai/shap-e-img2img" )
__snake_case = pipe.to(a_ )
pipe.set_progress_bar_config(disable=a_ )
__snake_case = torch.Generator(device=a_ ).manual_seed(0 )
__snake_case = pipe(
a_ , generator=a_ , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type="np" , ).images[0]
assert images.shape == (20, 64, 64, 3)
assert_mean_pixel_difference(a_ , a_ )
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> list:
# bit count represents no. of bits in the gray code
if bit_count < 0:
raise ValueError("The given input must be positive" )
# get the generated string sequence
__snake_case = gray_code_sequence_string(_UpperCAmelCase )
#
# convert them to integers
for i in range(len(_UpperCAmelCase ) ):
__snake_case = int(sequence[i] , 2 )
return sequence
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> list:
# The approach is a recursive one
# Base case achieved when either n = 0 or n=1
if bit_count == 0:
return ["0"]
if bit_count == 1:
return ["0", "1"]
__snake_case = 1 << bit_count # defines the length of the sequence
# 1<< n is equivalent to 2^n
# recursive answer will generate answer for n-1 bits
__snake_case = gray_code_sequence_string(bit_count - 1 )
__snake_case = []
# append 0 to first half of the smaller sequence generated
for i in range(seq_len // 2 ):
__snake_case = "0" + smaller_sequence[i]
sequence.append(_UpperCAmelCase )
# append 1 to second half ... start from the end of the list
for i in reversed(range(seq_len // 2 ) ):
__snake_case = "1" + smaller_sequence[i]
sequence.append(_UpperCAmelCase )
return sequence
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 | 1 |
'''simple docstring'''
import gc
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
StableDiffusionAttendAndExcitePipeline,
UNetaDConditionModel,
)
from diffusers.utils import load_numpy, skip_mps, slow
from diffusers.utils.testing_utils import require_torch_gpu
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin
a : List[Any] = False
@skip_mps
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = StableDiffusionAttendAndExcitePipeline
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = TEXT_TO_IMAGE_PARAMS
__SCREAMING_SNAKE_CASE = TEXT_TO_IMAGE_BATCH_PARAMS.union({"""token_indices"""} )
__SCREAMING_SNAKE_CASE = TEXT_TO_IMAGE_IMAGE_PARAMS
__SCREAMING_SNAKE_CASE = TEXT_TO_IMAGE_IMAGE_PARAMS
@classmethod
def A ( cls : Union[str, Any] ):
"""simple docstring"""
super().setUpClass()
torch.use_deterministic_algorithms(a_ )
@classmethod
def A ( cls : List[Any] ):
"""simple docstring"""
super().tearDownClass()
torch.use_deterministic_algorithms(a_ )
def A ( self : Union[str, Any] ):
"""simple docstring"""
torch.manual_seed(0 )
__snake_case = UNetaDConditionModel(
block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=a_ , )
__snake_case = DDIMScheduler(
beta_start=0.00085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=a_ , set_alpha_to_one=a_ , )
torch.manual_seed(0 )
__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 , sample_size=128 , )
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=1_000 , hidden_act="gelu" , projection_dim=512 , )
__snake_case = CLIPTextModel(a_ )
__snake_case = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )
__snake_case = {
"unet": unet,
"scheduler": scheduler,
"vae": vae,
"text_encoder": text_encoder,
"tokenizer": tokenizer,
"safety_checker": None,
"feature_extractor": None,
}
return components
def A ( self : Optional[Any] , a_ : Optional[Any] , a_ : Optional[int]=0 ):
"""simple docstring"""
if str(a_ ).startswith("mps" ):
__snake_case = torch.manual_seed(a_ )
else:
__snake_case = torch.Generator(device=a_ ).manual_seed(a_ )
__snake_case = __snake_case = {
"prompt": "a cat and a frog",
"token_indices": [2, 5],
"generator": generator,
"num_inference_steps": 1,
"guidance_scale": 6.0,
"output_type": "numpy",
"max_iter_to_alter": 2,
"thresholds": {0: 0.7},
}
return inputs
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = "cpu"
__snake_case = self.get_dummy_components()
__snake_case = self.pipeline_class(**a_ )
pipe.to(a_ )
pipe.set_progress_bar_config(disable=a_ )
__snake_case = self.get_dummy_inputs(a_ )
__snake_case = pipe(**a_ ).images
__snake_case = image[0, -3:, -3:, -1]
self.assertEqual(image.shape , (1, 64, 64, 3) )
__snake_case = np.array(
[0.63905364, 0.62897307, 0.48599017, 0.5133624, 0.5550048, 0.45769516, 0.50326973, 0.5023139, 0.45384496] )
__snake_case = np.abs(image_slice.flatten() - expected_slice ).max()
self.assertLessEqual(a_ , 1e-3 )
def A ( self : str ):
"""simple docstring"""
super().test_cpu_offload_forward_pass(expected_max_diff=5e-4 )
def A ( self : str ):
"""simple docstring"""
self._test_inference_batch_consistent(batch_sizes=[1, 2] )
def A ( self : int ):
"""simple docstring"""
self._test_inference_batch_single_identical(batch_size=2 , expected_max_diff=7e-4 )
def A ( self : List[str] ):
"""simple docstring"""
super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 )
def A ( self : Tuple ):
"""simple docstring"""
super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5e-4 )
def A ( self : str ):
"""simple docstring"""
super().test_save_load_local(expected_max_difference=5e-4 )
def A ( self : str ):
"""simple docstring"""
super().test_save_load_optional_components(expected_max_difference=4e-4 )
@require_torch_gpu
@slow
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
@classmethod
def A ( cls : Optional[Any] ):
"""simple docstring"""
super().setUpClass()
torch.use_deterministic_algorithms(a_ )
@classmethod
def A ( cls : List[str] ):
"""simple docstring"""
super().tearDownClass()
torch.use_deterministic_algorithms(a_ )
def A ( self : List[Any] ):
"""simple docstring"""
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = torch.manual_seed(51 )
__snake_case = StableDiffusionAttendAndExcitePipeline.from_pretrained(
"CompVis/stable-diffusion-v1-4" , safety_checker=a_ , torch_dtype=torch.floataa )
pipe.to("cuda" )
__snake_case = "a painting of an elephant with glasses"
__snake_case = [5, 7]
__snake_case = pipe(
prompt=a_ , token_indices=a_ , guidance_scale=7.5 , generator=a_ , num_inference_steps=5 , max_iter_to_alter=5 , output_type="numpy" , ).images[0]
__snake_case = load_numpy(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy" )
assert np.abs((expected_image - image).max() ) < 5e-1
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : str , _UpperCAmelCase : str ) -> list:
__snake_case = len(_UpperCAmelCase )
__snake_case = []
for i in range(len(_UpperCAmelCase ) - pat_len + 1 ):
__snake_case = True
for j in range(_UpperCAmelCase ):
if s[i + j] != pattern[j]:
__snake_case = 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'''))
| 69 | 1 |
'''simple docstring'''
import platform
from argparse import ArgumentParser
import huggingface_hub
from .. import __version__ as version
from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available
from . import BaseDiffusersCLICommand
def __UpperCAmelCase ( _UpperCAmelCase : List[Any] ) -> Dict:
return EnvironmentCommand()
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
@staticmethod
def A ( a_ : ArgumentParser ):
"""simple docstring"""
__snake_case = parser.add_parser("env" )
download_parser.set_defaults(func=a_ )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = huggingface_hub.__version__
__snake_case = "not installed"
__snake_case = "NA"
if is_torch_available():
import torch
__snake_case = torch.__version__
__snake_case = torch.cuda.is_available()
__snake_case = "not installed"
if is_transformers_available():
import transformers
__snake_case = transformers.__version__
__snake_case = "not installed"
if is_accelerate_available():
import accelerate
__snake_case = accelerate.__version__
__snake_case = "not installed"
if is_xformers_available():
import xformers
__snake_case = xformers.__version__
__snake_case = {
"`diffusers` version": version,
"Platform": platform.platform(),
"Python version": platform.python_version(),
"PyTorch version (GPU?)": f'''{pt_version} ({pt_cuda_available})''',
"Huggingface_hub version": hub_version,
"Transformers version": transformers_version,
"Accelerate version": accelerate_version,
"xFormers version": xformers_version,
"Using GPU in script?": "<fill in>",
"Using distributed or parallel set-up in script?": "<fill in>",
}
print("\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n" )
print(self.format_dict(a_ ) )
return info
@staticmethod
def A ( a_ : Union[str, Any] ):
"""simple docstring"""
return "\n".join([f'''- {prop}: {val}''' for prop, val in d.items()] ) + "\n"
| 69 |
'''simple docstring'''
a : Dict = range(2, 20 + 1)
a : Optional[int] = [10**k for k in range(ks[-1] + 1)]
a : dict[int, dict[int, list[list[int]]]] = {}
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Dict , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[Any] ) -> int:
__snake_case = sum(a_i[j] for j in range(_UpperCAmelCase , len(_UpperCAmelCase ) ) )
__snake_case = sum(a_i[j] * base[j] for j in range(min(len(_UpperCAmelCase ) , _UpperCAmelCase ) ) )
__snake_case , __snake_case = 0, 0
__snake_case = n - i
__snake_case = memo.get(_UpperCAmelCase )
if sub_memo is not None:
__snake_case = sub_memo.get(_UpperCAmelCase )
if jumps is not None and len(_UpperCAmelCase ) > 0:
# find and make the largest jump without going over
__snake_case = -1
for _k in range(len(_UpperCAmelCase ) - 1 , -1 , -1 ):
if jumps[_k][2] <= k and jumps[_k][1] <= max_dn:
__snake_case = _k
break
if max_jump >= 0:
__snake_case , __snake_case , __snake_case = jumps[max_jump]
# since the difference between jumps is cached, add c
__snake_case = diff + c
for j in range(min(_UpperCAmelCase , len(_UpperCAmelCase ) ) ):
__snake_case , __snake_case = divmod(_UpperCAmelCase , 10 )
if new_c > 0:
add(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
else:
__snake_case = []
else:
__snake_case = {c: []}
__snake_case = sub_memo
if dn >= max_dn or c + diff >= base[k]:
return diff, dn
if k > ks[0]:
while True:
# keep doing smaller jumps
__snake_case , __snake_case = next_term(_UpperCAmelCase , k - 1 , i + dn , _UpperCAmelCase )
diff += _diff
dn += terms_jumped
if dn >= max_dn or c + diff >= base[k]:
break
else:
# would be too small a jump, just compute sequential terms instead
__snake_case , __snake_case = compute(_UpperCAmelCase , _UpperCAmelCase , i + dn , _UpperCAmelCase )
diff += _diff
dn += terms_jumped
__snake_case = sub_memo[c]
# keep jumps sorted by # of terms skipped
__snake_case = 0
while j < len(_UpperCAmelCase ):
if jumps[j][1] > dn:
break
j += 1
# cache the jump for this value digitsum(b) and c
sub_memo[c].insert(_UpperCAmelCase , (diff, dn, k) )
return (diff, dn)
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[int] ) -> Optional[int]:
if i >= n:
return 0, i
if k > len(_UpperCAmelCase ):
a_i.extend([0 for _ in range(k - len(_UpperCAmelCase ) )] )
# note: a_i -> b * 10^k + c
# ds_b -> digitsum(b)
# ds_c -> digitsum(c)
__snake_case = i
__snake_case , __snake_case , __snake_case = 0, 0, 0
for j in range(len(_UpperCAmelCase ) ):
if j >= k:
ds_b += a_i[j]
else:
ds_c += a_i[j]
while i < n:
i += 1
__snake_case = ds_c + ds_b
diff += addend
__snake_case = 0
for j in range(_UpperCAmelCase ):
__snake_case = a_i[j] + addend
__snake_case , __snake_case = divmod(_UpperCAmelCase , 10 )
ds_c += a_i[j]
if addend > 0:
break
if addend > 0:
add(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
return diff, i - start_i
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Tuple , _UpperCAmelCase : str ) -> Tuple:
for j in range(_UpperCAmelCase , len(_UpperCAmelCase ) ):
__snake_case = digits[j] + addend
if s >= 10:
__snake_case , __snake_case = divmod(_UpperCAmelCase , 10 )
__snake_case = addend // 10 + quotient
else:
__snake_case = s
__snake_case = addend // 10
if addend == 0:
break
while addend > 0:
__snake_case , __snake_case = divmod(_UpperCAmelCase , 10 )
digits.append(_UpperCAmelCase )
def __UpperCAmelCase ( _UpperCAmelCase : int = 10**15 ) -> int:
__snake_case = [1]
__snake_case = 1
__snake_case = 0
while True:
__snake_case , __snake_case = next_term(_UpperCAmelCase , 20 , i + dn , _UpperCAmelCase )
dn += terms_jumped
if dn == n - i:
break
__snake_case = 0
for j in range(len(_UpperCAmelCase ) ):
a_n += digits[j] * 10**j
return a_n
if __name__ == "__main__":
print(F'''{solution() = }''')
| 69 | 1 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
a : Optional[Any] = logging.get_logger(__name__)
a : int = {
'''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json''',
# See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox
}
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = """gpt_neox"""
def __init__( self : Dict , a_ : Any=50_432 , a_ : Dict=6_144 , a_ : Union[str, Any]=44 , a_ : Optional[Any]=64 , a_ : List[Any]=24_576 , a_ : List[str]="gelu" , a_ : str=0.25 , a_ : Dict=10_000 , a_ : Union[str, Any]=0.0 , a_ : Any=0.0 , a_ : Any=0.1 , a_ : Optional[Any]=2_048 , a_ : Dict=0.02 , a_ : Optional[Any]=1e-5 , a_ : Dict=True , a_ : List[Any]=0 , a_ : Union[str, Any]=2 , a_ : List[Any]=False , a_ : Dict=True , a_ : List[str]=None , **a_ : Dict , ):
"""simple docstring"""
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_size
__snake_case = hidden_act
__snake_case = rotary_pct
__snake_case = rotary_emb_base
__snake_case = attention_dropout
__snake_case = hidden_dropout
__snake_case = classifier_dropout
__snake_case = initializer_range
__snake_case = layer_norm_eps
__snake_case = use_cache
__snake_case = tie_word_embeddings
__snake_case = use_parallel_residual
__snake_case = rope_scaling
self._rope_scaling_validation()
if self.hidden_size % self.num_attention_heads != 0:
raise ValueError(
"The hidden size is not divisble by the number of attention heads! Make sure to update them!" )
def A ( self : Union[str, Any] ):
"""simple docstring"""
if self.rope_scaling is None:
return
if not isinstance(self.rope_scaling , a_ ) or len(self.rope_scaling ) != 2:
raise ValueError(
"`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, "
f'''got {self.rope_scaling}''' )
__snake_case = self.rope_scaling.get("type" , a_ )
__snake_case = self.rope_scaling.get("factor" , a_ )
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
raise ValueError(
f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' )
if rope_scaling_factor is None or not isinstance(a_ , a_ ) or rope_scaling_factor <= 1.0:
raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : List[Any]=2_81_23 ) -> str:
__snake_case = [1] * (limit + 1)
for i in range(2 , int(limit**0.5 ) + 1 ):
sum_divs[i * i] += i
for k in range(i + 1 , limit // i + 1 ):
sum_divs[k * i] += k + i
__snake_case = set()
__snake_case = 0
for n in range(1 , limit + 1 ):
if sum_divs[n] > n:
abundants.add(_UpperCAmelCase )
if not any((n - a in abundants) for a in abundants ):
res += n
return res
if __name__ == "__main__":
print(solution())
| 69 | 1 |
'''simple docstring'''
# Imports
import numpy as np
class SCREAMING_SNAKE_CASE__ :
def __init__( self : List[str] , a_ : str=None , a_ : Tuple=None , a_ : Optional[Any]=None , a_ : Union[str, Any]=None , a_ : List[Any]=None ):
"""simple docstring"""
self.set_matricies(red=a_ , green=a_ , blue=a_ , red_edge=a_ , nir=a_ )
def A ( self : List[Any] , a_ : List[str]=None , a_ : Optional[Any]=None , a_ : Tuple=None , a_ : Any=None , a_ : List[Any]=None ):
"""simple docstring"""
if red is not None:
__snake_case = red
if green is not None:
__snake_case = green
if blue is not None:
__snake_case = blue
if red_edge is not None:
__snake_case = red_edge
if nir is not None:
__snake_case = nir
return True
def A ( self : int , a_ : List[str]="" , a_ : List[Any]=None , a_ : Union[str, Any]=None , a_ : int=None , a_ : int=None , a_ : int=None ):
"""simple docstring"""
self.set_matricies(red=a_ , green=a_ , blue=a_ , red_edge=a_ , nir=a_ )
__snake_case = {
"ARVI2": self.arvaa,
"CCCI": self.ccci,
"CVI": self.cvi,
"GLI": self.gli,
"NDVI": self.ndvi,
"BNDVI": self.bndvi,
"redEdgeNDVI": self.red_edge_ndvi,
"GNDVI": self.gndvi,
"GBNDVI": self.gbndvi,
"GRNDVI": self.grndvi,
"RBNDVI": self.rbndvi,
"PNDVI": self.pndvi,
"ATSAVI": self.atsavi,
"BWDRVI": self.bwdrvi,
"CIgreen": self.ci_green,
"CIrededge": self.ci_rededge,
"CI": self.ci,
"CTVI": self.ctvi,
"GDVI": self.gdvi,
"EVI": self.evi,
"GEMI": self.gemi,
"GOSAVI": self.gosavi,
"GSAVI": self.gsavi,
"Hue": self.hue,
"IVI": self.ivi,
"IPVI": self.ipvi,
"I": self.i,
"RVI": self.rvi,
"MRVI": self.mrvi,
"MSAVI": self.m_savi,
"NormG": self.norm_g,
"NormNIR": self.norm_nir,
"NormR": self.norm_r,
"NGRDI": self.ngrdi,
"RI": self.ri,
"S": self.s,
"IF": self._if,
"DVI": self.dvi,
"TVI": self.tvi,
"NDRE": self.ndre,
}
try:
return funcs[index]()
except KeyError:
print("Index not in the list!" )
return False
def A ( self : List[Any] ):
"""simple docstring"""
return -0.18 + (1.17 * ((self.nir - self.red) / (self.nir + self.red)))
def A ( self : List[Any] ):
"""simple docstring"""
return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / (
(self.nir - self.red) / (self.nir + self.red)
)
def A ( self : Union[str, Any] ):
"""simple docstring"""
return self.nir * (self.red / (self.green**2))
def A ( self : Tuple ):
"""simple docstring"""
return (2 * self.green - self.red - self.blue) / (
2 * self.green + self.red + self.blue
)
def A ( self : List[str] ):
"""simple docstring"""
return (self.nir - self.red) / (self.nir + self.red)
def A ( self : str ):
"""simple docstring"""
return (self.nir - self.blue) / (self.nir + self.blue)
def A ( self : Tuple ):
"""simple docstring"""
return (self.redEdge - self.red) / (self.redEdge + self.red)
def A ( self : int ):
"""simple docstring"""
return (self.nir - self.green) / (self.nir + self.green)
def A ( self : List[Any] ):
"""simple docstring"""
return (self.nir - (self.green + self.blue)) / (
self.nir + (self.green + self.blue)
)
def A ( self : List[Any] ):
"""simple docstring"""
return (self.nir - (self.green + self.red)) / (
self.nir + (self.green + self.red)
)
def A ( self : Any ):
"""simple docstring"""
return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red))
def A ( self : Any ):
"""simple docstring"""
return (self.nir - (self.green + self.red + self.blue)) / (
self.nir + (self.green + self.red + self.blue)
)
def A ( self : Any , a_ : Tuple=0.08 , a_ : Tuple=1.22 , a_ : Any=0.03 ):
"""simple docstring"""
return a * (
(self.nir - a * self.red - b)
/ (a * self.nir + self.red - a * b + x * (1 + a**2))
)
def A ( self : Dict ):
"""simple docstring"""
return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue)
def A ( self : Optional[Any] ):
"""simple docstring"""
return (self.nir / self.green) - 1
def A ( self : Tuple ):
"""simple docstring"""
return (self.nir / self.redEdge) - 1
def A ( self : List[str] ):
"""simple docstring"""
return (self.red - self.blue) / self.red
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = self.ndvi()
return ((ndvi + 0.5) / (abs(ndvi + 0.5 ))) * (abs(ndvi + 0.5 ) ** (1 / 2))
def A ( self : List[Any] ):
"""simple docstring"""
return self.nir - self.green
def A ( self : Tuple ):
"""simple docstring"""
return 2.5 * (
(self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1)
)
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = (2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / (
self.nir + self.red + 0.5
)
return n * (1 - 0.25 * n) - (self.red - 0.125) / (1 - self.red)
def A ( self : Tuple , a_ : Optional[int]=0.16 ):
"""simple docstring"""
return (self.nir - self.green) / (self.nir + self.green + y)
def A ( self : int , a_ : List[Any]=0.5 ):
"""simple docstring"""
return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n)
def A ( self : Tuple ):
"""simple docstring"""
return np.arctan(
((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue) )
def A ( self : Union[str, Any] , a_ : Optional[int]=None , a_ : List[Any]=None ):
"""simple docstring"""
return (self.nir - b) / (a * self.red)
def A ( self : Tuple ):
"""simple docstring"""
return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1)
def A ( self : Dict ):
"""simple docstring"""
return (self.red + self.green + self.blue) / 30.5
def A ( self : List[Any] ):
"""simple docstring"""
return self.nir / self.red
def A ( self : Union[str, Any] ):
"""simple docstring"""
return (self.rvi() - 1) / (self.rvi() + 1)
def A ( self : Dict ):
"""simple docstring"""
return (
(2 * self.nir + 1)
- ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2)
) / 2
def A ( self : Tuple ):
"""simple docstring"""
return self.green / (self.nir + self.red + self.green)
def A ( self : List[Any] ):
"""simple docstring"""
return self.nir / (self.nir + self.red + self.green)
def A ( self : Optional[int] ):
"""simple docstring"""
return self.red / (self.nir + self.red + self.green)
def A ( self : List[Any] ):
"""simple docstring"""
return (self.green - self.red) / (self.green + self.red)
def A ( self : str ):
"""simple docstring"""
return (self.red - self.green) / (self.red + self.green)
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = np.max([np.max(self.red ), np.max(self.green ), np.max(self.blue )] )
__snake_case = np.min([np.min(self.red ), np.min(self.green ), np.min(self.blue )] )
return (max_value - min_value) / max_value
def A ( self : Optional[int] ):
"""simple docstring"""
return (2 * self.red - self.green - self.blue) / (self.green - self.blue)
def A ( self : Any ):
"""simple docstring"""
return self.nir / self.red
def A ( self : Any ):
"""simple docstring"""
return (self.ndvi() + 0.5) ** (1 / 2)
def A ( self : Optional[int] ):
"""simple docstring"""
return (self.nir - self.redEdge) / (self.nir + self.redEdge)
| 69 |
'''simple docstring'''
import unittest
from transformers import AutoTokenizer, FalconConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
FalconForCausalLM,
FalconForQuestionAnswering,
FalconForSequenceClassification,
FalconForTokenClassification,
FalconModel,
)
class SCREAMING_SNAKE_CASE__ :
def __init__( self : str , a_ : List[str] , a_ : Tuple=3 , a_ : Any=7 , a_ : Any=True , a_ : Union[str, Any]=True , a_ : Tuple=False , a_ : Optional[int]=True , a_ : Any=99 , a_ : Dict=32 , a_ : Dict=5 , a_ : List[Any]=4 , a_ : Any=37 , a_ : Any="gelu" , a_ : List[str]=0.1 , a_ : Dict=0.1 , a_ : Optional[Any]=512 , a_ : List[Any]=16 , a_ : Any=2 , a_ : str=0.02 , a_ : Any=3 , a_ : List[Any]=4 , a_ : List[str]=None , ):
"""simple docstring"""
__snake_case = parent
__snake_case = batch_size
__snake_case = seq_length
__snake_case = is_training
__snake_case = use_input_mask
__snake_case = use_token_type_ids
__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_act
__snake_case = hidden_dropout_prob
__snake_case = attention_probs_dropout_prob
__snake_case = max_position_embeddings
__snake_case = type_vocab_size
__snake_case = type_sequence_label_size
__snake_case = initializer_range
__snake_case = num_labels
__snake_case = num_choices
__snake_case = scope
def A ( self : Any ):
"""simple docstring"""
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__snake_case = None
if self.use_input_mask:
__snake_case = random_attention_mask([self.batch_size, self.seq_length] )
__snake_case = None
__snake_case = None
__snake_case = None
__snake_case = None
if self.use_labels:
__snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__snake_case = ids_tensor([self.batch_size] , self.num_choices )
__snake_case = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def A ( self : Optional[int] ):
"""simple docstring"""
return FalconConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a_ , initializer_range=self.initializer_range , pad_token_id=1 , new_decoder_architecture=a_ , )
def A ( self : List[str] , a_ : Dict , a_ : Tuple , a_ : Optional[Any] , a_ : Dict , a_ : Dict , a_ : Dict , a_ : Union[str, Any] ):
"""simple docstring"""
__snake_case = FalconModel(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ )
__snake_case = model(a_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def A ( self : List[Any] , a_ : List[Any] , a_ : Union[str, Any] , a_ : Optional[Any] , a_ : Any , a_ : List[Any] , a_ : Optional[Any] , a_ : Union[str, Any] , a_ : Tuple , a_ : Optional[int] , ):
"""simple docstring"""
__snake_case = True
__snake_case = FalconModel(a_ )
model.to(a_ )
model.eval()
__snake_case = model(
a_ , attention_mask=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , )
__snake_case = model(
a_ , attention_mask=a_ , encoder_hidden_states=a_ , )
__snake_case = model(a_ , attention_mask=a_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def A ( self : Optional[int] , a_ : int , a_ : int , a_ : List[Any] , a_ : str , a_ : List[str] , a_ : str , a_ : str , a_ : Union[str, Any] , a_ : Optional[int] , ):
"""simple docstring"""
__snake_case = FalconForCausalLM(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def A ( self : List[Any] , a_ : Optional[int] , a_ : Optional[Any] , a_ : str , a_ : Tuple , a_ : str , a_ : List[Any] , a_ : Optional[Any] , a_ : Any , a_ : Dict , ):
"""simple docstring"""
__snake_case = True
__snake_case = True
__snake_case = FalconForCausalLM(config=a_ )
model.to(a_ )
model.eval()
# first forward pass
__snake_case = model(
a_ , attention_mask=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , use_cache=a_ , )
__snake_case = outputs.past_key_values
# create hypothetical multiple next token and extent to next_input_ids
__snake_case = ids_tensor((self.batch_size, 3) , config.vocab_size )
__snake_case = ids_tensor((self.batch_size, 3) , vocab_size=2 )
# append to next input_ids and
__snake_case = torch.cat([input_ids, next_tokens] , dim=-1 )
__snake_case = torch.cat([input_mask, next_mask] , dim=-1 )
__snake_case = model(
a_ , attention_mask=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , output_hidden_states=a_ , )["hidden_states"][0]
__snake_case = model(
a_ , attention_mask=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , past_key_values=a_ , output_hidden_states=a_ , )["hidden_states"][0]
# select random slice
__snake_case = ids_tensor((1,) , output_from_past.shape[-1] ).item()
__snake_case = output_from_no_past[:, -3:, random_slice_idx].detach()
__snake_case = output_from_past[:, :, random_slice_idx].detach()
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] )
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = self.prepare_config_and_inputs()
(
(
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) ,
) = config_and_inputs
__snake_case = {"input_ids": input_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = (
(
FalconModel,
FalconForCausalLM,
FalconForSequenceClassification,
FalconForTokenClassification,
FalconForQuestionAnswering,
)
if is_torch_available()
else ()
)
__SCREAMING_SNAKE_CASE = (FalconForCausalLM,) if is_torch_available() else ()
__SCREAMING_SNAKE_CASE = (
{
"""feature-extraction""": FalconModel,
"""text-classification""": FalconForSequenceClassification,
"""text-generation""": FalconForCausalLM,
"""question-answering""": FalconForQuestionAnswering,
"""token-classification""": FalconForTokenClassification,
"""zero-shot""": FalconForSequenceClassification,
}
if is_torch_available()
else {}
)
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = False
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = FalconModelTester(self )
__snake_case = ConfigTester(self , config_class=a_ , hidden_size=37 )
def A ( self : Optional[Any] ):
"""simple docstring"""
self.config_tester.run_common_tests()
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*a_ )
def A ( self : List[str] ):
"""simple docstring"""
__snake_case , *__snake_case = self.model_tester.prepare_config_and_inputs()
for alibi in [True, False]:
__snake_case = alibi
self.model_tester.create_and_check_model(a_ , *a_ )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = 3
__snake_case = input_dict["input_ids"]
__snake_case = input_ids.ne(1 ).to(a_ )
__snake_case = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size )
__snake_case = FalconForSequenceClassification(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) )
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = 3
__snake_case = "single_label_classification"
__snake_case = input_dict["input_ids"]
__snake_case = input_ids.ne(1 ).to(a_ )
__snake_case = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size )
__snake_case = FalconForSequenceClassification(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = input_dict["input_ids"]
__snake_case = FalconForCausalLM(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , use_cache=a_ )
__snake_case = input_ids.shape[0]
__snake_case = model._convert_to_rw_cache(result.past_key_values )
__snake_case = model._convert_cache_to_standard_format(a_ , a_ )
for layer in range(len(a_ ) ):
for tensor_idx in range(2 ):
self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3 )
self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4 )
self.assertTrue(
torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx] ) )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = 3
__snake_case = "multi_label_classification"
__snake_case = input_dict["input_ids"]
__snake_case = input_ids.ne(1 ).to(a_ )
__snake_case = ids_tensor(
[self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float )
__snake_case = FalconForSequenceClassification(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) )
def A ( self : Dict ):
"""simple docstring"""
for model_class in self.all_generative_model_classes:
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
# If it doesn't support cache, pass the test
if not hasattr(a_ , "use_cache" ):
return
__snake_case = model_class(a_ ).to(a_ )
if "use_cache" not in inputs:
__snake_case = True
__snake_case = model(**a_ )
# If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format)
if "past_key_values" not in outputs:
return
__snake_case = (
getattr(a_ , "decoder_layers" , a_ )
or getattr(a_ , "num_decoder_layers" , a_ )
or config.num_hidden_layers
)
__snake_case = getattr(a_ , "num_kv_heads" , config.num_attention_heads )
__snake_case = getattr(a_ , "d_model" , config.hidden_size )
__snake_case = embed_dim // num_attention_heads
__snake_case = outputs["past_key_values"]
self.assertEqual(len(a_ ) , a_ )
__snake_case , __snake_case = inputs["input_ids"].shape
for i in range(a_ ):
if config.new_decoder_architecture:
__snake_case = config.num_attention_heads
elif config.multi_query:
__snake_case = 1
self.assertEqual(len(past_kv[0] ) , 2 ) # K V for the decoder = 2
self.assertEqual(
past_kv[i][0].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) )
self.assertEqual(
past_kv[i][1].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) )
@require_torch
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
@slow
def A ( self : Any ):
"""simple docstring"""
__snake_case = AutoTokenizer.from_pretrained("Rocketknight1/falcon-rw-1b" )
__snake_case = FalconForCausalLM.from_pretrained("Rocketknight1/falcon-rw-1b" )
model.eval()
model.to(a_ )
__snake_case = tokenizer("My favorite food is" , return_tensors="pt" ).to(a_ )
__snake_case = (
"My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday."
)
__snake_case = model.generate(**a_ , do_sample=a_ , max_new_tokens=19 )
__snake_case = tokenizer.batch_decode(a_ )[0]
self.assertEqual(a_ , a_ )
@slow
def A ( self : Optional[int] ):
"""simple docstring"""
for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]:
__snake_case = AutoTokenizer.from_pretrained(a_ )
__snake_case = FalconForCausalLM.from_pretrained(a_ )
model.eval()
model.to(a_ )
__snake_case = tokenizer("My favorite food is" , return_tensors="pt" ).to(a_ )
# We just test that these run without errors - the models are randomly initialized
# and so the actual text outputs will be garbage
model.generate(**a_ , do_sample=a_ , max_new_tokens=4 )
model.generate(**a_ , do_sample=a_ , max_new_tokens=4 )
model.generate(**a_ , num_beams=2 , max_new_tokens=4 )
@slow
def A ( self : Any ):
"""simple docstring"""
with torch.no_grad():
for repo in [
"Rocketknight1/falcon-rw-1b",
"Rocketknight1/tiny-random-falcon-7b",
"Rocketknight1/tiny-random-falcon-40b",
]:
__snake_case = AutoTokenizer.from_pretrained(a_ )
__snake_case = FalconForCausalLM.from_pretrained(a_ )
model.eval()
model.to(device=a_ )
__snake_case = tokenizer("My favorite food is" , return_tensors="pt" ).to(a_ )
# Test results are the same with and without cache
__snake_case = model.generate(**a_ , do_sample=a_ , max_new_tokens=20 , use_cache=a_ )
__snake_case = model.generate(**a_ , do_sample=a_ , max_new_tokens=20 , use_cache=a_ )
self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0 )
| 69 | 1 |
'''simple docstring'''
import json
from typing import List, Optional, Tuple
from tokenizers import pre_tokenizers, processors
from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bart import BartTokenizer
a : Optional[Any] = logging.get_logger(__name__)
a : Any = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''}
# See all BART models at https://huggingface.co/models?filter=bart
a : Union[str, Any] = {
'''vocab_file''': {
'''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/vocab.json''',
'''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/vocab.json''',
'''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json''',
'''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json''',
'''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json''',
'''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json''',
},
'''merges_file''': {
'''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/merges.txt''',
'''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/merges.txt''',
'''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt''',
'''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt''',
'''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt''',
'''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt''',
},
'''tokenizer_file''': {
'''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json''',
'''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json''',
'''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json''',
'''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json''',
'''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json''',
'''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json''',
},
}
a : Any = {
'''facebook/bart-base''': 1_024,
'''facebook/bart-large''': 1_024,
'''facebook/bart-large-mnli''': 1_024,
'''facebook/bart-large-cnn''': 1_024,
'''facebook/bart-large-xsum''': 1_024,
'''yjernite/bart_eli5''': 1_024,
}
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES
__SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP
__SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__SCREAMING_SNAKE_CASE = ["""input_ids""", """attention_mask"""]
__SCREAMING_SNAKE_CASE = BartTokenizer
def __init__( self : List[str] , a_ : Union[str, Any]=None , a_ : Tuple=None , a_ : Tuple=None , a_ : List[str]="replace" , a_ : Dict="<s>" , a_ : Optional[Any]="</s>" , a_ : Union[str, Any]="</s>" , a_ : int="<s>" , a_ : Tuple="<unk>" , a_ : List[str]="<pad>" , a_ : List[Any]="<mask>" , a_ : Optional[int]=False , a_ : Optional[Any]=True , **a_ : int , ):
"""simple docstring"""
super().__init__(
a_ , a_ , tokenizer_file=a_ , errors=a_ , bos_token=a_ , eos_token=a_ , sep_token=a_ , cls_token=a_ , unk_token=a_ , pad_token=a_ , mask_token=a_ , add_prefix_space=a_ , trim_offsets=a_ , **a_ , )
__snake_case = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
if pre_tok_state.get("add_prefix_space" , a_ ) != add_prefix_space:
__snake_case = getattr(a_ , pre_tok_state.pop("type" ) )
__snake_case = add_prefix_space
__snake_case = pre_tok_class(**a_ )
__snake_case = add_prefix_space
# the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
__snake_case = "post_processor"
__snake_case = getattr(self.backend_tokenizer , a_ , a_ )
if tokenizer_component_instance:
__snake_case = 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:
__snake_case = tuple(state["sep"] )
if "cls" in state:
__snake_case = tuple(state["cls"] )
__snake_case = False
if state.get("add_prefix_space" , a_ ) != add_prefix_space:
__snake_case = add_prefix_space
__snake_case = True
if state.get("trim_offsets" , a_ ) != trim_offsets:
__snake_case = trim_offsets
__snake_case = True
if changes_to_apply:
__snake_case = getattr(a_ , state.pop("type" ) )
__snake_case = component_class(**a_ )
setattr(self.backend_tokenizer , a_ , a_ )
@property
def A ( self : Dict ):
"""simple docstring"""
if self._mask_token is None:
if self.verbose:
logger.error("Using mask_token, but it is not set yet." )
return None
return str(self._mask_token )
@mask_token.setter
def A ( self : List[str] , a_ : Any ):
"""simple docstring"""
__snake_case = AddedToken(a_ , lstrip=a_ , rstrip=a_ ) if isinstance(a_ , a_ ) else value
__snake_case = value
def A ( self : Tuple , *a_ : Optional[Any] , **a_ : int ):
"""simple docstring"""
__snake_case = kwargs.get("is_split_into_words" , a_ )
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
"to use it with pretokenized inputs." )
return super()._batch_encode_plus(*a_ , **a_ )
def A ( self : str , *a_ : Optional[Any] , **a_ : Optional[int] ):
"""simple docstring"""
__snake_case = kwargs.get("is_split_into_words" , a_ )
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
"to use it with pretokenized inputs." )
return super()._encode_plus(*a_ , **a_ )
def A ( self : Tuple , a_ : str , a_ : Optional[str] = None ):
"""simple docstring"""
__snake_case = self._tokenizer.model.save(a_ , name=a_ )
return tuple(a_ )
def A ( self : Tuple , a_ : int , a_ : Optional[Any]=None ):
"""simple docstring"""
__snake_case = [self.bos_token_id] + token_ids_a + [self.eos_token_id]
if token_ids_a is None:
return output
return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]
def A ( self : Optional[Any] , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
__snake_case = [self.sep_token_id]
__snake_case = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
| 69 |
'''simple docstring'''
import mpmath # for roots of unity
import numpy as np
class SCREAMING_SNAKE_CASE__ :
def __init__( self : Tuple , a_ : Optional[int]=None , a_ : int=None ):
"""simple docstring"""
__snake_case = list(poly_a or [0] )[:]
__snake_case = list(poly_b or [0] )[:]
# Remove leading zero coefficients
while self.polyA[-1] == 0:
self.polyA.pop()
__snake_case = len(self.polyA )
while self.polyB[-1] == 0:
self.polyB.pop()
__snake_case = len(self.polyB )
# Add 0 to make lengths equal a power of 2
__snake_case = int(
2 ** np.ceil(np.loga(len(self.polyA ) + len(self.polyB ) - 1 ) ) )
while len(self.polyA ) < self.c_max_length:
self.polyA.append(0 )
while len(self.polyB ) < self.c_max_length:
self.polyB.append(0 )
# A complex root used for the fourier transform
__snake_case = complex(mpmath.root(x=1 , n=self.c_max_length , k=1 ) )
# The product
__snake_case = self.__multiply()
def A ( self : Any , a_ : Optional[Any] ):
"""simple docstring"""
__snake_case = [[x] for x in self.polyA] if which == "A" else [[x] for x in self.polyB]
# Corner case
if len(a_ ) <= 1:
return dft[0]
#
__snake_case = self.c_max_length // 2
while next_ncol > 0:
__snake_case = [[] for i in range(a_ )]
__snake_case = self.root**next_ncol
# First half of next step
__snake_case = 1
for j in range(self.c_max_length // (next_ncol * 2) ):
for i in range(a_ ):
new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j] )
current_root *= root
# Second half of next step
__snake_case = 1
for j in range(self.c_max_length // (next_ncol * 2) ):
for i in range(a_ ):
new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j] )
current_root *= root
# Update
__snake_case = new_dft
__snake_case = next_ncol // 2
return dft[0]
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = self.__dft("A" )
__snake_case = self.__dft("B" )
__snake_case = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length )]]
del dft_a
del dft_b
# Corner Case
if len(inverce_c[0] ) <= 1:
return inverce_c[0]
# Inverse DFT
__snake_case = 2
while next_ncol <= self.c_max_length:
__snake_case = [[] for i in range(a_ )]
__snake_case = self.root ** (next_ncol // 2)
__snake_case = 1
# First half of next step
for j in range(self.c_max_length // next_ncol ):
for i in range(next_ncol // 2 ):
# Even positions
new_inverse_c[i].append(
(
inverce_c[i][j]
+ inverce_c[i][j + self.c_max_length // next_ncol]
)
/ 2 )
# Odd positions
new_inverse_c[i + next_ncol // 2].append(
(
inverce_c[i][j]
- inverce_c[i][j + self.c_max_length // next_ncol]
)
/ (2 * current_root) )
current_root *= root
# Update
__snake_case = new_inverse_c
next_ncol *= 2
# Unpack
__snake_case = [round(x[0].real , 8 ) + round(x[0].imag , 8 ) * 1j for x in inverce_c]
# Remove leading 0's
while inverce_c[-1] == 0:
inverce_c.pop()
return inverce_c
def __str__( self : Optional[int] ):
"""simple docstring"""
__snake_case = "A = " + " + ".join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.polyA[: self.len_A] ) )
__snake_case = "B = " + " + ".join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.polyB[: self.len_B] ) )
__snake_case = "A*B = " + " + ".join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.product ) )
return f'''{a}\n{b}\n{c}'''
# Unit tests
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 | 1 |
'''simple docstring'''
import unittest
from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
@require_sentencepiece
@slow # see https://github.com/huggingface/transformers/issues/11457
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = BarthezTokenizer
__SCREAMING_SNAKE_CASE = BarthezTokenizerFast
__SCREAMING_SNAKE_CASE = True
__SCREAMING_SNAKE_CASE = True
def A ( self : Dict ):
"""simple docstring"""
super().setUp()
__snake_case = BarthezTokenizerFast.from_pretrained("moussaKam/mbarthez" )
tokenizer.save_pretrained(self.tmpdirname )
tokenizer.save_pretrained(self.tmpdirname , legacy_format=a_ )
__snake_case = tokenizer
def A ( self : int ):
"""simple docstring"""
__snake_case = "<pad>"
__snake_case = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ )
def A ( self : Any ):
"""simple docstring"""
__snake_case = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , "<s>" )
self.assertEqual(vocab_keys[1] , "<pad>" )
self.assertEqual(vocab_keys[-1] , "<mask>" )
self.assertEqual(len(a_ ) , 101_122 )
def A ( self : Any ):
"""simple docstring"""
self.assertEqual(self.get_tokenizer().vocab_size , 101_122 )
@require_torch
def A ( self : Dict ):
"""simple docstring"""
__snake_case = ["A long paragraph for summarization.", "Another paragraph for summarization."]
__snake_case = [0, 57, 3_018, 70_307, 91, 2]
__snake_case = self.tokenizer(
a_ , max_length=len(a_ ) , padding=a_ , truncation=a_ , return_tensors="pt" )
self.assertIsInstance(a_ , a_ )
self.assertEqual((2, 6) , batch.input_ids.shape )
self.assertEqual((2, 6) , batch.attention_mask.shape )
__snake_case = batch.input_ids.tolist()[0]
self.assertListEqual(a_ , a_ )
def A ( self : List[Any] ):
"""simple docstring"""
if not self.test_rust_tokenizer:
return
__snake_case = self.get_tokenizer()
__snake_case = self.get_rust_tokenizer()
__snake_case = "I was born in 92000, and this is falsé."
__snake_case = tokenizer.tokenize(a_ )
__snake_case = rust_tokenizer.tokenize(a_ )
self.assertListEqual(a_ , a_ )
__snake_case = tokenizer.encode(a_ , add_special_tokens=a_ )
__snake_case = rust_tokenizer.encode(a_ , add_special_tokens=a_ )
self.assertListEqual(a_ , a_ )
__snake_case = self.get_rust_tokenizer()
__snake_case = tokenizer.encode(a_ )
__snake_case = rust_tokenizer.encode(a_ )
self.assertListEqual(a_ , a_ )
@slow
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = {"input_ids": [[0, 490, 14_328, 4_507, 354, 47, 43_669, 95, 25, 78_117, 20_215, 19_779, 190, 22, 400, 4, 35_343, 80_310, 603, 86, 24_937, 105, 33_438, 94_762, 196, 39_642, 7, 15, 15_933, 173, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 10_534, 87, 25, 66, 3_358, 196, 55_289, 8, 82_961, 81, 2_204, 75_203, 7, 15, 763, 12_956, 216, 178, 14_328, 9_595, 1_377, 69_693, 7, 448, 71_021, 196, 18_106, 1_437, 13_974, 108, 9_083, 4, 49_315, 7, 39, 86, 1_326, 2_793, 46_333, 4, 448, 196, 74_588, 7, 49_315, 7, 39, 21, 822, 38_470, 74, 21, 66_723, 62_480, 8, 22_050, 5, 2]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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
# moussaKam/mbarthez is a french model. So we also use french texts.
__snake_case = [
"Le transformeur est un modèle d'apprentissage profond introduit en 2017, "
"utilisé principalement dans le domaine du traitement automatique des langues (TAL).",
"À l'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus "
"pour gérer des données séquentielles, telles que le langage naturel, pour des tâches "
"telles que la traduction et la synthèse de texte.",
]
self.tokenizer_integration_test_util(
expected_encoding=a_ , model_name="moussaKam/mbarthez" , revision="c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6" , sequences=a_ , )
| 69 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
a : List[Any] = {
'''configuration_table_transformer''': [
'''TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''TableTransformerConfig''',
'''TableTransformerOnnxConfig''',
]
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : Tuple = [
'''TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TableTransformerForObjectDetection''',
'''TableTransformerModel''',
'''TableTransformerPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_table_transformer import (
TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
TableTransformerConfig,
TableTransformerOnnxConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_table_transformer import (
TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TableTransformerForObjectDetection,
TableTransformerModel,
TableTransformerPreTrainedModel,
)
else:
import sys
a : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 69 | 1 |
'''simple docstring'''
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import logging
if TYPE_CHECKING:
from ...processing_utils import ProcessorMixin
from ...utils import TensorType
a : List[Any] = logging.get_logger(__name__)
a : Optional[Any] = {
'''microsoft/layoutlmv3-base''': '''https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json''',
}
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = """layoutlmv3"""
def __init__( self : List[str] , a_ : Any=50_265 , a_ : Tuple=768 , a_ : List[str]=12 , a_ : Dict=12 , a_ : List[Any]=3_072 , a_ : Union[str, Any]="gelu" , a_ : Any=0.1 , a_ : Optional[int]=0.1 , a_ : Optional[int]=512 , a_ : Tuple=2 , a_ : Tuple=0.02 , a_ : str=1e-5 , a_ : List[Any]=1 , a_ : Union[str, Any]=0 , a_ : int=2 , a_ : Optional[Any]=1_024 , a_ : Tuple=128 , a_ : Any=128 , a_ : Tuple=True , a_ : List[Any]=32 , a_ : Optional[Any]=128 , a_ : int=64 , a_ : Optional[Any]=256 , a_ : Any=True , a_ : Dict=True , a_ : Optional[int]=True , a_ : List[Any]=224 , a_ : Any=3 , a_ : Union[str, Any]=16 , a_ : int=None , **a_ : Tuple , ):
"""simple docstring"""
super().__init__(
vocab_size=a_ , hidden_size=a_ , num_hidden_layers=a_ , num_attention_heads=a_ , intermediate_size=a_ , hidden_act=a_ , hidden_dropout_prob=a_ , attention_probs_dropout_prob=a_ , max_position_embeddings=a_ , type_vocab_size=a_ , initializer_range=a_ , layer_norm_eps=a_ , pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ , )
__snake_case = max_ad_position_embeddings
__snake_case = coordinate_size
__snake_case = shape_size
__snake_case = has_relative_attention_bias
__snake_case = rel_pos_bins
__snake_case = max_rel_pos
__snake_case = has_spatial_attention_bias
__snake_case = rel_ad_pos_bins
__snake_case = max_rel_ad_pos
__snake_case = text_embed
__snake_case = visual_embed
__snake_case = input_size
__snake_case = num_channels
__snake_case = patch_size
__snake_case = classifier_dropout
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = version.parse("""1.12""" )
@property
def A ( self : Any ):
"""simple docstring"""
if self.task in ["question-answering", "sequence-classification"]:
return OrderedDict(
[
("input_ids", {0: "batch", 1: "sequence"}),
("attention_mask", {0: "batch", 1: "sequence"}),
("bbox", {0: "batch", 1: "sequence"}),
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
] )
else:
return OrderedDict(
[
("input_ids", {0: "batch", 1: "sequence"}),
("bbox", {0: "batch", 1: "sequence"}),
("attention_mask", {0: "batch", 1: "sequence"}),
("pixel_values", {0: "batch", 1: "num_channels"}),
] )
@property
def A ( self : str ):
"""simple docstring"""
return 1e-5
@property
def A ( self : Optional[int] ):
"""simple docstring"""
return 12
def A ( self : Dict , a_ : "ProcessorMixin" , a_ : int = -1 , a_ : int = -1 , a_ : bool = False , a_ : Optional["TensorType"] = None , a_ : int = 3 , a_ : int = 40 , a_ : int = 40 , ):
"""simple docstring"""
setattr(processor.image_processor , "apply_ocr" , a_ )
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
__snake_case = 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
__snake_case = processor.tokenizer.num_special_tokens_to_add(a_ )
__snake_case = 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
__snake_case = [[" ".join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size
# Generate dummy bounding boxes
__snake_case = [[[48, 84, 73, 128]]] * batch_size
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
# batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch)
__snake_case = self._generate_dummy_images(a_ , a_ , a_ , a_ )
__snake_case = dict(
processor(
a_ , text=a_ , boxes=a_ , return_tensors=a_ , ) )
return inputs
| 69 |
'''simple docstring'''
import json
import os
import torch
from diffusers import UNetaDModel
os.makedirs('''hub/hopper-medium-v2/unet/hor32''', exist_ok=True)
os.makedirs('''hub/hopper-medium-v2/unet/hor128''', exist_ok=True)
os.makedirs('''hub/hopper-medium-v2/value_function''', exist_ok=True)
def __UpperCAmelCase ( _UpperCAmelCase : List[str] ) -> str:
if hor == 1_28:
__snake_case = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D")
__snake_case = (32, 1_28, 2_56)
__snake_case = ("UpResnetBlock1D", "UpResnetBlock1D")
elif hor == 32:
__snake_case = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D")
__snake_case = (32, 64, 1_28, 2_56)
__snake_case = ("UpResnetBlock1D", "UpResnetBlock1D", "UpResnetBlock1D")
__snake_case = torch.load(F'''/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch''' )
__snake_case = model.state_dict()
__snake_case = {
"down_block_types": down_block_types,
"block_out_channels": block_out_channels,
"up_block_types": up_block_types,
"layers_per_block": 1,
"use_timestep_embedding": True,
"out_block_type": "OutConv1DBlock",
"norm_num_groups": 8,
"downsample_each_block": False,
"in_channels": 14,
"out_channels": 14,
"extra_in_channels": 0,
"time_embedding_type": "positional",
"flip_sin_to_cos": False,
"freq_shift": 1,
"sample_size": 6_55_36,
"mid_block_type": "MidResTemporalBlock1D",
"act_fn": "mish",
}
__snake_case = UNetaDModel(**_UpperCAmelCase )
print(F'''length of state dict: {len(state_dict.keys() )}''' )
print(F'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' )
__snake_case = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) )
for k, v in mapping.items():
__snake_case = state_dict.pop(_UpperCAmelCase )
hf_value_function.load_state_dict(_UpperCAmelCase )
torch.save(hf_value_function.state_dict() , F'''hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin''' )
with open(F'''hub/hopper-medium-v2/unet/hor{hor}/config.json''' , "w" ) as f:
json.dump(_UpperCAmelCase , _UpperCAmelCase )
def __UpperCAmelCase ( ) -> List[Any]:
__snake_case = {
"in_channels": 14,
"down_block_types": ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D"),
"up_block_types": (),
"out_block_type": "ValueFunction",
"mid_block_type": "ValueFunctionMidBlock1D",
"block_out_channels": (32, 64, 1_28, 2_56),
"layers_per_block": 1,
"downsample_each_block": True,
"sample_size": 6_55_36,
"out_channels": 14,
"extra_in_channels": 0,
"time_embedding_type": "positional",
"use_timestep_embedding": True,
"flip_sin_to_cos": False,
"freq_shift": 1,
"norm_num_groups": 8,
"act_fn": "mish",
}
__snake_case = torch.load("/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch" )
__snake_case = model
__snake_case = UNetaDModel(**_UpperCAmelCase )
print(F'''length of state dict: {len(state_dict.keys() )}''' )
print(F'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' )
__snake_case = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) )
for k, v in mapping.items():
__snake_case = state_dict.pop(_UpperCAmelCase )
hf_value_function.load_state_dict(_UpperCAmelCase )
torch.save(hf_value_function.state_dict() , "hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin" )
with open("hub/hopper-medium-v2/value_function/config.json" , "w" ) as f:
json.dump(_UpperCAmelCase , _UpperCAmelCase )
if __name__ == "__main__":
unet(32)
# unet(128)
value_function()
| 69 | 1 |
'''simple docstring'''
import unittest
from transformers import DonutProcessor
a : Union[str, Any] = '''naver-clova-ix/donut-base'''
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = DonutProcessor.from_pretrained(a_ )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = {
"name": "John Doe",
"age": "99",
"city": "Atlanta",
"state": "GA",
"zip": "30301",
"phone": "123-4567",
"nicknames": [{"nickname": "Johnny"}, {"nickname": "JD"}],
}
__snake_case = (
"<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>"
"<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>"
"<s_nicknames><s_nickname>Johnny</s_nickname>"
"<sep/><s_nickname>JD</s_nickname></s_nicknames>"
)
__snake_case = self.processor.tokenajson(a_ )
self.assertDictEqual(a_ , a_ )
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int = 1_00_00_00 ) -> int:
__snake_case = 1
__snake_case = 1
__snake_case = {1: 1}
for inputa in range(2 , _UpperCAmelCase ):
__snake_case = 0
__snake_case = inputa
while True:
if number in counters:
counter += counters[number]
break
if number % 2 == 0:
number //= 2
counter += 1
else:
__snake_case = (3 * number) + 1
counter += 1
if inputa not in counters:
__snake_case = counter
if counter > pre_counter:
__snake_case = inputa
__snake_case = counter
return largest_number
if __name__ == "__main__":
print(solution(int(input().strip())))
| 69 | 1 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> int:
__snake_case = abs(_UpperCAmelCase )
__snake_case = 0
while n > 0:
res += n % 10
n //= 10
return res
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> int:
__snake_case = abs(_UpperCAmelCase )
return n if n < 10 else n % 10 + sum_of_digits(n // 10 )
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> int:
return sum(int(_UpperCAmelCase ) for c in str(abs(_UpperCAmelCase ) ) )
def __UpperCAmelCase ( ) -> None:
from collections.abc import Callable
from timeit import timeit
def benchmark_a_function(_UpperCAmelCase : Callable , _UpperCAmelCase : int ) -> None:
__snake_case = F'''{func.__name__}({value})'''
__snake_case = timeit(F'''__main__.{call}''' , setup="import __main__" )
print(F'''{call:56} = {func(_UpperCAmelCase )} -- {timing:.4f} seconds''' )
for value in (26_21_44, 11_25_89_99_06_84_26_24, 1_26_76_50_60_02_28_22_94_01_49_67_03_20_53_76):
for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact):
benchmark_a_function(_UpperCAmelCase , _UpperCAmelCase )
print()
if __name__ == "__main__":
import doctest
doctest.testmod()
benchmark()
| 69 |
'''simple docstring'''
from ...processing_utils import ProcessorMixin
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = """SpeechT5FeatureExtractor"""
__SCREAMING_SNAKE_CASE = """SpeechT5Tokenizer"""
def __init__( self : List[Any] , a_ : str , a_ : str ):
"""simple docstring"""
super().__init__(a_ , a_ )
def __call__( self : Dict , *a_ : Tuple , **a_ : List[str] ):
"""simple docstring"""
__snake_case = kwargs.pop("audio" , a_ )
__snake_case = kwargs.pop("text" , a_ )
__snake_case = kwargs.pop("text_target" , a_ )
__snake_case = kwargs.pop("audio_target" , a_ )
__snake_case = kwargs.pop("sampling_rate" , a_ )
if audio is not None and text is not None:
raise ValueError(
"Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?" )
if audio_target is not None and text_target is not None:
raise ValueError(
"Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?" )
if audio is None and audio_target is None and text is None and text_target is None:
raise ValueError(
"You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process." )
if audio is not None:
__snake_case = self.feature_extractor(a_ , *a_ , sampling_rate=a_ , **a_ )
elif text is not None:
__snake_case = self.tokenizer(a_ , **a_ )
else:
__snake_case = None
if audio_target is not None:
__snake_case = self.feature_extractor(audio_target=a_ , *a_ , sampling_rate=a_ , **a_ )
__snake_case = targets["input_values"]
elif text_target is not None:
__snake_case = self.tokenizer(a_ , **a_ )
__snake_case = targets["input_ids"]
else:
__snake_case = None
if inputs is None:
return targets
if targets is not None:
__snake_case = labels
__snake_case = targets.get("attention_mask" )
if decoder_attention_mask is not None:
__snake_case = decoder_attention_mask
return inputs
def A ( self : List[str] , *a_ : str , **a_ : Dict ):
"""simple docstring"""
__snake_case = kwargs.pop("input_values" , a_ )
__snake_case = kwargs.pop("input_ids" , a_ )
__snake_case = kwargs.pop("labels" , a_ )
if input_values is not None and input_ids is not None:
raise ValueError("Cannot process both `input_values` and `input_ids` inputs." )
if input_values is None and input_ids is None and labels is None:
raise ValueError(
"You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded." )
if input_values is not None:
__snake_case = self.feature_extractor.pad(a_ , *a_ , **a_ )
elif input_ids is not None:
__snake_case = self.tokenizer.pad(a_ , **a_ )
else:
__snake_case = None
if labels is not None:
if "input_ids" in labels or (isinstance(a_ , a_ ) and "input_ids" in labels[0]):
__snake_case = self.tokenizer.pad(a_ , **a_ )
__snake_case = targets["input_ids"]
else:
__snake_case = self.feature_extractor.feature_size
__snake_case = self.feature_extractor.num_mel_bins
__snake_case = self.feature_extractor.pad(a_ , *a_ , **a_ )
__snake_case = feature_size_hack
__snake_case = targets["input_values"]
else:
__snake_case = None
if inputs is None:
return targets
if targets is not None:
__snake_case = labels
__snake_case = targets.get("attention_mask" )
if decoder_attention_mask is not None:
__snake_case = decoder_attention_mask
return inputs
def A ( self : List[str] , *a_ : Any , **a_ : List[str] ):
"""simple docstring"""
return self.tokenizer.batch_decode(*a_ , **a_ )
def A ( self : Optional[int] , *a_ : Union[str, Any] , **a_ : str ):
"""simple docstring"""
return self.tokenizer.decode(*a_ , **a_ )
| 69 | 1 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
a : List[Any] = {
'''configuration_roc_bert''': ['''ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RoCBertConfig'''],
'''tokenization_roc_bert''': ['''RoCBertTokenizer'''],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
pass
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : List[Any] = [
'''ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''RoCBertForCausalLM''',
'''RoCBertForMaskedLM''',
'''RoCBertForMultipleChoice''',
'''RoCBertForPreTraining''',
'''RoCBertForQuestionAnswering''',
'''RoCBertForSequenceClassification''',
'''RoCBertForTokenClassification''',
'''RoCBertLayer''',
'''RoCBertModel''',
'''RoCBertPreTrainedModel''',
'''load_tf_weights_in_roc_bert''',
]
if TYPE_CHECKING:
from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig
from .tokenization_roc_bert import RoCBertTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
raise OptionalDependencyNotAvailable()
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_roc_bert import (
ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
RoCBertForCausalLM,
RoCBertForMaskedLM,
RoCBertForMultipleChoice,
RoCBertForPreTraining,
RoCBertForQuestionAnswering,
RoCBertForSequenceClassification,
RoCBertForTokenClassification,
RoCBertLayer,
RoCBertModel,
RoCBertPreTrainedModel,
load_tf_weights_in_roc_bert,
)
else:
import sys
a : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 69 |
'''simple docstring'''
import re
from pathlib import Path
from unittest import TestCase
import pytest
@pytest.mark.integration
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def A ( self : Optional[Any] , a_ : str ):
"""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 A ( self : Any , a_ : str ):
"""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 A ( self : Optional[int] ):
"""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 A ( self : Optional[Any] ):
"""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.''' )
| 69 | 1 |
'''simple docstring'''
import argparse
import json
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
from accelerate.utils.deepspeed import DummyOptim, DummyScheduler
a : Tuple = 16
a : Optional[Any] = 32
def __UpperCAmelCase ( _UpperCAmelCase : Accelerator , _UpperCAmelCase : int = 16 , _UpperCAmelCase : str = "bert-base-cased" ) -> Any:
__snake_case = AutoTokenizer.from_pretrained(_UpperCAmelCase )
__snake_case = load_dataset("glue" , "mrpc" )
def tokenize_function(_UpperCAmelCase : List[Any] ):
# max_length=None => use the model max length (it's actually the default)
__snake_case = 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
__snake_case = datasets.map(
_UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=["idx", "sentence1", "sentence2"] , load_from_cache_file=_UpperCAmelCase )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
__snake_case = tokenized_datasets.rename_column("label" , "labels" )
def collate_fn(_UpperCAmelCase : Tuple ):
# 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(_UpperCAmelCase , padding="max_length" , max_length=1_28 , return_tensors="pt" )
return tokenizer.pad(_UpperCAmelCase , padding="longest" , return_tensors="pt" )
# Instantiate dataloaders.
__snake_case = DataLoader(
tokenized_datasets["train"] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase )
__snake_case = DataLoader(
tokenized_datasets["validation"] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase )
return train_dataloader, eval_dataloader
def __UpperCAmelCase ( _UpperCAmelCase : Optional[int] , _UpperCAmelCase : str , _UpperCAmelCase : Any , _UpperCAmelCase : List[Any] ) -> int:
model.eval()
__snake_case = 0
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():
__snake_case = model(**_UpperCAmelCase )
__snake_case = outputs.logits.argmax(dim=-1 )
# It is slightly faster to call this once, than multiple times
__snake_case , __snake_case = accelerator.gather(
(predictions, batch["labels"]) ) # If we are in a multiprocess environment, the last batch has duplicates
if accelerator.use_distributed:
if step == len(_UpperCAmelCase ) - 1:
__snake_case = predictions[: len(eval_dataloader.dataset ) - samples_seen]
__snake_case = references[: len(eval_dataloader.dataset ) - samples_seen]
else:
samples_seen += references.shape[0]
metric.add_batch(
predictions=_UpperCAmelCase , references=_UpperCAmelCase , )
__snake_case = metric.compute()
return eval_metric["accuracy"]
def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : Dict ) -> Optional[Any]:
# Initialize accelerator
__snake_case = Accelerator()
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
__snake_case = config["lr"]
__snake_case = int(config["num_epochs"] )
__snake_case = int(config["seed"] )
__snake_case = int(config["batch_size"] )
__snake_case = args.model_name_or_path
set_seed(_UpperCAmelCase )
__snake_case , __snake_case = get_dataloaders(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
__snake_case = AutoModelForSequenceClassification.from_pretrained(_UpperCAmelCase , return_dict=_UpperCAmelCase )
# Instantiate optimizer
__snake_case = (
AdamW
if accelerator.state.deepspeed_plugin is None
or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config
else DummyOptim
)
__snake_case = optimizer_cls(params=model.parameters() , lr=_UpperCAmelCase )
if accelerator.state.deepspeed_plugin is not None:
__snake_case = accelerator.state.deepspeed_plugin.deepspeed_config[
"gradient_accumulation_steps"
]
else:
__snake_case = 1
__snake_case = (len(_UpperCAmelCase ) * num_epochs) // gradient_accumulation_steps
# Instantiate scheduler
if (
accelerator.state.deepspeed_plugin is None
or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
):
__snake_case = get_linear_schedule_with_warmup(
optimizer=_UpperCAmelCase , num_warmup_steps=0 , num_training_steps=_UpperCAmelCase , )
else:
__snake_case = DummyScheduler(_UpperCAmelCase , total_num_steps=_UpperCAmelCase , 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.
__snake_case , __snake_case , __snake_case , __snake_case , __snake_case = accelerator.prepare(
_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
# We need to keep track of how many total steps we have iterated over
__snake_case = 0
# We also need to keep track of the stating epoch so files are named properly
__snake_case = 0
__snake_case = evaluate.load("glue" , "mrpc" )
__snake_case = num_epochs
if args.partial_train_epoch is not None:
__snake_case = args.partial_train_epoch
if args.resume_from_checkpoint:
accelerator.load_state(args.resume_from_checkpoint )
__snake_case = args.resume_from_checkpoint.split("epoch_" )[1]
__snake_case = ""
for char in epoch_string:
if char.isdigit():
state_epoch_num += char
else:
break
__snake_case = int(_UpperCAmelCase ) + 1
__snake_case = evaluation_loop(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
accelerator.print("resumed checkpoint performance:" , _UpperCAmelCase )
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:
__snake_case = json.load(_UpperCAmelCase )
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
__snake_case = {}
for epoch in range(_UpperCAmelCase , _UpperCAmelCase ):
model.train()
for step, batch in enumerate(_UpperCAmelCase ):
__snake_case = model(**_UpperCAmelCase )
__snake_case = outputs.loss
__snake_case = loss / gradient_accumulation_steps
accelerator.backward(_UpperCAmelCase )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
overall_step += 1
__snake_case = F'''epoch_{epoch}'''
__snake_case = os.path.join(args.output_dir , _UpperCAmelCase )
accelerator.save_state(_UpperCAmelCase )
__snake_case = evaluation_loop(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
__snake_case = accuracy
__snake_case = lr_scheduler.get_lr()[0]
__snake_case = optimizer.param_groups[0]["lr"]
__snake_case = epoch
__snake_case = overall_step
accelerator.print(F'''epoch {epoch}:''' , _UpperCAmelCase )
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(_UpperCAmelCase , _UpperCAmelCase )
def __UpperCAmelCase ( ) -> Union[str, Any]:
__snake_case = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage." )
parser.add_argument(
"--model_name_or_path" , type=_UpperCAmelCase , default="bert-base-cased" , help="Path to pretrained model or model identifier from huggingface.co/models." , required=_UpperCAmelCase , )
parser.add_argument(
"--output_dir" , type=_UpperCAmelCase , 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=_UpperCAmelCase , default=_UpperCAmelCase , help="If the training should continue from a checkpoint folder." , )
parser.add_argument(
"--partial_train_epoch" , type=_UpperCAmelCase , default=_UpperCAmelCase , help="If passed, the training will stop after this number of epochs." , )
parser.add_argument(
"--num_epochs" , type=_UpperCAmelCase , default=2 , help="Number of train epochs." , )
__snake_case = parser.parse_args()
__snake_case = {"lr": 2E-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16}
training_function(_UpperCAmelCase , _UpperCAmelCase )
if __name__ == "__main__":
main()
| 69 |
'''simple docstring'''
import os
from shutil import copyfile
from typing import List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
a : Optional[Any] = logging.get_logger(__name__)
a : Dict = {'''vocab_file''': '''sentencepiece.model'''}
a : Tuple = {
'''vocab_file''': {
'''google/rembert''': '''https://huggingface.co/google/rembert/resolve/main/sentencepiece.model''',
},
}
a : str = {
'''google/rembert''': 256,
}
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES
__SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP
__SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__( self : Optional[Any] , a_ : int , a_ : Any=False , a_ : List[Any]=True , a_ : List[Any]=True , a_ : List[Any]="[CLS]" , a_ : List[Any]="[SEP]" , a_ : List[Any]="[UNK]" , a_ : str="[SEP]" , a_ : List[str]="[PAD]" , a_ : Optional[int]="[CLS]" , a_ : List[str]="[MASK]" , **a_ : str , ):
"""simple docstring"""
super().__init__(
do_lower_case=a_ , remove_space=a_ , keep_accents=a_ , bos_token=a_ , eos_token=a_ , unk_token=a_ , sep_token=a_ , pad_token=a_ , cls_token=a_ , mask_token=a_ , **a_ , )
__snake_case = do_lower_case
__snake_case = remove_space
__snake_case = keep_accents
__snake_case = vocab_file
__snake_case = spm.SentencePieceProcessor()
self.sp_model.Load(a_ )
@property
def A ( self : Optional[Any] ):
"""simple docstring"""
return len(self.sp_model )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = {self.convert_ids_to_tokens(a_ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self : Dict ):
"""simple docstring"""
__snake_case = self.__dict__.copy()
__snake_case = None
return state
def __setstate__( self : str , a_ : Optional[int] ):
"""simple docstring"""
__snake_case = d
__snake_case = spm.SentencePieceProcessor()
self.sp_model.Load(self.vocab_file )
def A ( self : Tuple , a_ : Optional[int] , a_ : int=False ):
"""simple docstring"""
__snake_case = self.sp_model.EncodeAsPieces(a_ )
return pieces
def A ( self : Any , a_ : Optional[Any] ):
"""simple docstring"""
return self.sp_model.PieceToId(a_ )
def A ( self : Optional[Any] , a_ : List[str] ):
"""simple docstring"""
return self.sp_model.IdToPiece(a_ )
def A ( self : Optional[Any] , a_ : int ):
"""simple docstring"""
__snake_case = self.sp_model.decode_pieces(a_ )
return out_string
def A ( self : Union[str, Any] , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
__snake_case = [self.sep_token_id]
__snake_case = [self.cls_token_id]
if token_ids_a is None:
return cls + token_ids_a + sep
return cls + token_ids_a + sep + token_ids_a + sep
def A ( self : List[str] , a_ : List[int] , a_ : Optional[List[int]] = None , a_ : bool = False ):
"""simple docstring"""
if already_has_special_tokens:
if token_ids_a is not None:
raise ValueError(
"You should not supply a second sequence if the provided sequence of "
"ids is already formatted with special tokens for the model." )
return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]
if token_ids_a is not None:
return [1] + ([0] * len(a_ )) + [1] + ([0] * len(a_ )) + [1]
return [1] + ([0] * len(a_ )) + [1]
def A ( self : Tuple , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
__snake_case = [self.sep_token_id]
__snake_case = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def A ( self : List[Any] , a_ : str , a_ : Optional[str] = None ):
"""simple docstring"""
if not os.path.isdir(a_ ):
logger.error("Vocabulary path ({}) should be a directory".format(a_ ) )
return
__snake_case = 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_ ):
copyfile(self.vocab_file , a_ )
return (out_vocab_file,)
| 69 | 1 |
'''simple docstring'''
# This is the module that test_patching.py uses to test patch_submodule()
import os # noqa: this is just for tests
import os as renamed_os # noqa: this is just for tests
from os import path # noqa: this is just for tests
from os import path as renamed_path # noqa: this is just for tests
from os.path import join # noqa: this is just for tests
from os.path import join as renamed_join # noqa: this is just for tests
a : Tuple = open # noqa: we just need to have a builtin inside this module to test it properly
| 69 |
'''simple docstring'''
import os
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from huggingface_hub import HfFolder, delete_repo
from huggingface_hub.file_download import http_get
from requests.exceptions import HTTPError
from transformers import (
AlbertTokenizer,
AutoTokenizer,
BertTokenizer,
BertTokenizerFast,
GPTaTokenizerFast,
is_tokenizers_available,
)
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers
from transformers.tokenization_utils import Trie
sys.path.append(str(Path(__file__).parent.parent / '''utils'''))
from test_module.custom_tokenization import CustomTokenizer # noqa E402
if is_tokenizers_available():
from test_module.custom_tokenization_fast import CustomTokenizerFast
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = mock.Mock()
__snake_case = 500
__snake_case = {}
__snake_case = HTTPError
__snake_case = {}
# Download this model to make sure it's in the cache.
__snake_case = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" )
# Under the mock environment we get a 500 error when trying to reach the tokenizer.
with mock.patch("requests.Session.request" , return_value=a_ ) as mock_head:
__snake_case = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" )
# This check we did call the fake head request
mock_head.assert_called()
@require_tokenizers
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = mock.Mock()
__snake_case = 500
__snake_case = {}
__snake_case = HTTPError
__snake_case = {}
# Download this model to make sure it's in the cache.
__snake_case = GPTaTokenizerFast.from_pretrained("gpt2" )
# Under the mock environment we get a 500 error when trying to reach the tokenizer.
with mock.patch("requests.Session.request" , return_value=a_ ) as mock_head:
__snake_case = GPTaTokenizerFast.from_pretrained("gpt2" )
# This check we did call the fake head request
mock_head.assert_called()
def A ( self : Optional[Any] ):
"""simple docstring"""
try:
__snake_case = tempfile.mktemp()
with open(a_ , "wb" ) as f:
http_get("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" , a_ )
__snake_case = AlbertTokenizer.from_pretrained(a_ )
finally:
os.remove(a_ )
# Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in
# the current folder and have the right name.
if os.path.isfile("tokenizer.json" ):
# We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it.
return
try:
with open("tokenizer.json" , "wb" ) as f:
http_get("https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json" , a_ )
__snake_case = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" )
# The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000
self.assertEqual(tokenizer.vocab_size , 1_000 )
# Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file.
finally:
os.remove("tokenizer.json" )
def A ( self : str ):
"""simple docstring"""
__snake_case = AlbertTokenizer.from_pretrained("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" )
@is_staging_test
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
__SCREAMING_SNAKE_CASE = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""]
@classmethod
def A ( cls : List[Any] ):
"""simple docstring"""
__snake_case = TOKEN
HfFolder.save_token(a_ )
@classmethod
def A ( cls : List[Any] ):
"""simple docstring"""
try:
delete_repo(token=cls._token , repo_id="test-tokenizer" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="valid_org/test-tokenizer-org" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="test-dynamic-tokenizer" )
except HTTPError:
pass
def A ( self : int ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = BertTokenizer(a_ )
tokenizer.push_to_hub("test-tokenizer" , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
# Reset repo
delete_repo(token=self._token , repo_id="test-tokenizer" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(a_ , repo_id="test-tokenizer" , push_to_hub=a_ , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
def A ( self : int ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = BertTokenizer(a_ )
tokenizer.push_to_hub("valid_org/test-tokenizer-org" , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
# Reset repo
delete_repo(token=self._token , repo_id="valid_org/test-tokenizer-org" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(
a_ , repo_id="valid_org/test-tokenizer-org" , push_to_hub=a_ , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
@require_tokenizers
def A ( self : List[str] ):
"""simple docstring"""
CustomTokenizer.register_for_auto_class()
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = CustomTokenizer(a_ )
# No fast custom tokenizer
tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token )
__snake_case = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=a_ )
# Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module
self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizer" )
# Fast and slow custom tokenizer
CustomTokenizerFast.register_for_auto_class()
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = BertTokenizerFast.from_pretrained(a_ )
bert_tokenizer.save_pretrained(a_ )
__snake_case = CustomTokenizerFast.from_pretrained(a_ )
tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token )
__snake_case = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=a_ )
# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizerFast" )
__snake_case = AutoTokenizer.from_pretrained(
f'''{USER}/test-dynamic-tokenizer''' , use_fast=a_ , trust_remote_code=a_ )
# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizer" )
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def A ( self : Optional[int] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("Hello 友達" )
self.assertEqual(trie.data , {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}} )
trie.add("Hello" )
trie.data
self.assertEqual(trie.data , {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}} )
def A ( self : str ):
"""simple docstring"""
__snake_case = Trie()
self.assertEqual(trie.split("[CLS] This is a extra_id_100" ) , ["[CLS] This is a extra_id_100"] )
trie.add("[CLS]" )
trie.add("extra_id_1" )
trie.add("extra_id_100" )
self.assertEqual(trie.split("[CLS] This is a extra_id_100" ) , ["[CLS]", " This is a ", "extra_id_100"] )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("A" )
self.assertEqual(trie.split("ABC" ) , ["A", "BC"] )
self.assertEqual(trie.split("BCA" ) , ["BC", "A"] )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("TOKEN]" )
trie.add("[SPECIAL_TOKEN]" )
self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] )
def A ( self : str ):
"""simple docstring"""
__snake_case = Trie()
trie.add("A" )
trie.add("P" )
trie.add("[SPECIAL_TOKEN]" )
self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] )
def A ( self : Optional[int] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("AB" )
trie.add("B" )
trie.add("C" )
self.assertEqual(trie.split("ABC" ) , ["AB", "C"] )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = Trie()
trie.add("ABC" )
trie.add("B" )
trie.add("CD" )
self.assertEqual(trie.split("ABCD" ) , ["ABC", "D"] )
def A ( self : Any ):
"""simple docstring"""
__snake_case = Trie()
__snake_case = trie.cut_text("ABC" , [0, 0, 2, 1, 2, 3] )
self.assertEqual(a_ , ["AB", "C"] )
| 69 | 1 |
'''simple docstring'''
import random
def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : float , _UpperCAmelCase : bool = False ) -> dict:
__snake_case = {i: [] for i in range(_UpperCAmelCase )}
# if probability is greater or equal than 1, then generate a complete graph
if probability >= 1:
return complete_graph(_UpperCAmelCase )
# if probability is lower or equal than 0, then return a graph without edges
if probability <= 0:
return graph
# for each couple of nodes, add an edge from u to v
# if the number randomly generated is greater than probability probability
for i in range(_UpperCAmelCase ):
for j in range(i + 1 , _UpperCAmelCase ):
if random.random() < probability:
graph[i].append(_UpperCAmelCase )
if not directed:
# if the graph is undirected, add an edge in from j to i, either
graph[j].append(_UpperCAmelCase )
return graph
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> dict:
return {
i: [j for j in range(_UpperCAmelCase ) if i != j] for i in range(_UpperCAmelCase )
}
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> int:
assert (
isinstance(_UpperCAmelCase , _UpperCAmelCase ) and number_of_steps > 0
), F'''number_of_steps needs to be positive integer, your input {number_of_steps}'''
if number_of_steps == 1:
return 1
__snake_case , __snake_case = 1, 1
for _ in range(number_of_steps - 1 ):
__snake_case , __snake_case = current + previous, current
return current
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 | 1 |
'''simple docstring'''
from collections import UserDict
from typing import List, Union
from ..utils import (
add_end_docstrings,
is_tf_available,
is_torch_available,
is_vision_available,
logging,
requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_vision_available():
from PIL import Image
from ..image_utils import load_image
if is_torch_available():
from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
if is_tf_available():
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
from ..tf_utils import stable_softmax
a : Optional[Any] = logging.get_logger(__name__)
@add_end_docstrings(_UpperCamelCase )
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def __init__( self : Tuple , **a_ : str ):
"""simple docstring"""
super().__init__(**a_ )
requires_backends(self , "vision" )
self.check_model_type(
TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
if self.framework == "tf"
else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING )
def __call__( self : Optional[int] , a_ : Union[str, List[str], "Image", List["Image"]] , **a_ : Union[str, Any] ):
"""simple docstring"""
return super().__call__(a_ , **a_ )
def A ( self : List[str] , **a_ : Any ):
"""simple docstring"""
__snake_case = {}
if "candidate_labels" in kwargs:
__snake_case = kwargs["candidate_labels"]
if "hypothesis_template" in kwargs:
__snake_case = kwargs["hypothesis_template"]
return preprocess_params, {}, {}
def A ( self : str , a_ : List[str] , a_ : Optional[Any]=None , a_ : Optional[Any]="This is a photo of {}." ):
"""simple docstring"""
__snake_case = load_image(a_ )
__snake_case = self.image_processor(images=[image] , return_tensors=self.framework )
__snake_case = candidate_labels
__snake_case = [hypothesis_template.format(a_ ) for x in candidate_labels]
__snake_case = self.tokenizer(a_ , return_tensors=self.framework , padding=a_ )
__snake_case = [text_inputs]
return inputs
def A ( self : Tuple , a_ : Optional[int] ):
"""simple docstring"""
__snake_case = model_inputs.pop("candidate_labels" )
__snake_case = model_inputs.pop("text_inputs" )
if isinstance(text_inputs[0] , a_ ):
__snake_case = text_inputs[0]
else:
# Batching case.
__snake_case = text_inputs[0][0]
__snake_case = self.model(**a_ , **a_ )
__snake_case = {
"candidate_labels": candidate_labels,
"logits": outputs.logits_per_image,
}
return model_outputs
def A ( self : Any , a_ : int ):
"""simple docstring"""
__snake_case = model_outputs.pop("candidate_labels" )
__snake_case = model_outputs["logits"][0]
if self.framework == "pt":
__snake_case = logits.softmax(dim=-1 ).squeeze(-1 )
__snake_case = probs.tolist()
if not isinstance(a_ , a_ ):
__snake_case = [scores]
elif self.framework == "tf":
__snake_case = stable_softmax(a_ , axis=-1 )
__snake_case = probs.numpy().tolist()
else:
raise ValueError(f'''Unsupported framework: {self.framework}''' )
__snake_case = [
{"score": score, "label": candidate_label}
for score, candidate_label in sorted(zip(a_ , a_ ) , key=lambda a_ : -x[0] )
]
return result
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> str:
return " ".join(
"".join(word[::-1] ) if len(_UpperCAmelCase ) > 4 else word for word in sentence.split() )
if __name__ == "__main__":
import doctest
doctest.testmod()
print(reverse_long_words('''Hey wollef sroirraw'''))
| 69 | 1 |
'''simple docstring'''
import warnings
from ...utils import logging
from .image_processing_videomae import VideoMAEImageProcessor
a : List[Any] = logging.get_logger(__name__)
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def __init__( self : List[Any] , *a_ : int , **a_ : str ):
"""simple docstring"""
warnings.warn(
"The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers."
" Please use VideoMAEImageProcessor instead." , a_ , )
super().__init__(*a_ , **a_ )
| 69 |
'''simple docstring'''
import unittest
from transformers import MPNetConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
MPNetForMaskedLM,
MPNetForMultipleChoice,
MPNetForQuestionAnswering,
MPNetForSequenceClassification,
MPNetForTokenClassification,
MPNetModel,
)
class SCREAMING_SNAKE_CASE__ :
def __init__( self : str , a_ : Any , a_ : Union[str, Any]=13 , a_ : Any=7 , a_ : Any=True , a_ : Dict=True , a_ : Union[str, Any]=False , a_ : Tuple=True , a_ : str=99 , a_ : Tuple=64 , a_ : Tuple=5 , a_ : Union[str, Any]=4 , a_ : Dict=64 , a_ : Union[str, Any]="gelu" , a_ : Dict=0.1 , a_ : List[str]=0.1 , a_ : Dict=512 , a_ : Tuple=16 , a_ : str=2 , a_ : Any=0.02 , a_ : List[Any]=3 , a_ : Tuple=4 , a_ : Optional[int]=None , ):
"""simple docstring"""
__snake_case = parent
__snake_case = batch_size
__snake_case = seq_length
__snake_case = is_training
__snake_case = use_input_mask
__snake_case = use_token_type_ids
__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_act
__snake_case = hidden_dropout_prob
__snake_case = attention_probs_dropout_prob
__snake_case = max_position_embeddings
__snake_case = type_vocab_size
__snake_case = type_sequence_label_size
__snake_case = initializer_range
__snake_case = num_labels
__snake_case = num_choices
__snake_case = scope
def A ( self : int ):
"""simple docstring"""
return MPNetConfig.from_pretrained("microsoft/mpnet-base" )
def A ( self : str ):
"""simple docstring"""
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__snake_case = None
if self.use_input_mask:
__snake_case = random_attention_mask([self.batch_size, self.seq_length] )
__snake_case = None
__snake_case = None
__snake_case = None
if self.use_labels:
__snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__snake_case = ids_tensor([self.batch_size] , self.num_choices )
__snake_case = self.get_config()
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
def A ( self : List[str] ):
"""simple docstring"""
return MPNetConfig(
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 , initializer_range=self.initializer_range , )
def A ( self : Tuple , a_ : int , a_ : str , a_ : Optional[int] , a_ : List[Any] , a_ : str , a_ : Optional[Any] ):
"""simple docstring"""
__snake_case = MPNetModel(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , a_ )
__snake_case = model(a_ )
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 A ( self : Any , a_ : int , a_ : Tuple , a_ : str , a_ : int , a_ : str , a_ : List[Any] ):
"""simple docstring"""
__snake_case = MPNetForQuestionAnswering(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(
a_ , attention_mask=a_ , start_positions=a_ , end_positions=a_ , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def A ( self : Any , a_ : Any , a_ : int , a_ : Union[str, Any] , a_ : Dict , a_ : Optional[Any] , a_ : Any ):
"""simple docstring"""
__snake_case = self.num_labels
__snake_case = MPNetForSequenceClassification(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def A ( self : Optional[Any] , a_ : Any , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : List[Any] , a_ : List[Any] ):
"""simple docstring"""
__snake_case = self.num_choices
__snake_case = MPNetForMultipleChoice(config=a_ )
model.to(a_ )
model.eval()
__snake_case = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__snake_case = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__snake_case = model(
a_ , attention_mask=a_ , labels=a_ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def A ( self : Dict , a_ : List[str] , a_ : str , a_ : Union[str, Any] , a_ : str , a_ : Optional[int] , a_ : Optional[Any] ):
"""simple docstring"""
__snake_case = self.num_labels
__snake_case = MPNetForTokenClassification(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.prepare_config_and_inputs()
((__snake_case) , (__snake_case) , (__snake_case) , (__snake_case) , (__snake_case) , (__snake_case)) = config_and_inputs
__snake_case = {"input_ids": input_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = (
(
MPNetForMaskedLM,
MPNetForMultipleChoice,
MPNetForQuestionAnswering,
MPNetForSequenceClassification,
MPNetForTokenClassification,
MPNetModel,
)
if is_torch_available()
else ()
)
__SCREAMING_SNAKE_CASE = (
{
"""feature-extraction""": MPNetModel,
"""fill-mask""": MPNetForMaskedLM,
"""question-answering""": MPNetForQuestionAnswering,
"""text-classification""": MPNetForSequenceClassification,
"""token-classification""": MPNetForTokenClassification,
"""zero-shot""": MPNetForSequenceClassification,
}
if is_torch_available()
else {}
)
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = True
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = MPNetModelTester(self )
__snake_case = ConfigTester(self , config_class=a_ , hidden_size=37 )
def A ( self : List[Any] ):
"""simple docstring"""
self.config_tester.run_common_tests()
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_model(*a_ )
def A ( self : Dict ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_sequence_classification(*a_ )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_multiple_choice(*a_ )
def A ( self : int ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_token_classification(*a_ )
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_question_answering(*a_ )
@require_torch
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
@slow
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = MPNetModel.from_pretrained("microsoft/mpnet-base" )
__snake_case = torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] )
__snake_case = model(a_ )[0]
__snake_case = torch.Size((1, 11, 768) )
self.assertEqual(output.shape , a_ )
__snake_case = torch.tensor(
[[[-0.0550, 0.1943, -0.0740], [-0.0562, 0.2211, -0.0579], [-0.0437, 0.3337, -0.0641]]] )
# compare the actual values for a slice.
self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) )
| 69 | 1 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
a : List[str] = {
'''configuration_chinese_clip''': [
'''CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''ChineseCLIPConfig''',
'''ChineseCLIPOnnxConfig''',
'''ChineseCLIPTextConfig''',
'''ChineseCLIPVisionConfig''',
],
'''processing_chinese_clip''': ['''ChineseCLIPProcessor'''],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : str = ['''ChineseCLIPFeatureExtractor''']
a : Any = ['''ChineseCLIPImageProcessor''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : Optional[Any] = [
'''CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''ChineseCLIPModel''',
'''ChineseCLIPPreTrainedModel''',
'''ChineseCLIPTextModel''',
'''ChineseCLIPVisionModel''',
]
if TYPE_CHECKING:
from .configuration_chinese_clip import (
CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
ChineseCLIPConfig,
ChineseCLIPOnnxConfig,
ChineseCLIPTextConfig,
ChineseCLIPVisionConfig,
)
from .processing_chinese_clip import ChineseCLIPProcessor
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_chinese_clip import (
CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
ChineseCLIPModel,
ChineseCLIPPreTrainedModel,
ChineseCLIPTextModel,
ChineseCLIPVisionModel,
)
else:
import sys
a : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 69 |
'''simple docstring'''
# Logistic Regression from scratch
# In[62]:
# In[63]:
# importing all the required libraries
import numpy as np
from matplotlib import pyplot as plt
from sklearn import datasets
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> Optional[int]:
return 1 / (1 + np.exp(-z ))
def __UpperCAmelCase ( _UpperCAmelCase : Tuple , _UpperCAmelCase : Dict ) -> List[str]:
return (-y * np.log(_UpperCAmelCase ) - (1 - y) * np.log(1 - h )).mean()
def __UpperCAmelCase ( _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : List[Any] ) -> Optional[Any]:
__snake_case = np.dot(_UpperCAmelCase , _UpperCAmelCase )
return np.sum(y * scores - np.log(1 + np.exp(_UpperCAmelCase ) ) )
def __UpperCAmelCase ( _UpperCAmelCase : List[Any] , _UpperCAmelCase : str , _UpperCAmelCase : Dict , _UpperCAmelCase : List[str]=7_00_00 ) -> Union[str, Any]:
__snake_case = np.zeros(x.shape[1] )
for iterations in range(_UpperCAmelCase ):
__snake_case = np.dot(_UpperCAmelCase , _UpperCAmelCase )
__snake_case = sigmoid_function(_UpperCAmelCase )
__snake_case = np.dot(x.T , h - y ) / y.size
__snake_case = theta - alpha * gradient # updating the weights
__snake_case = np.dot(_UpperCAmelCase , _UpperCAmelCase )
__snake_case = sigmoid_function(_UpperCAmelCase )
__snake_case = cost_function(_UpperCAmelCase , _UpperCAmelCase )
if iterations % 1_00 == 0:
print(F'''loss: {j} \t''' ) # printing the loss after every 100 iterations
return theta
# In[68]:
if __name__ == "__main__":
a : int = datasets.load_iris()
a : int = iris.data[:, :2]
a : Optional[Any] = (iris.target != 0) * 1
a : Tuple = 0.1
a : List[str] = logistic_reg(alpha, x, y, max_iterations=70_000)
print('''theta: ''', theta) # printing the theta i.e our weights vector
def __UpperCAmelCase ( _UpperCAmelCase : Optional[int] ) -> Union[str, Any]:
return sigmoid_function(
np.dot(_UpperCAmelCase , _UpperCAmelCase ) ) # predicting the value of probability from the logistic regression algorithm
plt.figure(figsize=(10, 6))
plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color='''b''', label='''0''')
plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color='''r''', label='''1''')
((a) , (a)) : Any = (x[:, 0].min(), x[:, 0].max())
((a) , (a)) : Any = (x[:, 1].min(), x[:, 1].max())
((a) , (a)) : Any = np.meshgrid(np.linspace(xa_min, xa_max), np.linspace(xa_min, xa_max))
a : Optional[Any] = np.c_[xxa.ravel(), xxa.ravel()]
a : List[Any] = predict_prob(grid).reshape(xxa.shape)
plt.contour(xxa, xxa, probs, [0.5], linewidths=1, colors='''black''')
plt.legend()
plt.show()
| 69 | 1 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : float , _UpperCAmelCase : float , _UpperCAmelCase : float , _UpperCAmelCase : float , _UpperCAmelCase : float , ) -> float:
__snake_case = [redshift, radiation_density, matter_density, dark_energy]
if any(p < 0 for p in parameters ):
raise ValueError("All input parameters must be positive" )
if any(p > 1 for p in parameters[1:4] ):
raise ValueError("Relative densities cannot be greater than one" )
else:
__snake_case = 1 - (matter_density + radiation_density + dark_energy)
__snake_case = (
radiation_density * (redshift + 1) ** 4
+ matter_density * (redshift + 1) ** 3
+ curvature * (redshift + 1) ** 2
+ dark_energy
)
__snake_case = hubble_constant * e_a ** (1 / 2)
return hubble
if __name__ == "__main__":
import doctest
# run doctest
doctest.testmod()
# demo LCDM approximation
a : List[Any] = 0.3
print(
hubble_parameter(
hubble_constant=68.3,
radiation_density=1e-4,
matter_density=matter_density,
dark_energy=1 - matter_density,
redshift=0,
)
)
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> bool:
return number & 1 == 0
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 | 1 |
'''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 : int = '''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 __UpperCAmelCase ( ) -> str:
__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 __UpperCAmelCase ( _UpperCAmelCase : Any=None ) -> List[Any]:
if subparsers is not None:
__snake_case = subparsers.add_parser("config" , description=_UpperCAmelCase )
else:
__snake_case = argparse.ArgumentParser("Accelerate config command" , description=_UpperCAmelCase )
parser.add_argument(
"--config_file" , default=_UpperCAmelCase , 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=_UpperCAmelCase )
return parser
def __UpperCAmelCase ( _UpperCAmelCase : List[Any] ) -> List[str]:
__snake_case = get_user_input()
if args.config_file is not None:
__snake_case = args.config_file
else:
if not os.path.isdir(_UpperCAmelCase ):
os.makedirs(_UpperCAmelCase )
__snake_case = default_yaml_config_file
if config_file.endswith(".json" ):
config.to_json_file(_UpperCAmelCase )
else:
config.to_yaml_file(_UpperCAmelCase )
print(F'''accelerate configuration saved at {config_file}''' )
def __UpperCAmelCase ( ) -> Any:
__snake_case = config_command_parser()
__snake_case = parser.parse_args()
config_command(_UpperCAmelCase )
if __name__ == "__main__":
main()
| 69 |
'''simple docstring'''
import argparse
from pathlib import Path
import torch
from transformers import OPTConfig, OPTModel
from transformers.utils import logging
logging.set_verbosity_info()
a : List[str] = logging.get_logger(__name__)
def __UpperCAmelCase ( _UpperCAmelCase : Dict ) -> Union[str, Any]:
__snake_case = torch.load(_UpperCAmelCase , map_location="cpu" )
if "model" in sd.keys():
__snake_case = torch.load(_UpperCAmelCase , map_location="cpu" )["model"]
# pop unnecessary weights
__snake_case = [
"decoder.version",
"decoder.output_projection.weight",
]
for key in keys_to_delete:
if key in sd:
sd.pop(_UpperCAmelCase )
__snake_case = {
"decoder.project_in_dim.weight": "decoder.project_in.weight",
"decoder.project_out_dim.weight": "decoder.project_out.weight",
"decoder.layer_norm.weight": "decoder.final_layer_norm.weight",
"decoder.layer_norm.bias": "decoder.final_layer_norm.bias",
}
for old_key, new_key in keys_to_rename.items():
if old_key in sd:
__snake_case = sd.pop(_UpperCAmelCase )
__snake_case = list(sd.keys() )
for key in keys:
if ".qkv_proj." in key:
__snake_case = sd[key]
# We split QKV in separate Q,K,V
__snake_case = key.replace(".qkv_proj." , ".q_proj." )
__snake_case = key.replace(".qkv_proj." , ".k_proj." )
__snake_case = key.replace(".qkv_proj." , ".v_proj." )
__snake_case = value.shape[0]
assert depth % 3 == 0
# `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming:
# https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97
__snake_case , __snake_case , __snake_case = torch.split(_UpperCAmelCase , depth // 3 , dim=0 )
__snake_case = q
__snake_case = k
__snake_case = v
del sd[key]
return sd
@torch.no_grad()
def __UpperCAmelCase ( _UpperCAmelCase : List[str] , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : int=None ) -> Any:
__snake_case = load_checkpoint(_UpperCAmelCase )
if config is not None:
__snake_case = OPTConfig.from_pretrained(_UpperCAmelCase )
else:
__snake_case = OPTConfig()
__snake_case = OPTModel(_UpperCAmelCase ).half().eval()
model.load_state_dict(_UpperCAmelCase )
# Check results
Path(_UpperCAmelCase ).mkdir(exist_ok=_UpperCAmelCase )
model.save_pretrained(_UpperCAmelCase )
if __name__ == "__main__":
a : int = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--fairseq_path''',
type=str,
help=(
'''path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:'''
''' https://huggingface.co/models?other=opt_metasq'''
),
)
parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
parser.add_argument('''--hf_config''', default=None, type=str, help='''Define HF config.''')
a : Optional[int] = parser.parse_args()
convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
| 69 | 1 |
'''simple docstring'''
import os
from shutil import copyfile
from typing import List, Optional, Tuple
from tokenizers import processors
from ...tokenization_utils import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging
if is_sentencepiece_available():
from .tokenization_mbart import MBartTokenizer
else:
a : Dict = None
a : Optional[int] = logging.get_logger(__name__)
a : Optional[Any] = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''}
a : Optional[int] = {
'''vocab_file''': {
'''facebook/mbart-large-en-ro''': (
'''https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model'''
),
'''facebook/mbart-large-cc25''': (
'''https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model'''
),
},
'''tokenizer_file''': {
'''facebook/mbart-large-en-ro''': '''https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json''',
'''facebook/mbart-large-cc25''': '''https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json''',
},
}
a : Optional[int] = {
'''facebook/mbart-large-en-ro''': 1_024,
'''facebook/mbart-large-cc25''': 1_024,
}
# fmt: off
a : Union[str, Any] = ['''ar_AR''', '''cs_CZ''', '''de_DE''', '''en_XX''', '''es_XX''', '''et_EE''', '''fi_FI''', '''fr_XX''', '''gu_IN''', '''hi_IN''', '''it_IT''', '''ja_XX''', '''kk_KZ''', '''ko_KR''', '''lt_LT''', '''lv_LV''', '''my_MM''', '''ne_NP''', '''nl_XX''', '''ro_RO''', '''ru_RU''', '''si_LK''', '''tr_TR''', '''vi_VN''', '''zh_CN''']
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES
__SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP
__SCREAMING_SNAKE_CASE = ["""input_ids""", """attention_mask"""]
__SCREAMING_SNAKE_CASE = MBartTokenizer
__SCREAMING_SNAKE_CASE = []
__SCREAMING_SNAKE_CASE = []
def __init__( self : List[str] , a_ : Optional[int]=None , a_ : Dict=None , a_ : Optional[int]="<s>" , a_ : int="</s>" , a_ : Dict="</s>" , a_ : Any="<s>" , a_ : Any="<unk>" , a_ : Dict="<pad>" , a_ : Union[str, Any]="<mask>" , a_ : Optional[int]=None , a_ : Union[str, Any]=None , a_ : Dict=None , **a_ : Tuple , ):
"""simple docstring"""
__snake_case = AddedToken(a_ , lstrip=a_ , rstrip=a_ ) if isinstance(a_ , a_ ) else mask_token
super().__init__(
vocab_file=a_ , tokenizer_file=a_ , bos_token=a_ , eos_token=a_ , sep_token=a_ , cls_token=a_ , unk_token=a_ , pad_token=a_ , mask_token=a_ , src_lang=a_ , tgt_lang=a_ , additional_special_tokens=a_ , **a_ , )
__snake_case = vocab_file
__snake_case = False if not self.vocab_file else True
__snake_case = FAIRSEQ_LANGUAGE_CODES.copy()
if additional_special_tokens is not None:
# Only add those special tokens if they are not already there.
_additional_special_tokens.extend(
[t for t in additional_special_tokens if t not in _additional_special_tokens] )
self.add_special_tokens({"additional_special_tokens": _additional_special_tokens} )
__snake_case = {
lang_code: self.convert_tokens_to_ids(a_ ) for lang_code in FAIRSEQ_LANGUAGE_CODES
}
__snake_case = src_lang if src_lang is not None else "en_XX"
__snake_case = self.convert_tokens_to_ids(self._src_lang )
__snake_case = tgt_lang
self.set_src_lang_special_tokens(self._src_lang )
@property
def A ( self : Dict ):
"""simple docstring"""
return self._src_lang
@src_lang.setter
def A ( self : str , a_ : str ):
"""simple docstring"""
__snake_case = new_src_lang
self.set_src_lang_special_tokens(self._src_lang )
def A ( self : Any , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
if token_ids_a is None:
return self.prefix_tokens + token_ids_a + self.suffix_tokens
# We don't expect to process pairs, but leave the pair logic for API consistency
return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens
def A ( self : Union[str, Any] , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
__snake_case = [self.sep_token_id]
__snake_case = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
def A ( self : int , a_ : Optional[int] , a_ : str , a_ : Optional[str] , a_ : Optional[str] , **a_ : int ):
"""simple docstring"""
if src_lang is None or tgt_lang is None:
raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" )
__snake_case = src_lang
__snake_case = self(a_ , add_special_tokens=a_ , return_tensors=a_ , **a_ )
__snake_case = self.convert_tokens_to_ids(a_ )
__snake_case = tgt_lang_id
return inputs
def A ( self : Any , a_ : List[str] , a_ : str = "en_XX" , a_ : Optional[List[str]] = None , a_ : str = "ro_RO" , **a_ : Optional[Any] , ):
"""simple docstring"""
__snake_case = src_lang
__snake_case = tgt_lang
return super().prepare_seqaseq_batch(a_ , a_ , **a_ )
def A ( self : str ):
"""simple docstring"""
return self.set_src_lang_special_tokens(self.src_lang )
def A ( self : Dict ):
"""simple docstring"""
return self.set_tgt_lang_special_tokens(self.tgt_lang )
def A ( self : int , a_ : int ):
"""simple docstring"""
__snake_case = self.convert_tokens_to_ids(a_ )
__snake_case = []
__snake_case = [self.eos_token_id, self.cur_lang_code]
__snake_case = self.convert_ids_to_tokens(self.prefix_tokens )
__snake_case = self.convert_ids_to_tokens(self.suffix_tokens )
__snake_case = processors.TemplateProcessing(
single=prefix_tokens_str + ["$A"] + suffix_tokens_str , pair=prefix_tokens_str + ["$A", "$B"] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , )
def A ( self : Dict , a_ : str ):
"""simple docstring"""
__snake_case = self.convert_tokens_to_ids(a_ )
__snake_case = []
__snake_case = [self.eos_token_id, self.cur_lang_code]
__snake_case = self.convert_ids_to_tokens(self.prefix_tokens )
__snake_case = self.convert_ids_to_tokens(self.suffix_tokens )
__snake_case = processors.TemplateProcessing(
single=prefix_tokens_str + ["$A"] + suffix_tokens_str , pair=prefix_tokens_str + ["$A", "$B"] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , )
def A ( self : List[str] , a_ : str , a_ : Optional[str] = None ):
"""simple docstring"""
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(a_ ):
logger.error(f'''Vocabulary path ({save_directory}) should be a directory.''' )
return
__snake_case = 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_ ):
copyfile(self.vocab_file , a_ )
return (out_vocab_file,)
| 69 |
'''simple docstring'''
from typing import List, Optional
from ...configuration_utils import PretrainedConfig
from ...utils import logging
a : List[str] = logging.get_logger(__name__)
a : Tuple = {
'''huggingface/autoformer-tourism-monthly''': '''https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json''',
}
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = """autoformer"""
__SCREAMING_SNAKE_CASE = {
"""hidden_size""": """d_model""",
"""num_attention_heads""": """encoder_attention_heads""",
"""num_hidden_layers""": """encoder_layers""",
}
def __init__( self : List[Any] , a_ : Optional[int] = None , a_ : Optional[int] = None , a_ : str = "student_t" , a_ : str = "nll" , a_ : int = 1 , a_ : List[int] = [1, 2, 3, 4, 5, 6, 7] , a_ : bool = True , a_ : int = 0 , a_ : int = 0 , a_ : int = 0 , a_ : int = 0 , a_ : Optional[List[int]] = None , a_ : Optional[List[int]] = None , a_ : int = 64 , a_ : int = 2 , a_ : int = 2 , a_ : int = 2 , a_ : int = 2 , a_ : int = 32 , a_ : int = 32 , a_ : str = "gelu" , a_ : float = 0.1 , a_ : float = 0.1 , a_ : float = 0.1 , a_ : float = 0.1 , a_ : float = 0.1 , a_ : int = 100 , a_ : float = 0.02 , a_ : bool = True , a_ : Union[str, Any]=True , a_ : int = 10 , a_ : int = 25 , a_ : int = 3 , **a_ : Tuple , ):
"""simple docstring"""
__snake_case = prediction_length
__snake_case = context_length if context_length is not None else prediction_length
__snake_case = distribution_output
__snake_case = loss
__snake_case = input_size
__snake_case = num_time_features
__snake_case = lags_sequence
__snake_case = scaling
__snake_case = num_dynamic_real_features
__snake_case = num_static_real_features
__snake_case = num_static_categorical_features
if cardinality is not None 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`" )
__snake_case = cardinality
else:
__snake_case = [0]
if embedding_dimension is not None 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`" )
__snake_case = embedding_dimension
else:
__snake_case = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality]
__snake_case = num_parallel_samples
# Transformer architecture configuration
__snake_case = input_size * len(self.lags_sequence ) + self._number_of_features
__snake_case = d_model
__snake_case = encoder_attention_heads
__snake_case = decoder_attention_heads
__snake_case = encoder_ffn_dim
__snake_case = decoder_ffn_dim
__snake_case = encoder_layers
__snake_case = decoder_layers
__snake_case = dropout
__snake_case = attention_dropout
__snake_case = activation_dropout
__snake_case = encoder_layerdrop
__snake_case = decoder_layerdrop
__snake_case = activation_function
__snake_case = init_std
__snake_case = use_cache
# Autoformer
__snake_case = label_length
__snake_case = moving_average
__snake_case = autocorrelation_factor
super().__init__(is_encoder_decoder=a_ , **a_ )
@property
def A ( self : Optional[int] ):
"""simple docstring"""
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
)
| 69 | 1 |
'''simple docstring'''
import inspect
import unittest
from transformers import SegformerConfig, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
MODEL_MAPPING,
SegformerForImageClassification,
SegformerForSemanticSegmentation,
SegformerModel,
)
from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import SegformerImageProcessor
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = self.config_class(**self.inputs_dict )
self.parent.assertTrue(hasattr(a_ , "hidden_sizes" ) )
self.parent.assertTrue(hasattr(a_ , "num_attention_heads" ) )
self.parent.assertTrue(hasattr(a_ , "num_encoder_blocks" ) )
class SCREAMING_SNAKE_CASE__ :
def __init__( self : List[Any] , a_ : Any , a_ : Tuple=13 , a_ : Optional[Any]=64 , a_ : str=3 , a_ : Any=4 , a_ : List[str]=[2, 2, 2, 2] , a_ : Optional[int]=[8, 4, 2, 1] , a_ : List[str]=[16, 32, 64, 128] , a_ : Union[str, Any]=[1, 4, 8, 16] , a_ : Dict=[1, 2, 4, 8] , a_ : Tuple=True , a_ : Optional[int]=True , a_ : int="gelu" , a_ : Optional[Any]=0.1 , a_ : Optional[int]=0.1 , a_ : int=0.02 , a_ : Optional[int]=3 , a_ : Any=None , ):
"""simple docstring"""
__snake_case = parent
__snake_case = batch_size
__snake_case = image_size
__snake_case = num_channels
__snake_case = num_encoder_blocks
__snake_case = sr_ratios
__snake_case = depths
__snake_case = hidden_sizes
__snake_case = downsampling_rates
__snake_case = num_attention_heads
__snake_case = is_training
__snake_case = use_labels
__snake_case = hidden_act
__snake_case = hidden_dropout_prob
__snake_case = attention_probs_dropout_prob
__snake_case = initializer_range
__snake_case = num_labels
__snake_case = scope
def A ( self : int ):
"""simple docstring"""
__snake_case = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
__snake_case = None
if self.use_labels:
__snake_case = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels )
__snake_case = self.get_config()
return config, pixel_values, labels
def A ( self : Union[str, Any] ):
"""simple docstring"""
return SegformerConfig(
image_size=self.image_size , num_channels=self.num_channels , num_encoder_blocks=self.num_encoder_blocks , depths=self.depths , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , )
def A ( self : List[Any] , a_ : int , a_ : List[str] , a_ : Dict ):
"""simple docstring"""
__snake_case = SegformerModel(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ )
__snake_case = __snake_case = self.image_size // (self.downsampling_rates[-1] * 2)
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width) )
def A ( self : int , a_ : List[Any] , a_ : Dict , a_ : Optional[Any] ):
"""simple docstring"""
__snake_case = self.num_labels
__snake_case = SegformerForSemanticSegmentation(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ )
self.parent.assertEqual(
result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) )
__snake_case = model(a_ , labels=a_ )
self.parent.assertEqual(
result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) )
self.parent.assertGreater(result.loss , 0.0 )
def A ( self : Optional[int] , a_ : str , a_ : Dict , a_ : str ):
"""simple docstring"""
__snake_case = 1
__snake_case = SegformerForSemanticSegmentation(config=a_ )
model.to(a_ )
model.eval()
__snake_case = torch.randint(0 , 1 , (self.batch_size, self.image_size, self.image_size) ).to(a_ )
__snake_case = model(a_ , labels=a_ )
self.parent.assertGreater(result.loss , 0.0 )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = self.prepare_config_and_inputs()
__snake_case , __snake_case , __snake_case = config_and_inputs
__snake_case = {"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = (
(
SegformerModel,
SegformerForSemanticSegmentation,
SegformerForImageClassification,
)
if is_torch_available()
else ()
)
__SCREAMING_SNAKE_CASE = (
{
"""feature-extraction""": SegformerModel,
"""image-classification""": SegformerForImageClassification,
"""image-segmentation""": SegformerForSemanticSegmentation,
}
if is_torch_available()
else {}
)
__SCREAMING_SNAKE_CASE = True
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = False
def A ( self : Any ):
"""simple docstring"""
__snake_case = SegformerModelTester(self )
__snake_case = SegformerConfigTester(self , config_class=a_ )
def A ( self : Any ):
"""simple docstring"""
self.config_tester.run_common_tests()
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*a_ )
def A ( self : str ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_binary_image_segmentation(*a_ )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_segmentation(*a_ )
@unittest.skip("SegFormer does not use inputs_embeds" )
def A ( self : Tuple ):
"""simple docstring"""
pass
@unittest.skip("SegFormer does not have get_input_embeddings method and get_output_embeddings methods" )
def A ( self : Optional[Any] ):
"""simple docstring"""
pass
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__snake_case = model_class(a_ )
__snake_case = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__snake_case = [*signature.parameters.keys()]
__snake_case = ["pixel_values"]
self.assertListEqual(arg_names[:1] , a_ )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = True
for model_class in self.all_model_classes:
__snake_case = True
__snake_case = False
__snake_case = True
__snake_case = model_class(a_ )
model.to(a_ )
model.eval()
with torch.no_grad():
__snake_case = model(**self._prepare_for_class(a_ , a_ ) )
__snake_case = outputs.attentions
__snake_case = sum(self.model_tester.depths )
self.assertEqual(len(a_ ) , a_ )
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
__snake_case = True
__snake_case = model_class(a_ )
model.to(a_ )
model.eval()
with torch.no_grad():
__snake_case = model(**self._prepare_for_class(a_ , a_ ) )
__snake_case = outputs.attentions
self.assertEqual(len(a_ ) , a_ )
# verify the first attentions (first block, first layer)
__snake_case = (self.model_tester.image_size // 4) ** 2
__snake_case = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
self.assertListEqual(
list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , )
# verify the last attentions (last block, last layer)
__snake_case = (self.model_tester.image_size // 32) ** 2
__snake_case = (self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2
self.assertListEqual(
list(attentions[-1].shape[-3:] ) , [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len] , )
__snake_case = len(a_ )
# Check attention is always last and order is fine
__snake_case = True
__snake_case = True
__snake_case = model_class(a_ )
model.to(a_ )
model.eval()
with torch.no_grad():
__snake_case = model(**self._prepare_for_class(a_ , a_ ) )
self.assertEqual(out_len + 1 , len(a_ ) )
__snake_case = outputs.attentions
self.assertEqual(len(a_ ) , a_ )
# verify the first attentions (first block, first layer)
__snake_case = (self.model_tester.image_size // 4) ** 2
__snake_case = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
self.assertListEqual(
list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , )
def A ( self : int ):
"""simple docstring"""
def check_hidden_states_output(a_ : List[Any] , a_ : List[Any] , a_ : Tuple ):
__snake_case = model_class(a_ )
model.to(a_ )
model.eval()
with torch.no_grad():
__snake_case = model(**self._prepare_for_class(a_ , a_ ) )
__snake_case = outputs.hidden_states
__snake_case = self.model_tester.num_encoder_blocks
self.assertEqual(len(a_ ) , a_ )
# verify the first hidden states (first block)
self.assertListEqual(
list(hidden_states[0].shape[-3:] ) , [
self.model_tester.hidden_sizes[0],
self.model_tester.image_size // 4,
self.model_tester.image_size // 4,
] , )
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__snake_case = True
check_hidden_states_output(a_ , a_ , a_ )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
__snake_case = True
check_hidden_states_output(a_ , a_ , a_ )
def A ( self : Tuple ):
"""simple docstring"""
if not self.model_tester.is_training:
return
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = True
for model_class in self.all_model_classes:
if model_class in get_values(a_ ):
continue
__snake_case = model_class(a_ )
model.to(a_ )
model.train()
__snake_case = self._prepare_for_class(a_ , a_ , return_labels=a_ )
__snake_case = model(**a_ ).loss
loss.backward()
@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." )
def A ( self : int ):
"""simple docstring"""
pass
@slow
def A ( self : List[str] ):
"""simple docstring"""
for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__snake_case = SegformerModel.from_pretrained(a_ )
self.assertIsNotNone(a_ )
def __UpperCAmelCase ( ) -> List[Any]:
__snake_case = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_torch
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
@slow
def A ( self : Dict ):
"""simple docstring"""
__snake_case = SegformerImageProcessor(
image_scale=(512, 512) , keep_ratio=a_ , align=a_ , do_random_crop=a_ )
__snake_case = SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512" ).to(
a_ )
__snake_case = prepare_img()
__snake_case = image_processor(images=a_ , return_tensors="pt" )
__snake_case = encoded_inputs.pixel_values.to(a_ )
with torch.no_grad():
__snake_case = model(a_ )
__snake_case = torch.Size((1, model.config.num_labels, 128, 128) )
self.assertEqual(outputs.logits.shape , a_ )
__snake_case = torch.tensor(
[
[[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]],
[[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]],
[[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]],
] ).to(a_ )
self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , a_ , atol=1e-4 ) )
@slow
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = SegformerImageProcessor(
image_scale=(512, 512) , keep_ratio=a_ , align=a_ , do_random_crop=a_ )
__snake_case = SegformerForSemanticSegmentation.from_pretrained(
"nvidia/segformer-b1-finetuned-cityscapes-1024-1024" ).to(a_ )
__snake_case = prepare_img()
__snake_case = image_processor(images=a_ , return_tensors="pt" )
__snake_case = encoded_inputs.pixel_values.to(a_ )
with torch.no_grad():
__snake_case = model(a_ )
__snake_case = torch.Size((1, model.config.num_labels, 128, 128) )
self.assertEqual(outputs.logits.shape , a_ )
__snake_case = torch.tensor(
[
[[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]],
[[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]],
[[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]],
] ).to(a_ )
self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , a_ , atol=1e-1 ) )
@slow
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = SegformerImageProcessor(
image_scale=(512, 512) , keep_ratio=a_ , align=a_ , do_random_crop=a_ )
__snake_case = SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512" ).to(
a_ )
__snake_case = prepare_img()
__snake_case = image_processor(images=a_ , return_tensors="pt" )
__snake_case = encoded_inputs.pixel_values.to(a_ )
with torch.no_grad():
__snake_case = model(a_ )
__snake_case = outputs.logits.detach().cpu()
__snake_case = image_processor.post_process_semantic_segmentation(outputs=a_ , target_sizes=[(500, 300)] )
__snake_case = torch.Size((500, 300) )
self.assertEqual(segmentation[0].shape , a_ )
__snake_case = image_processor.post_process_semantic_segmentation(outputs=a_ )
__snake_case = torch.Size((128, 128) )
self.assertEqual(segmentation[0].shape , a_ )
| 69 |
'''simple docstring'''
import unittest
from transformers import GPTSwaTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
a : List[Any] = get_tests_dir('''fixtures/test_sentencepiece_with_bytefallback.model''')
@require_sentencepiece
@require_tokenizers
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = GPTSwaTokenizer
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = True
__SCREAMING_SNAKE_CASE = False
def A ( self : int ):
"""simple docstring"""
super().setUp()
# We have a SentencePiece fixture for testing
__snake_case = GPTSwaTokenizer(a_ , eos_token="<unk>" , bos_token="<unk>" , pad_token="<unk>" )
tokenizer.save_pretrained(self.tmpdirname )
def A ( self : str , a_ : List[Any] ):
"""simple docstring"""
__snake_case = "This is a test"
__snake_case = "This is a test"
return input_text, output_text
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = "<s>"
__snake_case = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , "<unk>" )
self.assertEqual(vocab_keys[1] , "<s>" )
self.assertEqual(vocab_keys[-1] , "j" )
self.assertEqual(len(a_ ) , 2_000 )
def A ( self : Optional[int] ):
"""simple docstring"""
self.assertEqual(self.get_tokenizer().vocab_size , 2_000 )
def A ( self : Dict ):
"""simple docstring"""
__snake_case = GPTSwaTokenizer(a_ )
__snake_case = tokenizer.tokenize("This is a test" )
self.assertListEqual(a_ , ["▁This", "▁is", "▁a", "▁t", "est"] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , [465, 287, 265, 631, 842] )
__snake_case = tokenizer.tokenize("I was born in 92000, and this is falsé." )
# fmt: off
self.assertListEqual(
a_ , ["▁I", "▁was", "▁bor", "n", "▁in", "▁", "<0x39>", "2", "0", "0", "0", ",", "▁and", "▁this", "▁is", "▁f", "al", "s", "<0xC3>", "<0xA9>", "."] , )
# fmt: on
__snake_case = tokenizer.convert_tokens_to_ids(a_ )
self.assertListEqual(
a_ , [262, 272, 1_525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260] , )
__snake_case = tokenizer.convert_ids_to_tokens(a_ )
# fmt: off
self.assertListEqual(
a_ , ["▁I", "▁was", "▁bor", "n", "▁in", "▁", "<0x39>", "2", "0", "0", "0", ",", "▁and", "▁this", "▁is", "▁f", "al", "s", "<0xC3>", "<0xA9>", "."] )
# fmt: on
def A ( self : List[str] ):
"""simple docstring"""
__snake_case = GPTSwaTokenizer(a_ )
__snake_case = ["This is a test", "I was born in 92000, and this is falsé."]
__snake_case = [
[465, 287, 265, 631, 842],
[262, 272, 1_525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260],
]
# Test that encode_fast returns the same as tokenize + convert_tokens_to_ids
for text, expected_ids in zip(a_ , a_ ):
self.assertListEqual(tokenizer.encode_fast(a_ ) , a_ )
# Test that decode_fast returns the input text
for text, token_ids in zip(a_ , a_ ):
self.assertEqual(tokenizer.decode_fast(a_ ) , a_ )
@slow
def A ( self : Any ):
"""simple docstring"""
__snake_case = [
"<|python|>def fibonacci(n)\n if n < 0:\n print('Incorrect input')",
"Hey there, how are you doing this fine day?",
"This is a text with a trailing spaces followed by a dot .",
"Häj sväjs lillebrör! =)",
"Det är inget fel på Mr. Cool",
]
# fmt: off
__snake_case = {"input_ids": [[63_423, 5, 6_811, 14_954, 282, 816, 3_821, 63_466, 63_425, 63_462, 18, 63_978, 678, 301, 1_320, 63_423, 63_455, 63_458, 18, 63_982, 4_246, 3_940, 1_901, 47_789, 5_547, 18_994], [19_630, 1_100, 63_446, 1_342, 633, 544, 4_488, 593, 5_102, 2_416, 63_495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_652, 428, 268, 1_936, 515, 268, 58_593, 22_413, 9_106, 546, 268, 33_213, 63_979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [55_130, 63_450, 924, 63_449, 2_249, 4_062, 1_558, 318, 63_504, 21_498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2_827, 2_559, 332, 6_575, 63_443, 26_801, 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]], "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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [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], [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]]}
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=a_ , model_name="AI-Sweden/gpt-sw3-126m" , sequences=a_ , )
| 69 | 1 |
'''simple docstring'''
import argparse
from collections import defaultdict
def __UpperCAmelCase ( _UpperCAmelCase : str , _UpperCAmelCase : Tuple , _UpperCAmelCase : List[str] , _UpperCAmelCase : str , _UpperCAmelCase : Any ) -> List[str]:
__snake_case = F'''{file}_{class_name}_{test_name}'''
done_test[_id] += 1
with open(_UpperCAmelCase , "r" ) as f:
__snake_case = f.readlines()
__snake_case = F'''class {class_name}('''
__snake_case = F'''{4 * " "}def {test_name}('''
__snake_case = F'''{8 * " "}{correct_line.split()[0]}'''
__snake_case = F'''{16 * " "}{correct_line.split()[0]}'''
__snake_case = False
__snake_case = False
__snake_case = False
__snake_case = False
__snake_case = 0
__snake_case = 0
__snake_case = []
for line in lines:
if line.startswith(_UpperCAmelCase ):
__snake_case = True
elif in_class and line.startswith(_UpperCAmelCase ):
__snake_case = True
elif in_class and in_func and (line.startswith(_UpperCAmelCase ) or line.startswith(_UpperCAmelCase )):
__snake_case = len(line.split(correct_line.split()[0] )[0] )
count += 1
if count == done_test[_id]:
__snake_case = True
if in_class and in_func and in_line:
if ")" not in line:
continue
else:
__snake_case = True
if in_class and in_func and in_line and insert_line:
new_lines.append(F'''{spaces * " "}{correct_line}''' )
__snake_case = __snake_case = __snake_case = __snake_case = False
else:
new_lines.append(_UpperCAmelCase )
with open(_UpperCAmelCase , "w" ) as f:
for line in new_lines:
f.write(_UpperCAmelCase )
def __UpperCAmelCase ( _UpperCAmelCase : Dict , _UpperCAmelCase : Optional[Any]=None ) -> Tuple:
if fail is not None:
with open(_UpperCAmelCase , "r" ) as f:
__snake_case = {l.strip() for l in f.readlines()}
else:
__snake_case = None
with open(_UpperCAmelCase , "r" ) as f:
__snake_case = f.readlines()
__snake_case = defaultdict(_UpperCAmelCase )
for line in correct_lines:
__snake_case , __snake_case , __snake_case , __snake_case = line.split(";" )
if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures:
overwrite_file(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
if __name__ == "__main__":
a : str = argparse.ArgumentParser()
parser.add_argument('''--correct_filename''', help='''filename of tests with expected result''')
parser.add_argument('''--fail_filename''', help='''filename of test failures''', type=str, default=None)
a : List[Any] = parser.parse_args()
main(args.correct_filename, args.fail_filename)
| 69 |
'''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
a : Tuple = get_tests_dir('''fixtures''')
a : Dict = get_tests_dir('''fixtures/dummy_feature_extractor_config.json''')
a : int = get_tests_dir('''fixtures/dummy-config.json''')
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = 0
def A ( self : str ):
"""simple docstring"""
__snake_case = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h" )
self.assertIsInstance(a_ , a_ )
def A ( self : str ):
"""simple docstring"""
__snake_case = AutoFeatureExtractor.from_pretrained(a_ )
self.assertIsInstance(a_ , a_ )
def A ( self : str ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmpdirname:
__snake_case = WavaVecaConfig()
# remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
__snake_case = AutoFeatureExtractor.from_pretrained(a_ ).to_dict()
config_dict.pop("feature_extractor_type" )
__snake_case = WavaVecaFeatureExtractor(**a_ )
# save in new folder
model_config.save_pretrained(a_ )
config.save_pretrained(a_ )
__snake_case = AutoFeatureExtractor.from_pretrained(a_ )
# make sure private variable is not incorrectly saved
__snake_case = json.loads(config.to_json_string() )
self.assertTrue("_processor_class" not in dict_as_saved )
self.assertIsInstance(a_ , a_ )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = AutoFeatureExtractor.from_pretrained(a_ )
self.assertIsInstance(a_ , a_ )
def A ( self : Optional[Any] ):
"""simple docstring"""
with self.assertRaisesRegex(
a_ , "bert-base is not a local folder and is not a valid model identifier" ):
__snake_case = AutoFeatureExtractor.from_pretrained("bert-base" )
def A ( self : Dict ):
"""simple docstring"""
with self.assertRaisesRegex(
a_ , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ):
__snake_case = AutoFeatureExtractor.from_pretrained(a_ , revision="aaaaaa" )
def A ( self : Tuple ):
"""simple docstring"""
with self.assertRaisesRegex(
a_ , "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json." , ):
__snake_case = AutoFeatureExtractor.from_pretrained("hf-internal-testing/config-no-model" )
def A ( self : Tuple ):
"""simple docstring"""
with self.assertRaises(a_ ):
__snake_case = 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_ ):
__snake_case = AutoFeatureExtractor.from_pretrained(
"hf-internal-testing/test_dynamic_feature_extractor" , trust_remote_code=a_ )
__snake_case = 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_ )
__snake_case = AutoFeatureExtractor.from_pretrained(a_ , trust_remote_code=a_ )
self.assertEqual(reloaded_feature_extractor.__class__.__name__ , "NewFeatureExtractor" )
def A ( self : int ):
"""simple docstring"""
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
__snake_case = CustomFeatureExtractor.from_pretrained(a_ )
with tempfile.TemporaryDirectory() as tmp_dir:
feature_extractor.save_pretrained(a_ )
__snake_case = 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 A ( self : Dict ):
"""simple docstring"""
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = True
try:
AutoConfig.register("custom" , a_ )
AutoFeatureExtractor.register(a_ , a_ )
# If remote code is not set, the default is to use local
__snake_case = 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.
__snake_case = 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
__snake_case = 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]
| 69 | 1 |
'''simple docstring'''
import unittest
from transformers import DebertaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
DebertaForMaskedLM,
DebertaForQuestionAnswering,
DebertaForSequenceClassification,
DebertaForTokenClassification,
DebertaModel,
)
from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def __init__( self : Union[str, Any] , a_ : Optional[Any] , a_ : Dict=13 , a_ : List[Any]=7 , a_ : int=True , a_ : List[str]=True , a_ : List[Any]=True , a_ : Union[str, Any]=True , a_ : Tuple=99 , a_ : List[Any]=32 , a_ : str=5 , a_ : Optional[int]=4 , a_ : int=37 , a_ : Optional[Any]="gelu" , a_ : Union[str, Any]=0.1 , a_ : List[Any]=0.1 , a_ : Dict=512 , a_ : Optional[int]=16 , a_ : Dict=2 , a_ : str=0.02 , a_ : List[Any]=False , a_ : Optional[Any]=True , a_ : Optional[Any]="None" , a_ : List[Any]=3 , a_ : Tuple=4 , a_ : int=None , ):
"""simple docstring"""
__snake_case = parent
__snake_case = batch_size
__snake_case = seq_length
__snake_case = is_training
__snake_case = use_input_mask
__snake_case = use_token_type_ids
__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_act
__snake_case = hidden_dropout_prob
__snake_case = attention_probs_dropout_prob
__snake_case = max_position_embeddings
__snake_case = type_vocab_size
__snake_case = type_sequence_label_size
__snake_case = initializer_range
__snake_case = num_labels
__snake_case = num_choices
__snake_case = relative_attention
__snake_case = position_biased_input
__snake_case = pos_att_type
__snake_case = scope
def A ( self : List[str] ):
"""simple docstring"""
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__snake_case = None
if self.use_input_mask:
__snake_case = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 )
__snake_case = None
if self.use_token_type_ids:
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
__snake_case = None
__snake_case = None
__snake_case = None
if self.use_labels:
__snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__snake_case = ids_tensor([self.batch_size] , self.num_choices )
__snake_case = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def A ( self : str ):
"""simple docstring"""
return DebertaConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , )
def A ( self : int ):
"""simple docstring"""
__snake_case = self.get_config()
__snake_case = 300
return config
def A ( self : Union[str, Any] , a_ : Any ):
"""simple docstring"""
self.parent.assertListEqual(list(result.loss.size() ) , [] )
def A ( self : Union[str, Any] , a_ : Optional[int] , a_ : Optional[Any] , a_ : Tuple , a_ : List[Any] , a_ : Optional[Any] , a_ : Tuple , a_ : Optional[Any] ):
"""simple docstring"""
__snake_case = DebertaModel(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , token_type_ids=a_ )[0]
__snake_case = model(a_ , token_type_ids=a_ )[0]
__snake_case = model(a_ )[0]
self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] )
def A ( self : Optional[int] , a_ : List[Any] , a_ : Tuple , a_ : Tuple , a_ : List[Any] , a_ : Optional[int] , a_ : Any , a_ : Tuple ):
"""simple docstring"""
__snake_case = DebertaForMaskedLM(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def A ( self : List[Any] , a_ : List[str] , a_ : int , a_ : Optional[Any] , a_ : List[Any] , a_ : Optional[Any] , a_ : List[Any] , a_ : Any ):
"""simple docstring"""
__snake_case = self.num_labels
__snake_case = DebertaForSequenceClassification(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ )
self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] )
self.check_loss_output(a_ )
def A ( self : Optional[Any] , a_ : str , a_ : Tuple , a_ : Any , a_ : Union[str, Any] , a_ : Optional[Any] , a_ : str , a_ : List[Any] ):
"""simple docstring"""
__snake_case = self.num_labels
__snake_case = DebertaForTokenClassification(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def A ( self : Union[str, Any] , a_ : str , a_ : List[str] , a_ : Tuple , a_ : str , a_ : str , a_ : List[Any] , a_ : Union[str, Any] ):
"""simple docstring"""
__snake_case = DebertaForQuestionAnswering(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(
a_ , attention_mask=a_ , token_type_ids=a_ , start_positions=a_ , end_positions=a_ , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def A ( self : Dict ):
"""simple docstring"""
__snake_case = self.prepare_config_and_inputs()
(
(
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) ,
) = config_and_inputs
__snake_case = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = (
(
DebertaModel,
DebertaForMaskedLM,
DebertaForSequenceClassification,
DebertaForTokenClassification,
DebertaForQuestionAnswering,
)
if is_torch_available()
else ()
)
__SCREAMING_SNAKE_CASE = (
{
"""feature-extraction""": DebertaModel,
"""fill-mask""": DebertaForMaskedLM,
"""question-answering""": DebertaForQuestionAnswering,
"""text-classification""": DebertaForSequenceClassification,
"""token-classification""": DebertaForTokenClassification,
"""zero-shot""": DebertaForSequenceClassification,
}
if is_torch_available()
else {}
)
__SCREAMING_SNAKE_CASE = True
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = False
def A ( self : List[str] ):
"""simple docstring"""
__snake_case = DebertaModelTester(self )
__snake_case = ConfigTester(self , config_class=a_ , hidden_size=37 )
def A ( self : Any ):
"""simple docstring"""
self.config_tester.run_common_tests()
def A ( self : Any ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_model(*a_ )
def A ( self : str ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_for_sequence_classification(*a_ )
def A ( self : str ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_for_masked_lm(*a_ )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_for_question_answering(*a_ )
def A ( self : str ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_for_token_classification(*a_ )
@slow
def A ( self : List[str] ):
"""simple docstring"""
for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__snake_case = DebertaModel.from_pretrained(a_ )
self.assertIsNotNone(a_ )
@require_torch
@require_sentencepiece
@require_tokenizers
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
@unittest.skip(reason="Model not available yet" )
def A ( self : Optional[Any] ):
"""simple docstring"""
pass
@slow
def A ( self : int ):
"""simple docstring"""
__snake_case = DebertaModel.from_pretrained("microsoft/deberta-base" )
__snake_case = torch.tensor([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] )
__snake_case = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
with torch.no_grad():
__snake_case = model(a_ , attention_mask=a_ )[0]
# compare the actual values for a slice.
__snake_case = torch.tensor(
[[[-0.5986, -0.8055, -0.8462], [1.4484, -0.9348, -0.8059], [0.3123, 0.0032, -1.4131]]] )
self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , a_ , atol=1e-4 ) , f'''{output[:, 1:4, 1:4]}''' )
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> list:
# bit count represents no. of bits in the gray code
if bit_count < 0:
raise ValueError("The given input must be positive" )
# get the generated string sequence
__snake_case = gray_code_sequence_string(_UpperCAmelCase )
#
# convert them to integers
for i in range(len(_UpperCAmelCase ) ):
__snake_case = int(sequence[i] , 2 )
return sequence
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> list:
# The approach is a recursive one
# Base case achieved when either n = 0 or n=1
if bit_count == 0:
return ["0"]
if bit_count == 1:
return ["0", "1"]
__snake_case = 1 << bit_count # defines the length of the sequence
# 1<< n is equivalent to 2^n
# recursive answer will generate answer for n-1 bits
__snake_case = gray_code_sequence_string(bit_count - 1 )
__snake_case = []
# append 0 to first half of the smaller sequence generated
for i in range(seq_len // 2 ):
__snake_case = "0" + smaller_sequence[i]
sequence.append(_UpperCAmelCase )
# append 1 to second half ... start from the end of the list
for i in reversed(range(seq_len // 2 ) ):
__snake_case = "1" + smaller_sequence[i]
sequence.append(_UpperCAmelCase )
return sequence
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 | 1 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> list:
__snake_case = [0] * len(_UpperCAmelCase )
for i in range(1 , len(_UpperCAmelCase ) ):
# use last results for better performance - dynamic programming
__snake_case = prefix_result[i - 1]
while j > 0 and input_string[i] != input_string[j]:
__snake_case = prefix_result[j - 1]
if input_string[i] == input_string[j]:
j += 1
__snake_case = j
return prefix_result
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> int:
return max(prefix_function(_UpperCAmelCase ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : str , _UpperCAmelCase : str ) -> list:
__snake_case = len(_UpperCAmelCase )
__snake_case = []
for i in range(len(_UpperCAmelCase ) - pat_len + 1 ):
__snake_case = True
for j in range(_UpperCAmelCase ):
if s[i + j] != pattern[j]:
__snake_case = 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'''))
| 69 | 1 |
'''simple docstring'''
import argparse
import collections
import torch
from flax import traverse_util
from tax import checkpoints
from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration
from transformers.utils import logging
logging.set_verbosity_info()
def __UpperCAmelCase ( _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Any="attention" ) -> Optional[int]:
__snake_case = params[F'''{prefix}/layers_{i}/{layer_name}/key/kernel''']
__snake_case = params[F'''{prefix}/layers_{i}/{layer_name}/out/kernel''']
__snake_case = params[F'''{prefix}/layers_{i}/{layer_name}/query/kernel''']
__snake_case = params[F'''{prefix}/layers_{i}/{layer_name}/value/kernel''']
return k, o, q, v
def __UpperCAmelCase ( _UpperCAmelCase : List[str] , _UpperCAmelCase : Optional[int] , _UpperCAmelCase : Any , _UpperCAmelCase : List[str]=False ) -> Optional[int]:
if split_mlp_wi:
__snake_case = params[F'''{prefix}/layers_{i}/mlp/wi_0/kernel''']
__snake_case = params[F'''{prefix}/layers_{i}/mlp/wi_1/kernel''']
__snake_case = (wi_a, wi_a)
else:
__snake_case = params[F'''{prefix}/layers_{i}/mlp/wi/kernel''']
__snake_case = params[F'''{prefix}/layers_{i}/mlp/wo/kernel''']
return wi, wo
def __UpperCAmelCase ( _UpperCAmelCase : List[str] , _UpperCAmelCase : Dict , _UpperCAmelCase : Tuple , _UpperCAmelCase : Optional[int] ) -> int:
return params[F'''{prefix}/layers_{i}/{layer_name}/scale''']
def __UpperCAmelCase ( _UpperCAmelCase : dict , *, _UpperCAmelCase : int , _UpperCAmelCase : bool ) -> Optional[int]:
__snake_case = traverse_util.flatten_dict(variables["target"] )
__snake_case = {"/".join(_UpperCAmelCase ): v for k, v in old.items()}
# v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi
__snake_case = "encoder/layers_0/mlp/wi_0/kernel" in old
print("Split MLP:" , _UpperCAmelCase )
__snake_case = collections.OrderedDict()
# Shared embeddings.
__snake_case = old["token_embedder/embedding"]
# Encoder.
for i in range(_UpperCAmelCase ):
# Block i, layer 0 (Self Attention).
__snake_case = tax_layer_norm_lookup(_UpperCAmelCase , _UpperCAmelCase , "encoder" , "pre_attention_layer_norm" )
__snake_case , __snake_case , __snake_case , __snake_case = tax_attention_lookup(_UpperCAmelCase , _UpperCAmelCase , "encoder" , "attention" )
__snake_case = layer_norm
__snake_case = k.T
__snake_case = o.T
__snake_case = q.T
__snake_case = v.T
# Block i, layer 1 (MLP).
__snake_case = tax_layer_norm_lookup(_UpperCAmelCase , _UpperCAmelCase , "encoder" , "pre_mlp_layer_norm" )
__snake_case , __snake_case = tax_mlp_lookup(_UpperCAmelCase , _UpperCAmelCase , "encoder" , _UpperCAmelCase )
__snake_case = layer_norm
if split_mlp_wi:
__snake_case = wi[0].T
__snake_case = wi[1].T
else:
__snake_case = wi.T
__snake_case = wo.T
__snake_case = old[
"encoder/relpos_bias/rel_embedding"
].T
__snake_case = old["encoder/encoder_norm/scale"]
if not is_encoder_only:
# Decoder.
for i in range(_UpperCAmelCase ):
# Block i, layer 0 (Self Attention).
__snake_case = tax_layer_norm_lookup(_UpperCAmelCase , _UpperCAmelCase , "decoder" , "pre_self_attention_layer_norm" )
__snake_case , __snake_case , __snake_case , __snake_case = tax_attention_lookup(_UpperCAmelCase , _UpperCAmelCase , "decoder" , "self_attention" )
__snake_case = layer_norm
__snake_case = k.T
__snake_case = o.T
__snake_case = q.T
__snake_case = v.T
# Block i, layer 1 (Cross Attention).
__snake_case = tax_layer_norm_lookup(_UpperCAmelCase , _UpperCAmelCase , "decoder" , "pre_cross_attention_layer_norm" )
__snake_case , __snake_case , __snake_case , __snake_case = tax_attention_lookup(_UpperCAmelCase , _UpperCAmelCase , "decoder" , "encoder_decoder_attention" )
__snake_case = layer_norm
__snake_case = k.T
__snake_case = o.T
__snake_case = q.T
__snake_case = v.T
# Block i, layer 2 (MLP).
__snake_case = tax_layer_norm_lookup(_UpperCAmelCase , _UpperCAmelCase , "decoder" , "pre_mlp_layer_norm" )
__snake_case , __snake_case = tax_mlp_lookup(_UpperCAmelCase , _UpperCAmelCase , "decoder" , _UpperCAmelCase )
__snake_case = layer_norm
if split_mlp_wi:
__snake_case = wi[0].T
__snake_case = wi[1].T
else:
__snake_case = wi.T
__snake_case = wo.T
__snake_case = old["decoder/decoder_norm/scale"]
__snake_case = old[
"decoder/relpos_bias/rel_embedding"
].T
# LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead)
if "decoder/logits_dense/kernel" in old:
__snake_case = old["decoder/logits_dense/kernel"].T
return new
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : bool ) -> Optional[int]:
__snake_case = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] )
# Add what is missing.
if "encoder.embed_tokens.weight" not in state_dict:
__snake_case = state_dict["shared.weight"]
if not is_encoder_only:
if "decoder.embed_tokens.weight" not in state_dict:
__snake_case = state_dict["shared.weight"]
if "lm_head.weight" not in state_dict: # For old 1.0 models.
print("Using shared word embeddings as lm_head." )
__snake_case = state_dict["shared.weight"]
return state_dict
def __UpperCAmelCase ( _UpperCAmelCase : Dict , _UpperCAmelCase : Dict , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Any ) -> Dict:
__snake_case = checkpoints.load_tax_checkpoint(_UpperCAmelCase )
__snake_case = convert_tax_to_pytorch(_UpperCAmelCase , num_layers=config.num_layers , is_encoder_only=_UpperCAmelCase )
__snake_case = make_state_dict(_UpperCAmelCase , _UpperCAmelCase )
model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase )
def __UpperCAmelCase ( _UpperCAmelCase : str , _UpperCAmelCase : List[str] , _UpperCAmelCase : int , _UpperCAmelCase : bool = False ) -> Optional[Any]:
__snake_case = TaConfig.from_json_file(_UpperCAmelCase )
print(F'''Building PyTorch model from configuration: {config}''' )
# Non-v1.1 checkpoints could also use T5Model, but this works for all.
# The v1.0 checkpoints will simply have an LM head that is the word embeddings.
if is_encoder_only:
__snake_case = TaEncoderModel(_UpperCAmelCase )
else:
__snake_case = TaForConditionalGeneration(_UpperCAmelCase )
# Load weights from tf checkpoint
load_tax_weights_in_ta(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
# Save pytorch-model
print(F'''Save PyTorch model to {pytorch_dump_path}''' )
model.save_pretrained(_UpperCAmelCase )
# Verify that we can load the checkpoint.
model.from_pretrained(_UpperCAmelCase )
print("Done" )
if __name__ == "__main__":
a : Any = argparse.ArgumentParser(description='''Converts a native T5X checkpoint into a PyTorch checkpoint.''')
# Required parameters
parser.add_argument(
'''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path to the T5X checkpoint.'''
)
parser.add_argument(
'''--config_file''',
default=None,
type=str,
required=True,
help='''The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.''',
)
parser.add_argument(
'''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
)
parser.add_argument(
'''--is_encoder_only''', action='''store_true''', help='''Check if the model is encoder-decoder model''', default=False
)
a : Dict = parser.parse_args()
convert_tax_checkpoint_to_pytorch(
args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only
)
| 69 |
'''simple docstring'''
a : Dict = range(2, 20 + 1)
a : Optional[int] = [10**k for k in range(ks[-1] + 1)]
a : dict[int, dict[int, list[list[int]]]] = {}
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Dict , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[Any] ) -> int:
__snake_case = sum(a_i[j] for j in range(_UpperCAmelCase , len(_UpperCAmelCase ) ) )
__snake_case = sum(a_i[j] * base[j] for j in range(min(len(_UpperCAmelCase ) , _UpperCAmelCase ) ) )
__snake_case , __snake_case = 0, 0
__snake_case = n - i
__snake_case = memo.get(_UpperCAmelCase )
if sub_memo is not None:
__snake_case = sub_memo.get(_UpperCAmelCase )
if jumps is not None and len(_UpperCAmelCase ) > 0:
# find and make the largest jump without going over
__snake_case = -1
for _k in range(len(_UpperCAmelCase ) - 1 , -1 , -1 ):
if jumps[_k][2] <= k and jumps[_k][1] <= max_dn:
__snake_case = _k
break
if max_jump >= 0:
__snake_case , __snake_case , __snake_case = jumps[max_jump]
# since the difference between jumps is cached, add c
__snake_case = diff + c
for j in range(min(_UpperCAmelCase , len(_UpperCAmelCase ) ) ):
__snake_case , __snake_case = divmod(_UpperCAmelCase , 10 )
if new_c > 0:
add(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
else:
__snake_case = []
else:
__snake_case = {c: []}
__snake_case = sub_memo
if dn >= max_dn or c + diff >= base[k]:
return diff, dn
if k > ks[0]:
while True:
# keep doing smaller jumps
__snake_case , __snake_case = next_term(_UpperCAmelCase , k - 1 , i + dn , _UpperCAmelCase )
diff += _diff
dn += terms_jumped
if dn >= max_dn or c + diff >= base[k]:
break
else:
# would be too small a jump, just compute sequential terms instead
__snake_case , __snake_case = compute(_UpperCAmelCase , _UpperCAmelCase , i + dn , _UpperCAmelCase )
diff += _diff
dn += terms_jumped
__snake_case = sub_memo[c]
# keep jumps sorted by # of terms skipped
__snake_case = 0
while j < len(_UpperCAmelCase ):
if jumps[j][1] > dn:
break
j += 1
# cache the jump for this value digitsum(b) and c
sub_memo[c].insert(_UpperCAmelCase , (diff, dn, k) )
return (diff, dn)
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[int] ) -> Optional[int]:
if i >= n:
return 0, i
if k > len(_UpperCAmelCase ):
a_i.extend([0 for _ in range(k - len(_UpperCAmelCase ) )] )
# note: a_i -> b * 10^k + c
# ds_b -> digitsum(b)
# ds_c -> digitsum(c)
__snake_case = i
__snake_case , __snake_case , __snake_case = 0, 0, 0
for j in range(len(_UpperCAmelCase ) ):
if j >= k:
ds_b += a_i[j]
else:
ds_c += a_i[j]
while i < n:
i += 1
__snake_case = ds_c + ds_b
diff += addend
__snake_case = 0
for j in range(_UpperCAmelCase ):
__snake_case = a_i[j] + addend
__snake_case , __snake_case = divmod(_UpperCAmelCase , 10 )
ds_c += a_i[j]
if addend > 0:
break
if addend > 0:
add(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
return diff, i - start_i
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Tuple , _UpperCAmelCase : str ) -> Tuple:
for j in range(_UpperCAmelCase , len(_UpperCAmelCase ) ):
__snake_case = digits[j] + addend
if s >= 10:
__snake_case , __snake_case = divmod(_UpperCAmelCase , 10 )
__snake_case = addend // 10 + quotient
else:
__snake_case = s
__snake_case = addend // 10
if addend == 0:
break
while addend > 0:
__snake_case , __snake_case = divmod(_UpperCAmelCase , 10 )
digits.append(_UpperCAmelCase )
def __UpperCAmelCase ( _UpperCAmelCase : int = 10**15 ) -> int:
__snake_case = [1]
__snake_case = 1
__snake_case = 0
while True:
__snake_case , __snake_case = next_term(_UpperCAmelCase , 20 , i + dn , _UpperCAmelCase )
dn += terms_jumped
if dn == n - i:
break
__snake_case = 0
for j in range(len(_UpperCAmelCase ) ):
a_n += digits[j] * 10**j
return a_n
if __name__ == "__main__":
print(F'''{solution() = }''')
| 69 | 1 |
'''simple docstring'''
from numpy import exp, pi, sqrt
def __UpperCAmelCase ( _UpperCAmelCase : Tuple , _UpperCAmelCase : float = 0.0 , _UpperCAmelCase : float = 1.0 ) -> int:
return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : List[Any]=2_81_23 ) -> str:
__snake_case = [1] * (limit + 1)
for i in range(2 , int(limit**0.5 ) + 1 ):
sum_divs[i * i] += i
for k in range(i + 1 , limit // i + 1 ):
sum_divs[k * i] += k + i
__snake_case = set()
__snake_case = 0
for n in range(1 , limit + 1 ):
if sum_divs[n] > n:
abundants.add(_UpperCAmelCase )
if not any((n - a in abundants) for a in abundants ):
res += n
return res
if __name__ == "__main__":
print(solution())
| 69 | 1 |
'''simple docstring'''
import math
def __UpperCAmelCase ( _UpperCAmelCase : Optional[int] , _UpperCAmelCase : Optional[int] ) -> Tuple:
if 0 not in (x, y):
# We use the relation x^y = y*log10(x), where 10 is the base.
return y * math.logaa(_UpperCAmelCase )
else:
if x == 0: # 0 raised to any number is 0
return 0
elif y == 0:
return 1 # any number raised to 0 is 1
raise AssertionError("This should never happen" )
if __name__ == "__main__": # Main function
# Read two numbers from input and typecast them to int using map function.
# Here x is the base and y is the power.
a : Optional[Any] = '''Enter the base and the power separated by a comma: '''
a , a : Optional[int] = map(int, input(prompt).split(''','''))
a , a : Any = map(int, input(prompt).split(''','''))
# We find the log of each number, using the function res(), which takes two
# arguments.
a : Union[str, Any] = res(xa, ya)
a : Any = res(xa, ya)
# We check for the largest number
if resa > resa:
print('''Largest number is''', xa, '''^''', ya)
elif resa > resa:
print('''Largest number is''', xa, '''^''', ya)
else:
print('''Both are equal''')
| 69 |
'''simple docstring'''
import unittest
from transformers import AutoTokenizer, FalconConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
FalconForCausalLM,
FalconForQuestionAnswering,
FalconForSequenceClassification,
FalconForTokenClassification,
FalconModel,
)
class SCREAMING_SNAKE_CASE__ :
def __init__( self : str , a_ : List[str] , a_ : Tuple=3 , a_ : Any=7 , a_ : Any=True , a_ : Union[str, Any]=True , a_ : Tuple=False , a_ : Optional[int]=True , a_ : Any=99 , a_ : Dict=32 , a_ : Dict=5 , a_ : List[Any]=4 , a_ : Any=37 , a_ : Any="gelu" , a_ : List[str]=0.1 , a_ : Dict=0.1 , a_ : Optional[Any]=512 , a_ : List[Any]=16 , a_ : Any=2 , a_ : str=0.02 , a_ : Any=3 , a_ : List[Any]=4 , a_ : List[str]=None , ):
"""simple docstring"""
__snake_case = parent
__snake_case = batch_size
__snake_case = seq_length
__snake_case = is_training
__snake_case = use_input_mask
__snake_case = use_token_type_ids
__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_act
__snake_case = hidden_dropout_prob
__snake_case = attention_probs_dropout_prob
__snake_case = max_position_embeddings
__snake_case = type_vocab_size
__snake_case = type_sequence_label_size
__snake_case = initializer_range
__snake_case = num_labels
__snake_case = num_choices
__snake_case = scope
def A ( self : Any ):
"""simple docstring"""
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__snake_case = None
if self.use_input_mask:
__snake_case = random_attention_mask([self.batch_size, self.seq_length] )
__snake_case = None
__snake_case = None
__snake_case = None
__snake_case = None
if self.use_labels:
__snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__snake_case = ids_tensor([self.batch_size] , self.num_choices )
__snake_case = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def A ( self : Optional[int] ):
"""simple docstring"""
return FalconConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a_ , initializer_range=self.initializer_range , pad_token_id=1 , new_decoder_architecture=a_ , )
def A ( self : List[str] , a_ : Dict , a_ : Tuple , a_ : Optional[Any] , a_ : Dict , a_ : Dict , a_ : Dict , a_ : Union[str, Any] ):
"""simple docstring"""
__snake_case = FalconModel(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ )
__snake_case = model(a_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def A ( self : List[Any] , a_ : List[Any] , a_ : Union[str, Any] , a_ : Optional[Any] , a_ : Any , a_ : List[Any] , a_ : Optional[Any] , a_ : Union[str, Any] , a_ : Tuple , a_ : Optional[int] , ):
"""simple docstring"""
__snake_case = True
__snake_case = FalconModel(a_ )
model.to(a_ )
model.eval()
__snake_case = model(
a_ , attention_mask=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , )
__snake_case = model(
a_ , attention_mask=a_ , encoder_hidden_states=a_ , )
__snake_case = model(a_ , attention_mask=a_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def A ( self : Optional[int] , a_ : int , a_ : int , a_ : List[Any] , a_ : str , a_ : List[str] , a_ : str , a_ : str , a_ : Union[str, Any] , a_ : Optional[int] , ):
"""simple docstring"""
__snake_case = FalconForCausalLM(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def A ( self : List[Any] , a_ : Optional[int] , a_ : Optional[Any] , a_ : str , a_ : Tuple , a_ : str , a_ : List[Any] , a_ : Optional[Any] , a_ : Any , a_ : Dict , ):
"""simple docstring"""
__snake_case = True
__snake_case = True
__snake_case = FalconForCausalLM(config=a_ )
model.to(a_ )
model.eval()
# first forward pass
__snake_case = model(
a_ , attention_mask=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , use_cache=a_ , )
__snake_case = outputs.past_key_values
# create hypothetical multiple next token and extent to next_input_ids
__snake_case = ids_tensor((self.batch_size, 3) , config.vocab_size )
__snake_case = ids_tensor((self.batch_size, 3) , vocab_size=2 )
# append to next input_ids and
__snake_case = torch.cat([input_ids, next_tokens] , dim=-1 )
__snake_case = torch.cat([input_mask, next_mask] , dim=-1 )
__snake_case = model(
a_ , attention_mask=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , output_hidden_states=a_ , )["hidden_states"][0]
__snake_case = model(
a_ , attention_mask=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , past_key_values=a_ , output_hidden_states=a_ , )["hidden_states"][0]
# select random slice
__snake_case = ids_tensor((1,) , output_from_past.shape[-1] ).item()
__snake_case = output_from_no_past[:, -3:, random_slice_idx].detach()
__snake_case = output_from_past[:, :, random_slice_idx].detach()
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] )
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = self.prepare_config_and_inputs()
(
(
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) ,
) = config_and_inputs
__snake_case = {"input_ids": input_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = (
(
FalconModel,
FalconForCausalLM,
FalconForSequenceClassification,
FalconForTokenClassification,
FalconForQuestionAnswering,
)
if is_torch_available()
else ()
)
__SCREAMING_SNAKE_CASE = (FalconForCausalLM,) if is_torch_available() else ()
__SCREAMING_SNAKE_CASE = (
{
"""feature-extraction""": FalconModel,
"""text-classification""": FalconForSequenceClassification,
"""text-generation""": FalconForCausalLM,
"""question-answering""": FalconForQuestionAnswering,
"""token-classification""": FalconForTokenClassification,
"""zero-shot""": FalconForSequenceClassification,
}
if is_torch_available()
else {}
)
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = False
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = FalconModelTester(self )
__snake_case = ConfigTester(self , config_class=a_ , hidden_size=37 )
def A ( self : Optional[Any] ):
"""simple docstring"""
self.config_tester.run_common_tests()
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*a_ )
def A ( self : List[str] ):
"""simple docstring"""
__snake_case , *__snake_case = self.model_tester.prepare_config_and_inputs()
for alibi in [True, False]:
__snake_case = alibi
self.model_tester.create_and_check_model(a_ , *a_ )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = 3
__snake_case = input_dict["input_ids"]
__snake_case = input_ids.ne(1 ).to(a_ )
__snake_case = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size )
__snake_case = FalconForSequenceClassification(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) )
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = 3
__snake_case = "single_label_classification"
__snake_case = input_dict["input_ids"]
__snake_case = input_ids.ne(1 ).to(a_ )
__snake_case = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size )
__snake_case = FalconForSequenceClassification(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = input_dict["input_ids"]
__snake_case = FalconForCausalLM(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , use_cache=a_ )
__snake_case = input_ids.shape[0]
__snake_case = model._convert_to_rw_cache(result.past_key_values )
__snake_case = model._convert_cache_to_standard_format(a_ , a_ )
for layer in range(len(a_ ) ):
for tensor_idx in range(2 ):
self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3 )
self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4 )
self.assertTrue(
torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx] ) )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = 3
__snake_case = "multi_label_classification"
__snake_case = input_dict["input_ids"]
__snake_case = input_ids.ne(1 ).to(a_ )
__snake_case = ids_tensor(
[self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float )
__snake_case = FalconForSequenceClassification(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) )
def A ( self : Dict ):
"""simple docstring"""
for model_class in self.all_generative_model_classes:
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
# If it doesn't support cache, pass the test
if not hasattr(a_ , "use_cache" ):
return
__snake_case = model_class(a_ ).to(a_ )
if "use_cache" not in inputs:
__snake_case = True
__snake_case = model(**a_ )
# If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format)
if "past_key_values" not in outputs:
return
__snake_case = (
getattr(a_ , "decoder_layers" , a_ )
or getattr(a_ , "num_decoder_layers" , a_ )
or config.num_hidden_layers
)
__snake_case = getattr(a_ , "num_kv_heads" , config.num_attention_heads )
__snake_case = getattr(a_ , "d_model" , config.hidden_size )
__snake_case = embed_dim // num_attention_heads
__snake_case = outputs["past_key_values"]
self.assertEqual(len(a_ ) , a_ )
__snake_case , __snake_case = inputs["input_ids"].shape
for i in range(a_ ):
if config.new_decoder_architecture:
__snake_case = config.num_attention_heads
elif config.multi_query:
__snake_case = 1
self.assertEqual(len(past_kv[0] ) , 2 ) # K V for the decoder = 2
self.assertEqual(
past_kv[i][0].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) )
self.assertEqual(
past_kv[i][1].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) )
@require_torch
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
@slow
def A ( self : Any ):
"""simple docstring"""
__snake_case = AutoTokenizer.from_pretrained("Rocketknight1/falcon-rw-1b" )
__snake_case = FalconForCausalLM.from_pretrained("Rocketknight1/falcon-rw-1b" )
model.eval()
model.to(a_ )
__snake_case = tokenizer("My favorite food is" , return_tensors="pt" ).to(a_ )
__snake_case = (
"My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday."
)
__snake_case = model.generate(**a_ , do_sample=a_ , max_new_tokens=19 )
__snake_case = tokenizer.batch_decode(a_ )[0]
self.assertEqual(a_ , a_ )
@slow
def A ( self : Optional[int] ):
"""simple docstring"""
for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]:
__snake_case = AutoTokenizer.from_pretrained(a_ )
__snake_case = FalconForCausalLM.from_pretrained(a_ )
model.eval()
model.to(a_ )
__snake_case = tokenizer("My favorite food is" , return_tensors="pt" ).to(a_ )
# We just test that these run without errors - the models are randomly initialized
# and so the actual text outputs will be garbage
model.generate(**a_ , do_sample=a_ , max_new_tokens=4 )
model.generate(**a_ , do_sample=a_ , max_new_tokens=4 )
model.generate(**a_ , num_beams=2 , max_new_tokens=4 )
@slow
def A ( self : Any ):
"""simple docstring"""
with torch.no_grad():
for repo in [
"Rocketknight1/falcon-rw-1b",
"Rocketknight1/tiny-random-falcon-7b",
"Rocketknight1/tiny-random-falcon-40b",
]:
__snake_case = AutoTokenizer.from_pretrained(a_ )
__snake_case = FalconForCausalLM.from_pretrained(a_ )
model.eval()
model.to(device=a_ )
__snake_case = tokenizer("My favorite food is" , return_tensors="pt" ).to(a_ )
# Test results are the same with and without cache
__snake_case = model.generate(**a_ , do_sample=a_ , max_new_tokens=20 , use_cache=a_ )
__snake_case = model.generate(**a_ , do_sample=a_ , max_new_tokens=20 , use_cache=a_ )
self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0 )
| 69 | 1 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> str:
if isinstance(_UpperCAmelCase , _UpperCAmelCase ):
raise TypeError("'float' object cannot be interpreted as an integer" )
if isinstance(_UpperCAmelCase , _UpperCAmelCase ):
raise TypeError("'str' object cannot be interpreted as an integer" )
if num == 0:
return "0b0"
__snake_case = False
if num < 0:
__snake_case = True
__snake_case = -num
__snake_case = []
while num > 0:
binary.insert(0 , num % 2 )
num >>= 1
if negative:
return "-0b" + "".join(str(_UpperCAmelCase ) for e in binary )
return "0b" + "".join(str(_UpperCAmelCase ) for e in binary )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 |
'''simple docstring'''
import mpmath # for roots of unity
import numpy as np
class SCREAMING_SNAKE_CASE__ :
def __init__( self : Tuple , a_ : Optional[int]=None , a_ : int=None ):
"""simple docstring"""
__snake_case = list(poly_a or [0] )[:]
__snake_case = list(poly_b or [0] )[:]
# Remove leading zero coefficients
while self.polyA[-1] == 0:
self.polyA.pop()
__snake_case = len(self.polyA )
while self.polyB[-1] == 0:
self.polyB.pop()
__snake_case = len(self.polyB )
# Add 0 to make lengths equal a power of 2
__snake_case = int(
2 ** np.ceil(np.loga(len(self.polyA ) + len(self.polyB ) - 1 ) ) )
while len(self.polyA ) < self.c_max_length:
self.polyA.append(0 )
while len(self.polyB ) < self.c_max_length:
self.polyB.append(0 )
# A complex root used for the fourier transform
__snake_case = complex(mpmath.root(x=1 , n=self.c_max_length , k=1 ) )
# The product
__snake_case = self.__multiply()
def A ( self : Any , a_ : Optional[Any] ):
"""simple docstring"""
__snake_case = [[x] for x in self.polyA] if which == "A" else [[x] for x in self.polyB]
# Corner case
if len(a_ ) <= 1:
return dft[0]
#
__snake_case = self.c_max_length // 2
while next_ncol > 0:
__snake_case = [[] for i in range(a_ )]
__snake_case = self.root**next_ncol
# First half of next step
__snake_case = 1
for j in range(self.c_max_length // (next_ncol * 2) ):
for i in range(a_ ):
new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j] )
current_root *= root
# Second half of next step
__snake_case = 1
for j in range(self.c_max_length // (next_ncol * 2) ):
for i in range(a_ ):
new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j] )
current_root *= root
# Update
__snake_case = new_dft
__snake_case = next_ncol // 2
return dft[0]
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = self.__dft("A" )
__snake_case = self.__dft("B" )
__snake_case = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length )]]
del dft_a
del dft_b
# Corner Case
if len(inverce_c[0] ) <= 1:
return inverce_c[0]
# Inverse DFT
__snake_case = 2
while next_ncol <= self.c_max_length:
__snake_case = [[] for i in range(a_ )]
__snake_case = self.root ** (next_ncol // 2)
__snake_case = 1
# First half of next step
for j in range(self.c_max_length // next_ncol ):
for i in range(next_ncol // 2 ):
# Even positions
new_inverse_c[i].append(
(
inverce_c[i][j]
+ inverce_c[i][j + self.c_max_length // next_ncol]
)
/ 2 )
# Odd positions
new_inverse_c[i + next_ncol // 2].append(
(
inverce_c[i][j]
- inverce_c[i][j + self.c_max_length // next_ncol]
)
/ (2 * current_root) )
current_root *= root
# Update
__snake_case = new_inverse_c
next_ncol *= 2
# Unpack
__snake_case = [round(x[0].real , 8 ) + round(x[0].imag , 8 ) * 1j for x in inverce_c]
# Remove leading 0's
while inverce_c[-1] == 0:
inverce_c.pop()
return inverce_c
def __str__( self : Optional[int] ):
"""simple docstring"""
__snake_case = "A = " + " + ".join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.polyA[: self.len_A] ) )
__snake_case = "B = " + " + ".join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.polyB[: self.len_B] ) )
__snake_case = "A*B = " + " + ".join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.product ) )
return f'''{a}\n{b}\n{c}'''
# Unit tests
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 | 1 |
'''simple docstring'''
a : Dict = '''Alexander Joslin'''
import operator as op
from .stack import Stack
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> int:
__snake_case = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub}
__snake_case = Stack()
__snake_case = Stack()
for i in equation:
if i.isdigit():
# RULE 1
operand_stack.push(int(_UpperCAmelCase ) )
elif i in operators:
# RULE 2
operator_stack.push(_UpperCAmelCase )
elif i == ")":
# RULE 4
__snake_case = operator_stack.peek()
operator_stack.pop()
__snake_case = operand_stack.peek()
operand_stack.pop()
__snake_case = operand_stack.peek()
operand_stack.pop()
__snake_case = operators[opr](_UpperCAmelCase , _UpperCAmelCase )
operand_stack.push(_UpperCAmelCase )
# RULE 5
return operand_stack.peek()
if __name__ == "__main__":
a : Dict = '''(5 + ((4 * 2) * (2 + 3)))'''
# answer = 45
print(F'''{equation} = {dijkstras_two_stack_algorithm(equation)}''')
| 69 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
a : List[Any] = {
'''configuration_table_transformer''': [
'''TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''TableTransformerConfig''',
'''TableTransformerOnnxConfig''',
]
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : Tuple = [
'''TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TableTransformerForObjectDetection''',
'''TableTransformerModel''',
'''TableTransformerPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_table_transformer import (
TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
TableTransformerConfig,
TableTransformerOnnxConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_table_transformer import (
TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TableTransformerForObjectDetection,
TableTransformerModel,
TableTransformerPreTrainedModel,
)
else:
import sys
a : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 69 | 1 |
'''simple docstring'''
from datetime import datetime
import requests
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> bytes:
__snake_case = "https://downloadgram.net/wp-json/wppress/video-downloader/video?url="
__snake_case = requests.get(base_url + url ).json()[0]["urls"][0]["src"]
return requests.get(_UpperCAmelCase ).content
if __name__ == "__main__":
a : Optional[Any] = input('''Enter Video/IGTV url: ''').strip()
a : str = F'''{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4'''
with open(file_name, '''wb''') as fp:
fp.write(download_video(url))
print(F'''Done. Video saved to disk as {file_name}.''')
| 69 |
'''simple docstring'''
import json
import os
import torch
from diffusers import UNetaDModel
os.makedirs('''hub/hopper-medium-v2/unet/hor32''', exist_ok=True)
os.makedirs('''hub/hopper-medium-v2/unet/hor128''', exist_ok=True)
os.makedirs('''hub/hopper-medium-v2/value_function''', exist_ok=True)
def __UpperCAmelCase ( _UpperCAmelCase : List[str] ) -> str:
if hor == 1_28:
__snake_case = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D")
__snake_case = (32, 1_28, 2_56)
__snake_case = ("UpResnetBlock1D", "UpResnetBlock1D")
elif hor == 32:
__snake_case = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D")
__snake_case = (32, 64, 1_28, 2_56)
__snake_case = ("UpResnetBlock1D", "UpResnetBlock1D", "UpResnetBlock1D")
__snake_case = torch.load(F'''/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch''' )
__snake_case = model.state_dict()
__snake_case = {
"down_block_types": down_block_types,
"block_out_channels": block_out_channels,
"up_block_types": up_block_types,
"layers_per_block": 1,
"use_timestep_embedding": True,
"out_block_type": "OutConv1DBlock",
"norm_num_groups": 8,
"downsample_each_block": False,
"in_channels": 14,
"out_channels": 14,
"extra_in_channels": 0,
"time_embedding_type": "positional",
"flip_sin_to_cos": False,
"freq_shift": 1,
"sample_size": 6_55_36,
"mid_block_type": "MidResTemporalBlock1D",
"act_fn": "mish",
}
__snake_case = UNetaDModel(**_UpperCAmelCase )
print(F'''length of state dict: {len(state_dict.keys() )}''' )
print(F'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' )
__snake_case = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) )
for k, v in mapping.items():
__snake_case = state_dict.pop(_UpperCAmelCase )
hf_value_function.load_state_dict(_UpperCAmelCase )
torch.save(hf_value_function.state_dict() , F'''hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin''' )
with open(F'''hub/hopper-medium-v2/unet/hor{hor}/config.json''' , "w" ) as f:
json.dump(_UpperCAmelCase , _UpperCAmelCase )
def __UpperCAmelCase ( ) -> List[Any]:
__snake_case = {
"in_channels": 14,
"down_block_types": ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D"),
"up_block_types": (),
"out_block_type": "ValueFunction",
"mid_block_type": "ValueFunctionMidBlock1D",
"block_out_channels": (32, 64, 1_28, 2_56),
"layers_per_block": 1,
"downsample_each_block": True,
"sample_size": 6_55_36,
"out_channels": 14,
"extra_in_channels": 0,
"time_embedding_type": "positional",
"use_timestep_embedding": True,
"flip_sin_to_cos": False,
"freq_shift": 1,
"norm_num_groups": 8,
"act_fn": "mish",
}
__snake_case = torch.load("/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch" )
__snake_case = model
__snake_case = UNetaDModel(**_UpperCAmelCase )
print(F'''length of state dict: {len(state_dict.keys() )}''' )
print(F'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' )
__snake_case = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) )
for k, v in mapping.items():
__snake_case = state_dict.pop(_UpperCAmelCase )
hf_value_function.load_state_dict(_UpperCAmelCase )
torch.save(hf_value_function.state_dict() , "hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin" )
with open("hub/hopper-medium-v2/value_function/config.json" , "w" ) as f:
json.dump(_UpperCAmelCase , _UpperCAmelCase )
if __name__ == "__main__":
unet(32)
# unet(128)
value_function()
| 69 | 1 |
'''simple docstring'''
import gc
import importlib.metadata
import tempfile
import unittest
from packaging import version
from transformers import (
AutoModel,
AutoModelForCausalLM,
AutoModelForSeqaSeqLM,
AutoModelForSequenceClassification,
AutoTokenizer,
BitsAndBytesConfig,
pipeline,
)
from transformers.testing_utils import (
is_torch_available,
require_accelerate,
require_bitsandbytes,
require_torch,
require_torch_gpu,
require_torch_multi_gpu,
slow,
)
def __UpperCAmelCase ( _UpperCAmelCase : Any ) -> Union[str, Any]:
if model.config.model_type == "gpt2":
return model.transformer.h[0].mlp.c_fc
return model.transformer.h[0].mlp.dense_ah_to_h
if is_torch_available():
import torch
import torch.nn as nn
class SCREAMING_SNAKE_CASE__ ( nn.Module ):
def __init__( self : Dict , a_ : nn.Module , a_ : int ):
"""simple docstring"""
super().__init__()
__snake_case = module
__snake_case = nn.Sequential(
nn.Linear(module.in_features , a_ , bias=a_ ) , nn.Linear(a_ , module.out_features , bias=a_ ) , )
__snake_case = (2.0 / (5 * min(module.in_features , module.out_features ))) ** 0.5
nn.init.normal_(self.adapter[0].weight , std=a_ )
nn.init.zeros_(self.adapter[1].weight )
self.adapter.to(module.weight.device )
def A ( self : str , a_ : List[Any] , *a_ : int , **a_ : int ):
"""simple docstring"""
return self.module(a_ , *a_ , **a_ ) + self.adapter(a_ )
@require_bitsandbytes
@require_accelerate
@require_torch
@require_torch_gpu
@slow
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
# We keep the constants inside the init function and model loading inside setUp function
# We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected)
# Therefore here we use only bloom-1b3 to test our module
__SCREAMING_SNAKE_CASE = """bigscience/bloom-1b7"""
# Constant values
__SCREAMING_SNAKE_CASE = 2.109_6595_5269_2574
__SCREAMING_SNAKE_CASE = """Hello my name is"""
__SCREAMING_SNAKE_CASE = set()
EXPECTED_OUTPUTS.add("""Hello my name is John and I am a professional photographer. I""" )
EXPECTED_OUTPUTS.add("""Hello my name is John.\nI am a friend of your father.\n""" )
EXPECTED_OUTPUTS.add("""Hello my name is John Doe, I am a student at the University""" )
__SCREAMING_SNAKE_CASE = 10
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = AutoTokenizer.from_pretrained(self.model_name )
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def A ( self : Optional[int] ):
"""simple docstring"""
super().setUp()
# Models and tokenizer
__snake_case = AutoModelForCausalLM.from_pretrained(
self.model_name , torch_dtype=torch.floataa , device_map="auto" )
__snake_case = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a_ , device_map="auto" )
def A ( self : List[str] ):
"""simple docstring"""
del self.model_fpaa
del self.model_abit
gc.collect()
torch.cuda.empty_cache()
def A ( self : List[str] ):
"""simple docstring"""
__snake_case = self.model_abit.config
self.assertTrue(hasattr(a_ , "quantization_config" ) )
__snake_case = config.to_dict()
__snake_case = config.to_diff_dict()
__snake_case = config.to_json_string()
def A ( self : Optional[Any] ):
"""simple docstring"""
from bitsandbytes.nn import Paramsabit
__snake_case = self.model_fpaa.get_memory_footprint()
__snake_case = self.model_abit.get_memory_footprint()
self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE )
__snake_case = get_some_linear_layer(self.model_abit )
self.assertTrue(linear.weight.__class__ == Paramsabit )
def A ( self : int ):
"""simple docstring"""
from transformers import TaPreTrainedModel
self.model_fpaa.get_memory_footprint()
self.model_abit.get_memory_footprint()
for name, module in self.model_abit.named_modules():
if isinstance(a_ , torch.nn.Linear ):
if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules:
# 4-bit parameters are packed in uint8 variables
self.assertTrue(module.weight.dtype == torch.uinta )
def A ( self : Any ):
"""simple docstring"""
__snake_case = self.tokenizer(self.input_text , return_tensors="pt" )
__snake_case = self.model_abit.generate(input_ids=encoded_input["input_ids"].to(0 ) , max_new_tokens=10 )
self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a_ ) , self.EXPECTED_OUTPUTS )
def A ( self : int ):
"""simple docstring"""
__snake_case = BitsAndBytesConfig()
__snake_case = True
__snake_case = AutoModelForCausalLM.from_pretrained(
self.model_name , quantization_config=a_ , device_map="auto" )
__snake_case = self.tokenizer(self.input_text , return_tensors="pt" )
__snake_case = model_abit_from_config.generate(
input_ids=encoded_input["input_ids"].to(0 ) , max_new_tokens=10 )
self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a_ ) , self.EXPECTED_OUTPUTS )
def A ( self : Dict ):
"""simple docstring"""
with self.assertRaises(a_ ), tempfile.TemporaryDirectory() as tmpdirname:
self.model_abit.save_pretrained(a_ )
def A ( self : List[str] ):
"""simple docstring"""
__snake_case = BitsAndBytesConfig()
with self.assertRaises(a_ ):
__snake_case = AutoModelForCausalLM.from_pretrained(
self.model_name , quantization_config=a_ , load_in_abit=a_ , device_map="auto" , bnb_abit_quant_type="nf4" , )
def A ( self : int ):
"""simple docstring"""
with self.assertRaises(a_ ):
# Tries with `str`
self.model_abit.to("cpu" )
with self.assertRaises(a_ ):
# Tries with a `dtype``
self.model_abit.to(torch.floataa )
with self.assertRaises(a_ ):
# Tries with a `device`
self.model_abit.to(torch.device("cuda:0" ) )
with self.assertRaises(a_ ):
# Tries with a `device`
self.model_abit.float()
with self.assertRaises(a_ ):
# Tries with a `device`
self.model_abit.half()
# Test if we did not break anything
__snake_case = self.tokenizer(self.input_text , return_tensors="pt" )
__snake_case = self.model_fpaa.to(torch.floataa )
__snake_case = self.model_fpaa.generate(input_ids=encoded_input["input_ids"].to(0 ) , max_new_tokens=10 )
# Check this does not throw an error
__snake_case = self.model_fpaa.to("cpu" )
# Check this does not throw an error
__snake_case = self.model_fpaa.half()
# Check this does not throw an error
__snake_case = self.model_fpaa.float()
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = AutoModelForSeqaSeqLM.from_pretrained("t5-small" , load_in_abit=a_ , device_map="auto" )
self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa )
@require_bitsandbytes
@require_accelerate
@require_torch
@require_torch_gpu
@slow
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
@classmethod
def A ( cls : Optional[int] ):
"""simple docstring"""
__snake_case = "t5-small"
__snake_case = "google/flan-t5-small" # flan-t5 uses dense-act instead of dense-relu-dense
__snake_case = AutoTokenizer.from_pretrained(cls.model_name )
__snake_case = "Translate in German: Hello, my dog is cute"
def A ( self : List[str] ):
"""simple docstring"""
gc.collect()
torch.cuda.empty_cache()
def A ( self : List[str] ):
"""simple docstring"""
from transformers import TaForConditionalGeneration
__snake_case = TaForConditionalGeneration._keep_in_fpaa_modules
__snake_case = None
# test with `t5-small`
__snake_case = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a_ , device_map="auto" )
__snake_case = self.tokenizer(self.input_text , return_tensors="pt" ).to(0 )
__snake_case = model.generate(**a_ )
# test with `flan-t5-small`
__snake_case = TaForConditionalGeneration.from_pretrained(
self.dense_act_model_name , load_in_abit=a_ , device_map="auto" )
__snake_case = self.tokenizer(self.input_text , return_tensors="pt" ).to(0 )
__snake_case = model.generate(**a_ )
__snake_case = modules
def A ( self : Optional[Any] ):
"""simple docstring"""
import bitsandbytes as bnb
from transformers import TaForConditionalGeneration
# test with `t5-small`
__snake_case = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a_ , device_map="auto" )
# there was a bug with decoders - this test checks that it is fixed
self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit ) )
__snake_case = self.tokenizer(self.input_text , return_tensors="pt" ).to(0 )
__snake_case = model.generate(**a_ )
# test with `flan-t5-small`
__snake_case = TaForConditionalGeneration.from_pretrained(
self.dense_act_model_name , load_in_abit=a_ , device_map="auto" )
__snake_case = self.tokenizer(self.input_text , return_tensors="pt" ).to(0 )
__snake_case = model.generate(**a_ )
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def A ( self : Optional[int] ):
"""simple docstring"""
super().setUp()
# model_name
__snake_case = "bigscience/bloom-560m"
__snake_case = "t5-small"
# Different types of model
__snake_case = AutoModel.from_pretrained(self.model_name , load_in_abit=a_ , device_map="auto" )
# Sequence classification model
__snake_case = AutoModelForSequenceClassification.from_pretrained(
self.model_name , load_in_abit=a_ , device_map="auto" )
# CausalLM model
__snake_case = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a_ , device_map="auto" )
# Seq2seq model
__snake_case = AutoModelForSeqaSeqLM.from_pretrained(
self.seq_to_seq_name , load_in_abit=a_ , device_map="auto" )
def A ( self : Dict ):
"""simple docstring"""
del self.base_model
del self.sequence_model
del self.model_abit
del self.seq_to_seq_model
gc.collect()
torch.cuda.empty_cache()
def A ( self : int ):
"""simple docstring"""
from bitsandbytes.nn import Paramsabit
self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit )
# Other heads should be nn.Parameter
self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter )
self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter )
self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter )
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def A ( self : str ):
"""simple docstring"""
super().setUp()
def A ( self : str ):
"""simple docstring"""
del self.pipe
gc.collect()
torch.cuda.empty_cache()
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = pipeline(
"text-generation" , model=self.model_name , model_kwargs={"device_map": "auto", "load_in_4bit": True, "torch_dtype": torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , )
# Real second forward pass
__snake_case = self.pipe(self.input_text )
self.assertIn(pipeline_output[0]["generated_text"] , self.EXPECTED_OUTPUTS )
@require_torch_multi_gpu
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def A ( self : Any ):
"""simple docstring"""
super().setUp()
def A ( self : Optional[int] ):
"""simple docstring"""
__snake_case = AutoModelForCausalLM.from_pretrained(
self.model_name , load_in_abit=a_ , device_map="balanced" )
# Check correct device map
self.assertEqual(set(model_parallel.hf_device_map.values() ) , {0, 1} )
# Check that inference pass works on the model
__snake_case = self.tokenizer(self.input_text , return_tensors="pt" )
# Second real batch
__snake_case = model_parallel.generate(input_ids=encoded_input["input_ids"].to(0 ) , max_new_tokens=10 )
self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=a_ ) , self.EXPECTED_OUTPUTS )
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def A ( self : int ):
"""simple docstring"""
__snake_case = "facebook/opt-350m"
super().setUp()
def A ( self : Dict ):
"""simple docstring"""
if version.parse(importlib.metadata.version("bitsandbytes" ) ) < version.parse("0.37.0" ):
return
# Step 1: freeze all parameters
__snake_case = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a_ )
self.assertEqual(set(model.hf_device_map.values() ) , {torch.cuda.current_device()} )
for param in model.parameters():
__snake_case = False # freeze the model - train adapters later
if param.ndim == 1:
# cast the small parameters (e.g. layernorm) to fp32 for stability
__snake_case = param.data.to(torch.floataa )
# Step 2: add adapters
for _, module in model.named_modules():
if "OPTAttention" in repr(type(a_ ) ):
__snake_case = LoRALayer(module.q_proj , rank=16 )
__snake_case = LoRALayer(module.k_proj , rank=16 )
__snake_case = LoRALayer(module.v_proj , rank=16 )
# Step 3: dummy batch
__snake_case = self.tokenizer("Test batch " , return_tensors="pt" ).to(0 )
# Step 4: Check if the gradient is not None
with torch.cuda.amp.autocast():
__snake_case = model.forward(**a_ )
out.logits.norm().backward()
for module in model.modules():
if isinstance(a_ , a_ ):
self.assertTrue(module.adapter[1].weight.grad is not None )
self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0 )
elif isinstance(a_ , nn.Embedding ):
self.assertTrue(module.weight.grad is None )
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = """gpt2-xl"""
__SCREAMING_SNAKE_CASE = 3.3191_8548_5415_2187
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int = 1_00_00_00 ) -> int:
__snake_case = 1
__snake_case = 1
__snake_case = {1: 1}
for inputa in range(2 , _UpperCAmelCase ):
__snake_case = 0
__snake_case = inputa
while True:
if number in counters:
counter += counters[number]
break
if number % 2 == 0:
number //= 2
counter += 1
else:
__snake_case = (3 * number) + 1
counter += 1
if inputa not in counters:
__snake_case = counter
if counter > pre_counter:
__snake_case = inputa
__snake_case = counter
return largest_number
if __name__ == "__main__":
print(solution(int(input().strip())))
| 69 | 1 |
'''simple docstring'''
import functools
from typing import Any
def __UpperCAmelCase ( _UpperCAmelCase : str , _UpperCAmelCase : list[str] ) -> bool:
# Validation
if not isinstance(_UpperCAmelCase , _UpperCAmelCase ) or len(_UpperCAmelCase ) == 0:
raise ValueError("the string should be not empty string" )
if not isinstance(_UpperCAmelCase , _UpperCAmelCase ) or not all(
isinstance(_UpperCAmelCase , _UpperCAmelCase ) and len(_UpperCAmelCase ) > 0 for item in words ):
raise ValueError("the words should be a list of non-empty strings" )
# Build trie
__snake_case = {}
__snake_case = "WORD_KEEPER"
for word in words:
__snake_case = trie
for c in word:
if c not in trie_node:
__snake_case = {}
__snake_case = trie_node[c]
__snake_case = True
__snake_case = len(_UpperCAmelCase )
# Dynamic programming method
@functools.cache
def is_breakable(_UpperCAmelCase : int ) -> bool:
if index == len_string:
return True
__snake_case = trie
for i in range(_UpperCAmelCase , _UpperCAmelCase ):
__snake_case = trie_node.get(string[i] , _UpperCAmelCase )
if trie_node is None:
return False
if trie_node.get(_UpperCAmelCase , _UpperCAmelCase ) and is_breakable(i + 1 ):
return True
return False
return is_breakable(0 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 |
'''simple docstring'''
from ...processing_utils import ProcessorMixin
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = """SpeechT5FeatureExtractor"""
__SCREAMING_SNAKE_CASE = """SpeechT5Tokenizer"""
def __init__( self : List[Any] , a_ : str , a_ : str ):
"""simple docstring"""
super().__init__(a_ , a_ )
def __call__( self : Dict , *a_ : Tuple , **a_ : List[str] ):
"""simple docstring"""
__snake_case = kwargs.pop("audio" , a_ )
__snake_case = kwargs.pop("text" , a_ )
__snake_case = kwargs.pop("text_target" , a_ )
__snake_case = kwargs.pop("audio_target" , a_ )
__snake_case = kwargs.pop("sampling_rate" , a_ )
if audio is not None and text is not None:
raise ValueError(
"Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?" )
if audio_target is not None and text_target is not None:
raise ValueError(
"Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?" )
if audio is None and audio_target is None and text is None and text_target is None:
raise ValueError(
"You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process." )
if audio is not None:
__snake_case = self.feature_extractor(a_ , *a_ , sampling_rate=a_ , **a_ )
elif text is not None:
__snake_case = self.tokenizer(a_ , **a_ )
else:
__snake_case = None
if audio_target is not None:
__snake_case = self.feature_extractor(audio_target=a_ , *a_ , sampling_rate=a_ , **a_ )
__snake_case = targets["input_values"]
elif text_target is not None:
__snake_case = self.tokenizer(a_ , **a_ )
__snake_case = targets["input_ids"]
else:
__snake_case = None
if inputs is None:
return targets
if targets is not None:
__snake_case = labels
__snake_case = targets.get("attention_mask" )
if decoder_attention_mask is not None:
__snake_case = decoder_attention_mask
return inputs
def A ( self : List[str] , *a_ : str , **a_ : Dict ):
"""simple docstring"""
__snake_case = kwargs.pop("input_values" , a_ )
__snake_case = kwargs.pop("input_ids" , a_ )
__snake_case = kwargs.pop("labels" , a_ )
if input_values is not None and input_ids is not None:
raise ValueError("Cannot process both `input_values` and `input_ids` inputs." )
if input_values is None and input_ids is None and labels is None:
raise ValueError(
"You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded." )
if input_values is not None:
__snake_case = self.feature_extractor.pad(a_ , *a_ , **a_ )
elif input_ids is not None:
__snake_case = self.tokenizer.pad(a_ , **a_ )
else:
__snake_case = None
if labels is not None:
if "input_ids" in labels or (isinstance(a_ , a_ ) and "input_ids" in labels[0]):
__snake_case = self.tokenizer.pad(a_ , **a_ )
__snake_case = targets["input_ids"]
else:
__snake_case = self.feature_extractor.feature_size
__snake_case = self.feature_extractor.num_mel_bins
__snake_case = self.feature_extractor.pad(a_ , *a_ , **a_ )
__snake_case = feature_size_hack
__snake_case = targets["input_values"]
else:
__snake_case = None
if inputs is None:
return targets
if targets is not None:
__snake_case = labels
__snake_case = targets.get("attention_mask" )
if decoder_attention_mask is not None:
__snake_case = decoder_attention_mask
return inputs
def A ( self : List[str] , *a_ : Any , **a_ : List[str] ):
"""simple docstring"""
return self.tokenizer.batch_decode(*a_ , **a_ )
def A ( self : Optional[int] , *a_ : Union[str, Any] , **a_ : str ):
"""simple docstring"""
return self.tokenizer.decode(*a_ , **a_ )
| 69 | 1 |
'''simple docstring'''
from collections import OrderedDict
from typing import List, Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
a : Dict = logging.get_logger(__name__)
a : Union[str, Any] = {
'''google/efficientnet-b7''': '''https://huggingface.co/google/efficientnet-b7/resolve/main/config.json''',
}
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = """efficientnet"""
def __init__( self : Optional[int] , a_ : int = 3 , a_ : int = 600 , a_ : float = 2.0 , a_ : float = 3.1 , a_ : int = 8 , a_ : List[int] = [3, 3, 5, 3, 5, 5, 3] , a_ : List[int] = [32, 16, 24, 40, 80, 112, 192] , a_ : List[int] = [16, 24, 40, 80, 112, 192, 320] , a_ : List[int] = [] , a_ : List[int] = [1, 2, 2, 2, 1, 2, 1] , a_ : List[int] = [1, 2, 2, 3, 3, 4, 1] , a_ : List[int] = [1, 6, 6, 6, 6, 6, 6] , a_ : float = 0.25 , a_ : str = "swish" , a_ : int = 2_560 , a_ : str = "mean" , a_ : float = 0.02 , a_ : float = 0.001 , a_ : float = 0.99 , a_ : float = 0.5 , a_ : float = 0.2 , **a_ : Union[str, Any] , ):
"""simple docstring"""
super().__init__(**a_ )
__snake_case = num_channels
__snake_case = image_size
__snake_case = width_coefficient
__snake_case = depth_coefficient
__snake_case = depth_divisor
__snake_case = kernel_sizes
__snake_case = in_channels
__snake_case = out_channels
__snake_case = depthwise_padding
__snake_case = strides
__snake_case = num_block_repeats
__snake_case = expand_ratios
__snake_case = squeeze_expansion_ratio
__snake_case = hidden_act
__snake_case = hidden_dim
__snake_case = pooling_type
__snake_case = initializer_range
__snake_case = batch_norm_eps
__snake_case = batch_norm_momentum
__snake_case = dropout_rate
__snake_case = drop_connect_rate
__snake_case = sum(a_ ) * 4
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = version.parse("""1.11""" )
@property
def A ( self : str ):
"""simple docstring"""
return OrderedDict(
[
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
] )
@property
def A ( self : List[str] ):
"""simple docstring"""
return 1e-5
| 69 |
'''simple docstring'''
import re
from pathlib import Path
from unittest import TestCase
import pytest
@pytest.mark.integration
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def A ( self : Optional[Any] , a_ : str ):
"""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 A ( self : Any , a_ : str ):
"""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 A ( self : Optional[int] ):
"""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 A ( self : Optional[Any] ):
"""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.''' )
| 69 | 1 |
'''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_rembert import RemBertTokenizer
else:
a : List[Any] = None
a : List[str] = logging.get_logger(__name__)
a : Optional[int] = {'''vocab_file''': '''sentencepiece.model''', '''tokenizer_file''': '''tokenizer.json'''}
a : int = {
'''vocab_file''': {
'''google/rembert''': '''https://huggingface.co/google/rembert/resolve/main/sentencepiece.model''',
},
'''tokenizer_file''': {
'''google/rembert''': '''https://huggingface.co/google/rembert/resolve/main/tokenizer.json''',
},
}
a : List[str] = {
'''google/rembert''': 256,
}
a : Tuple = '''▁'''
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES
__SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP
__SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__SCREAMING_SNAKE_CASE = RemBertTokenizer
def __init__( self : Optional[int] , a_ : Optional[Any]=None , a_ : Optional[int]=None , a_ : List[Any]=True , a_ : List[str]=True , a_ : str=False , a_ : Optional[Any]="[CLS]" , a_ : Optional[Any]="[SEP]" , a_ : List[Any]="<unk>" , a_ : Any="[SEP]" , a_ : List[Any]="<pad>" , a_ : List[str]="[CLS]" , a_ : Optional[Any]="[MASK]" , **a_ : str , ):
"""simple docstring"""
__snake_case = AddedToken(a_ , lstrip=a_ , rstrip=a_ ) if isinstance(a_ , a_ ) else mask_token
super().__init__(
a_ , tokenizer_file=a_ , do_lower_case=a_ , remove_space=a_ , keep_accents=a_ , bos_token=a_ , eos_token=a_ , unk_token=a_ , sep_token=a_ , pad_token=a_ , cls_token=a_ , mask_token=a_ , **a_ , )
__snake_case = do_lower_case
__snake_case = remove_space
__snake_case = keep_accents
__snake_case = vocab_file
__snake_case = False if not self.vocab_file else True
def A ( self : Optional[Any] , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
__snake_case = [self.sep_token_id]
__snake_case = [self.cls_token_id]
if token_ids_a is None:
return cls + token_ids_a + sep
return cls + token_ids_a + sep + token_ids_a + sep
def A ( self : Union[str, Any] , a_ : List[int] , a_ : Optional[List[int]] = None , a_ : bool = False ):
"""simple docstring"""
if already_has_special_tokens:
if token_ids_a is not None:
raise ValueError(
"You should not supply a second sequence if the provided sequence of "
"ids is already formatted with special tokens for the model." )
return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]
if token_ids_a is not None:
return [1] + ([0] * len(a_ )) + [1] + ([0] * len(a_ )) + [1]
return [1] + ([0] * len(a_ )) + [1]
def A ( self : Dict , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
__snake_case = [self.sep_token_id]
__snake_case = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def A ( self : int , a_ : str , a_ : Optional[str] = None ):
"""simple docstring"""
if not os.path.isdir(a_ ):
logger.error("Vocabulary path ({}) should be a directory".format(a_ ) )
return
__snake_case = 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_ ):
copyfile(self.vocab_file , a_ )
return (out_vocab_file,)
| 69 |
'''simple docstring'''
import os
from shutil import copyfile
from typing import List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
a : Optional[Any] = logging.get_logger(__name__)
a : Dict = {'''vocab_file''': '''sentencepiece.model'''}
a : Tuple = {
'''vocab_file''': {
'''google/rembert''': '''https://huggingface.co/google/rembert/resolve/main/sentencepiece.model''',
},
}
a : str = {
'''google/rembert''': 256,
}
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES
__SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP
__SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__( self : Optional[Any] , a_ : int , a_ : Any=False , a_ : List[Any]=True , a_ : List[Any]=True , a_ : List[Any]="[CLS]" , a_ : List[Any]="[SEP]" , a_ : List[Any]="[UNK]" , a_ : str="[SEP]" , a_ : List[str]="[PAD]" , a_ : Optional[int]="[CLS]" , a_ : List[str]="[MASK]" , **a_ : str , ):
"""simple docstring"""
super().__init__(
do_lower_case=a_ , remove_space=a_ , keep_accents=a_ , bos_token=a_ , eos_token=a_ , unk_token=a_ , sep_token=a_ , pad_token=a_ , cls_token=a_ , mask_token=a_ , **a_ , )
__snake_case = do_lower_case
__snake_case = remove_space
__snake_case = keep_accents
__snake_case = vocab_file
__snake_case = spm.SentencePieceProcessor()
self.sp_model.Load(a_ )
@property
def A ( self : Optional[Any] ):
"""simple docstring"""
return len(self.sp_model )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = {self.convert_ids_to_tokens(a_ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self : Dict ):
"""simple docstring"""
__snake_case = self.__dict__.copy()
__snake_case = None
return state
def __setstate__( self : str , a_ : Optional[int] ):
"""simple docstring"""
__snake_case = d
__snake_case = spm.SentencePieceProcessor()
self.sp_model.Load(self.vocab_file )
def A ( self : Tuple , a_ : Optional[int] , a_ : int=False ):
"""simple docstring"""
__snake_case = self.sp_model.EncodeAsPieces(a_ )
return pieces
def A ( self : Any , a_ : Optional[Any] ):
"""simple docstring"""
return self.sp_model.PieceToId(a_ )
def A ( self : Optional[Any] , a_ : List[str] ):
"""simple docstring"""
return self.sp_model.IdToPiece(a_ )
def A ( self : Optional[Any] , a_ : int ):
"""simple docstring"""
__snake_case = self.sp_model.decode_pieces(a_ )
return out_string
def A ( self : Union[str, Any] , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
__snake_case = [self.sep_token_id]
__snake_case = [self.cls_token_id]
if token_ids_a is None:
return cls + token_ids_a + sep
return cls + token_ids_a + sep + token_ids_a + sep
def A ( self : List[str] , a_ : List[int] , a_ : Optional[List[int]] = None , a_ : bool = False ):
"""simple docstring"""
if already_has_special_tokens:
if token_ids_a is not None:
raise ValueError(
"You should not supply a second sequence if the provided sequence of "
"ids is already formatted with special tokens for the model." )
return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]
if token_ids_a is not None:
return [1] + ([0] * len(a_ )) + [1] + ([0] * len(a_ )) + [1]
return [1] + ([0] * len(a_ )) + [1]
def A ( self : Tuple , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
__snake_case = [self.sep_token_id]
__snake_case = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def A ( self : List[Any] , a_ : str , a_ : Optional[str] = None ):
"""simple docstring"""
if not os.path.isdir(a_ ):
logger.error("Vocabulary path ({}) should be a directory".format(a_ ) )
return
__snake_case = 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_ ):
copyfile(self.vocab_file , a_ )
return (out_vocab_file,)
| 69 | 1 |
'''simple docstring'''
import os
from shutil import copyfile
from typing import List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
a : Optional[Any] = logging.get_logger(__name__)
a : Dict = {'''vocab_file''': '''sentencepiece.model'''}
a : Tuple = {
'''vocab_file''': {
'''google/rembert''': '''https://huggingface.co/google/rembert/resolve/main/sentencepiece.model''',
},
}
a : str = {
'''google/rembert''': 256,
}
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES
__SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP
__SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__( self : Optional[Any] , a_ : int , a_ : Any=False , a_ : List[Any]=True , a_ : List[Any]=True , a_ : List[Any]="[CLS]" , a_ : List[Any]="[SEP]" , a_ : List[Any]="[UNK]" , a_ : str="[SEP]" , a_ : List[str]="[PAD]" , a_ : Optional[int]="[CLS]" , a_ : List[str]="[MASK]" , **a_ : str , ):
"""simple docstring"""
super().__init__(
do_lower_case=a_ , remove_space=a_ , keep_accents=a_ , bos_token=a_ , eos_token=a_ , unk_token=a_ , sep_token=a_ , pad_token=a_ , cls_token=a_ , mask_token=a_ , **a_ , )
__snake_case = do_lower_case
__snake_case = remove_space
__snake_case = keep_accents
__snake_case = vocab_file
__snake_case = spm.SentencePieceProcessor()
self.sp_model.Load(a_ )
@property
def A ( self : Optional[Any] ):
"""simple docstring"""
return len(self.sp_model )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = {self.convert_ids_to_tokens(a_ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self : Dict ):
"""simple docstring"""
__snake_case = self.__dict__.copy()
__snake_case = None
return state
def __setstate__( self : str , a_ : Optional[int] ):
"""simple docstring"""
__snake_case = d
__snake_case = spm.SentencePieceProcessor()
self.sp_model.Load(self.vocab_file )
def A ( self : Tuple , a_ : Optional[int] , a_ : int=False ):
"""simple docstring"""
__snake_case = self.sp_model.EncodeAsPieces(a_ )
return pieces
def A ( self : Any , a_ : Optional[Any] ):
"""simple docstring"""
return self.sp_model.PieceToId(a_ )
def A ( self : Optional[Any] , a_ : List[str] ):
"""simple docstring"""
return self.sp_model.IdToPiece(a_ )
def A ( self : Optional[Any] , a_ : int ):
"""simple docstring"""
__snake_case = self.sp_model.decode_pieces(a_ )
return out_string
def A ( self : Union[str, Any] , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
__snake_case = [self.sep_token_id]
__snake_case = [self.cls_token_id]
if token_ids_a is None:
return cls + token_ids_a + sep
return cls + token_ids_a + sep + token_ids_a + sep
def A ( self : List[str] , a_ : List[int] , a_ : Optional[List[int]] = None , a_ : bool = False ):
"""simple docstring"""
if already_has_special_tokens:
if token_ids_a is not None:
raise ValueError(
"You should not supply a second sequence if the provided sequence of "
"ids is already formatted with special tokens for the model." )
return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]
if token_ids_a is not None:
return [1] + ([0] * len(a_ )) + [1] + ([0] * len(a_ )) + [1]
return [1] + ([0] * len(a_ )) + [1]
def A ( self : Tuple , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
__snake_case = [self.sep_token_id]
__snake_case = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def A ( self : List[Any] , a_ : str , a_ : Optional[str] = None ):
"""simple docstring"""
if not os.path.isdir(a_ ):
logger.error("Vocabulary path ({}) should be a directory".format(a_ ) )
return
__snake_case = 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_ ):
copyfile(self.vocab_file , a_ )
return (out_vocab_file,)
| 69 |
'''simple docstring'''
import os
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from huggingface_hub import HfFolder, delete_repo
from huggingface_hub.file_download import http_get
from requests.exceptions import HTTPError
from transformers import (
AlbertTokenizer,
AutoTokenizer,
BertTokenizer,
BertTokenizerFast,
GPTaTokenizerFast,
is_tokenizers_available,
)
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers
from transformers.tokenization_utils import Trie
sys.path.append(str(Path(__file__).parent.parent / '''utils'''))
from test_module.custom_tokenization import CustomTokenizer # noqa E402
if is_tokenizers_available():
from test_module.custom_tokenization_fast import CustomTokenizerFast
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = mock.Mock()
__snake_case = 500
__snake_case = {}
__snake_case = HTTPError
__snake_case = {}
# Download this model to make sure it's in the cache.
__snake_case = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" )
# Under the mock environment we get a 500 error when trying to reach the tokenizer.
with mock.patch("requests.Session.request" , return_value=a_ ) as mock_head:
__snake_case = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" )
# This check we did call the fake head request
mock_head.assert_called()
@require_tokenizers
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = mock.Mock()
__snake_case = 500
__snake_case = {}
__snake_case = HTTPError
__snake_case = {}
# Download this model to make sure it's in the cache.
__snake_case = GPTaTokenizerFast.from_pretrained("gpt2" )
# Under the mock environment we get a 500 error when trying to reach the tokenizer.
with mock.patch("requests.Session.request" , return_value=a_ ) as mock_head:
__snake_case = GPTaTokenizerFast.from_pretrained("gpt2" )
# This check we did call the fake head request
mock_head.assert_called()
def A ( self : Optional[Any] ):
"""simple docstring"""
try:
__snake_case = tempfile.mktemp()
with open(a_ , "wb" ) as f:
http_get("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" , a_ )
__snake_case = AlbertTokenizer.from_pretrained(a_ )
finally:
os.remove(a_ )
# Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in
# the current folder and have the right name.
if os.path.isfile("tokenizer.json" ):
# We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it.
return
try:
with open("tokenizer.json" , "wb" ) as f:
http_get("https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json" , a_ )
__snake_case = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" )
# The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000
self.assertEqual(tokenizer.vocab_size , 1_000 )
# Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file.
finally:
os.remove("tokenizer.json" )
def A ( self : str ):
"""simple docstring"""
__snake_case = AlbertTokenizer.from_pretrained("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" )
@is_staging_test
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
__SCREAMING_SNAKE_CASE = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""]
@classmethod
def A ( cls : List[Any] ):
"""simple docstring"""
__snake_case = TOKEN
HfFolder.save_token(a_ )
@classmethod
def A ( cls : List[Any] ):
"""simple docstring"""
try:
delete_repo(token=cls._token , repo_id="test-tokenizer" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="valid_org/test-tokenizer-org" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="test-dynamic-tokenizer" )
except HTTPError:
pass
def A ( self : int ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = BertTokenizer(a_ )
tokenizer.push_to_hub("test-tokenizer" , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
# Reset repo
delete_repo(token=self._token , repo_id="test-tokenizer" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(a_ , repo_id="test-tokenizer" , push_to_hub=a_ , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
def A ( self : int ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = BertTokenizer(a_ )
tokenizer.push_to_hub("valid_org/test-tokenizer-org" , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
# Reset repo
delete_repo(token=self._token , repo_id="valid_org/test-tokenizer-org" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(
a_ , repo_id="valid_org/test-tokenizer-org" , push_to_hub=a_ , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
@require_tokenizers
def A ( self : List[str] ):
"""simple docstring"""
CustomTokenizer.register_for_auto_class()
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = CustomTokenizer(a_ )
# No fast custom tokenizer
tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token )
__snake_case = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=a_ )
# Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module
self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizer" )
# Fast and slow custom tokenizer
CustomTokenizerFast.register_for_auto_class()
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = BertTokenizerFast.from_pretrained(a_ )
bert_tokenizer.save_pretrained(a_ )
__snake_case = CustomTokenizerFast.from_pretrained(a_ )
tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token )
__snake_case = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=a_ )
# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizerFast" )
__snake_case = AutoTokenizer.from_pretrained(
f'''{USER}/test-dynamic-tokenizer''' , use_fast=a_ , trust_remote_code=a_ )
# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizer" )
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def A ( self : Optional[int] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("Hello 友達" )
self.assertEqual(trie.data , {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}} )
trie.add("Hello" )
trie.data
self.assertEqual(trie.data , {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}} )
def A ( self : str ):
"""simple docstring"""
__snake_case = Trie()
self.assertEqual(trie.split("[CLS] This is a extra_id_100" ) , ["[CLS] This is a extra_id_100"] )
trie.add("[CLS]" )
trie.add("extra_id_1" )
trie.add("extra_id_100" )
self.assertEqual(trie.split("[CLS] This is a extra_id_100" ) , ["[CLS]", " This is a ", "extra_id_100"] )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("A" )
self.assertEqual(trie.split("ABC" ) , ["A", "BC"] )
self.assertEqual(trie.split("BCA" ) , ["BC", "A"] )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("TOKEN]" )
trie.add("[SPECIAL_TOKEN]" )
self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] )
def A ( self : str ):
"""simple docstring"""
__snake_case = Trie()
trie.add("A" )
trie.add("P" )
trie.add("[SPECIAL_TOKEN]" )
self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] )
def A ( self : Optional[int] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("AB" )
trie.add("B" )
trie.add("C" )
self.assertEqual(trie.split("ABC" ) , ["AB", "C"] )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = Trie()
trie.add("ABC" )
trie.add("B" )
trie.add("CD" )
self.assertEqual(trie.split("ABCD" ) , ["ABC", "D"] )
def A ( self : Any ):
"""simple docstring"""
__snake_case = Trie()
__snake_case = trie.cut_text("ABC" , [0, 0, 2, 1, 2, 3] )
self.assertEqual(a_ , ["AB", "C"] )
| 69 | 1 |
'''simple docstring'''
import itertools
import random
import unittest
import numpy as np
from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor
from transformers.testing_utils import require_torch, slow
from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin
a : int = random.Random()
def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : Optional[int]=1.0 , _UpperCAmelCase : List[Any]=None , _UpperCAmelCase : Union[str, Any]=None ) -> List[Any]:
if rng is None:
__snake_case = global_rng
__snake_case = []
for batch_idx in range(shape[0] ):
values.append([] )
for _ in range(shape[1] ):
values[-1].append(rng.random() * scale )
return values
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def __init__( self : List[str] , a_ : List[str] , a_ : Union[str, Any]=7 , a_ : List[str]=400 , a_ : Dict=2_000 , a_ : Optional[Any]=1 , a_ : List[str]=0.0 , a_ : List[str]=16_000 , a_ : str=True , a_ : Optional[int]=True , ):
"""simple docstring"""
__snake_case = parent
__snake_case = batch_size
__snake_case = min_seq_length
__snake_case = max_seq_length
__snake_case = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
__snake_case = feature_size
__snake_case = padding_value
__snake_case = sampling_rate
__snake_case = return_attention_mask
__snake_case = do_normalize
def A ( self : int ):
"""simple docstring"""
return {
"feature_size": self.feature_size,
"padding_value": self.padding_value,
"sampling_rate": self.sampling_rate,
"return_attention_mask": self.return_attention_mask,
"do_normalize": self.do_normalize,
}
def A ( self : Tuple , a_ : Any=False , a_ : Union[str, Any]=False ):
"""simple docstring"""
def _flatten(a_ : Optional[Any] ):
return list(itertools.chain(*a_ ) )
if equal_length:
__snake_case = floats_list((self.batch_size, self.max_seq_length) )
else:
# make sure that inputs increase in size
__snake_case = [
_flatten(floats_list((x, self.feature_size) ) )
for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff )
]
if numpify:
__snake_case = [np.asarray(a_ ) for x in speech_inputs]
return speech_inputs
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = WavaVecaFeatureExtractionTester(self )
def A ( self : Tuple , a_ : Optional[int] ):
"""simple docstring"""
self.assertTrue(np.all(np.mean(a_ , axis=0 ) < 1e-3 ) )
self.assertTrue(np.all(np.abs(np.var(a_ , axis=0 ) - 1 ) < 1e-3 ) )
def A ( self : Optional[int] ):
"""simple docstring"""
__snake_case = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
# create three inputs of length 800, 1000, and 1200
__snake_case = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )]
__snake_case = [np.asarray(a_ ) for speech_input in speech_inputs]
# Test not batched input
__snake_case = feat_extract(speech_inputs[0] , return_tensors="np" ).input_values
__snake_case = feat_extract(np_speech_inputs[0] , return_tensors="np" ).input_values
self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) )
# Test batched
__snake_case = feat_extract(a_ , return_tensors="np" ).input_values
__snake_case = feat_extract(a_ , return_tensors="np" ).input_values
for enc_seq_a, enc_seq_a in zip(a_ , a_ ):
self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) )
# Test 2-D numpy arrays are batched.
__snake_case = [floats_list((1, x) )[0] for x in (800, 800, 800)]
__snake_case = np.asarray(a_ )
__snake_case = feat_extract(a_ , return_tensors="np" ).input_values
__snake_case = feat_extract(a_ , return_tensors="np" ).input_values
for enc_seq_a, enc_seq_a in zip(a_ , a_ ):
self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
__snake_case = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )]
__snake_case = ["longest", "max_length", "do_not_pad"]
__snake_case = [None, 1_600, None]
for max_length, padding in zip(a_ , a_ ):
__snake_case = feat_extract(a_ , padding=a_ , max_length=a_ , return_tensors="np" )
__snake_case = processed.input_values
self._check_zero_mean_unit_variance(input_values[0][:800] )
self.assertTrue(input_values[0][800:].sum() < 1e-6 )
self._check_zero_mean_unit_variance(input_values[1][:1_000] )
self.assertTrue(input_values[0][1_000:].sum() < 1e-6 )
self._check_zero_mean_unit_variance(input_values[2][:1_200] )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
__snake_case = range(800 , 1_400 , 200 )
__snake_case = [floats_list((1, x) )[0] for x in lengths]
__snake_case = ["longest", "max_length", "do_not_pad"]
__snake_case = [None, 1_600, None]
for max_length, padding in zip(a_ , a_ ):
__snake_case = feat_extract(a_ , max_length=a_ , padding=a_ )
__snake_case = processed.input_values
self._check_zero_mean_unit_variance(input_values[0][:800] )
self._check_zero_mean_unit_variance(input_values[1][:1_000] )
self._check_zero_mean_unit_variance(input_values[2][:1_200] )
def A ( self : str ):
"""simple docstring"""
__snake_case = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
__snake_case = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )]
__snake_case = feat_extract(
a_ , truncation=a_ , max_length=1_000 , padding="max_length" , return_tensors="np" )
__snake_case = processed.input_values
self._check_zero_mean_unit_variance(input_values[0, :800] )
self._check_zero_mean_unit_variance(input_values[1] )
self._check_zero_mean_unit_variance(input_values[2] )
def A ( self : Optional[int] ):
"""simple docstring"""
__snake_case = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
__snake_case = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )]
__snake_case = feat_extract(
a_ , truncation=a_ , max_length=1_000 , padding="longest" , return_tensors="np" )
__snake_case = processed.input_values
self._check_zero_mean_unit_variance(input_values[0, :800] )
self._check_zero_mean_unit_variance(input_values[1, :1_000] )
self._check_zero_mean_unit_variance(input_values[2] )
# make sure that if max_length < longest -> then pad to max_length
self.assertTrue(input_values.shape == (3, 1_000) )
__snake_case = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )]
__snake_case = feat_extract(
a_ , truncation=a_ , max_length=2_000 , padding="longest" , return_tensors="np" )
__snake_case = processed.input_values
self._check_zero_mean_unit_variance(input_values[0, :800] )
self._check_zero_mean_unit_variance(input_values[1, :1_000] )
self._check_zero_mean_unit_variance(input_values[2] )
# make sure that if max_length > longest -> then pad to longest
self.assertTrue(input_values.shape == (3, 1_200) )
@require_torch
def A ( self : Tuple ):
"""simple docstring"""
import torch
__snake_case = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
__snake_case = np.random.rand(100 ).astype(np.floataa )
__snake_case = np_speech_inputs.tolist()
for inputs in [py_speech_inputs, np_speech_inputs]:
__snake_case = feature_extractor.pad([{"input_values": inputs}] , return_tensors="np" )
self.assertTrue(np_processed.input_values.dtype == np.floataa )
__snake_case = feature_extractor.pad([{"input_values": inputs}] , return_tensors="pt" )
self.assertTrue(pt_processed.input_values.dtype == torch.floataa )
@slow
@require_torch
def A ( self : str ):
"""simple docstring"""
for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST:
__snake_case = WavaVecaConfig.from_pretrained(a_ )
__snake_case = WavaVecaFeatureExtractor.from_pretrained(a_ )
# only "layer" feature extraction norm should make use of
# attention_mask
self.assertEqual(feat_extract.return_attention_mask , config.feat_extract_norm == "layer" )
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> int:
assert (
isinstance(_UpperCAmelCase , _UpperCAmelCase ) and number_of_steps > 0
), F'''number_of_steps needs to be positive integer, your input {number_of_steps}'''
if number_of_steps == 1:
return 1
__snake_case , __snake_case = 1, 1
for _ in range(number_of_steps - 1 ):
__snake_case , __snake_case = current + previous, current
return current
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 | 1 |
'''simple docstring'''
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile
from huggingface_hub import HfFolder, Repository, create_repo, delete_repo
from requests.exceptions import HTTPError
import transformers
from transformers import (
CONFIG_MAPPING,
FEATURE_EXTRACTOR_MAPPING,
PROCESSOR_MAPPING,
TOKENIZER_MAPPING,
AutoConfig,
AutoFeatureExtractor,
AutoProcessor,
AutoTokenizer,
BertTokenizer,
ProcessorMixin,
WavaVecaConfig,
WavaVecaFeatureExtractor,
WavaVecaProcessor,
)
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test
from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available
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
from test_module.custom_processing import CustomProcessor # noqa E402
from test_module.custom_tokenization import CustomTokenizer # noqa E402
a : Optional[Any] = get_tests_dir('''fixtures/dummy_feature_extractor_config.json''')
a : Optional[Any] = get_tests_dir('''fixtures/vocab.json''')
a : Optional[int] = get_tests_dir('''fixtures''')
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
__SCREAMING_SNAKE_CASE = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""]
def A ( self : Dict ):
"""simple docstring"""
__snake_case = 0
def A ( self : Optional[int] ):
"""simple docstring"""
__snake_case = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h" )
self.assertIsInstance(a_ , a_ )
def A ( self : Optional[Any] ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmpdirname:
__snake_case = WavaVecaConfig()
__snake_case = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h" )
# save in new folder
model_config.save_pretrained(a_ )
processor.save_pretrained(a_ )
__snake_case = AutoProcessor.from_pretrained(a_ )
self.assertIsInstance(a_ , a_ )
def A ( self : Union[str, Any] ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmpdirname:
# copy relevant files
copyfile(a_ , os.path.join(a_ , a_ ) )
copyfile(a_ , os.path.join(a_ , "vocab.json" ) )
__snake_case = AutoProcessor.from_pretrained(a_ )
self.assertIsInstance(a_ , a_ )
def A ( self : List[str] ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmpdirname:
__snake_case = WavaVecaFeatureExtractor()
__snake_case = AutoTokenizer.from_pretrained("facebook/wav2vec2-base-960h" )
__snake_case = WavaVecaProcessor(a_ , a_ )
# save in new folder
processor.save_pretrained(a_ )
# drop `processor_class` in tokenizer
with open(os.path.join(a_ , a_ ) , "r" ) as f:
__snake_case = json.load(a_ )
config_dict.pop("processor_class" )
with open(os.path.join(a_ , a_ ) , "w" ) as f:
f.write(json.dumps(a_ ) )
__snake_case = AutoProcessor.from_pretrained(a_ )
self.assertIsInstance(a_ , a_ )
def A ( self : Optional[Any] ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmpdirname:
__snake_case = WavaVecaFeatureExtractor()
__snake_case = AutoTokenizer.from_pretrained("facebook/wav2vec2-base-960h" )
__snake_case = WavaVecaProcessor(a_ , a_ )
# save in new folder
processor.save_pretrained(a_ )
# drop `processor_class` in feature extractor
with open(os.path.join(a_ , a_ ) , "r" ) as f:
__snake_case = json.load(a_ )
config_dict.pop("processor_class" )
with open(os.path.join(a_ , a_ ) , "w" ) as f:
f.write(json.dumps(a_ ) )
__snake_case = AutoProcessor.from_pretrained(a_ )
self.assertIsInstance(a_ , a_ )
def A ( self : Optional[Any] ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmpdirname:
__snake_case = WavaVecaConfig(processor_class="Wav2Vec2Processor" )
model_config.save_pretrained(a_ )
# copy relevant files
copyfile(a_ , os.path.join(a_ , "vocab.json" ) )
# create emtpy sample processor
with open(os.path.join(a_ , a_ ) , "w" ) as f:
f.write("{}" )
__snake_case = AutoProcessor.from_pretrained(a_ )
self.assertIsInstance(a_ , a_ )
def A ( self : List[Any] ):
"""simple docstring"""
with self.assertRaises(a_ ):
__snake_case = AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor" )
# If remote code is disabled, we can't load this config.
with self.assertRaises(a_ ):
__snake_case = AutoProcessor.from_pretrained(
"hf-internal-testing/test_dynamic_processor" , trust_remote_code=a_ )
__snake_case = AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor" , trust_remote_code=a_ )
self.assertTrue(processor.special_attribute_present )
self.assertEqual(processor.__class__.__name__ , "NewProcessor" )
__snake_case = processor.feature_extractor
self.assertTrue(feature_extractor.special_attribute_present )
self.assertEqual(feature_extractor.__class__.__name__ , "NewFeatureExtractor" )
__snake_case = processor.tokenizer
self.assertTrue(tokenizer.special_attribute_present )
if is_tokenizers_available():
self.assertEqual(tokenizer.__class__.__name__ , "NewTokenizerFast" )
# Test we can also load the slow version
__snake_case = AutoProcessor.from_pretrained(
"hf-internal-testing/test_dynamic_processor" , trust_remote_code=a_ , use_fast=a_ )
__snake_case = new_processor.tokenizer
self.assertTrue(new_tokenizer.special_attribute_present )
self.assertEqual(new_tokenizer.__class__.__name__ , "NewTokenizer" )
else:
self.assertEqual(tokenizer.__class__.__name__ , "NewTokenizer" )
def A ( self : List[str] ):
"""simple docstring"""
try:
AutoConfig.register("custom" , a_ )
AutoFeatureExtractor.register(a_ , a_ )
AutoTokenizer.register(a_ , slow_tokenizer_class=a_ )
AutoProcessor.register(a_ , a_ )
# Trying to register something existing in the Transformers library will raise an error
with self.assertRaises(a_ ):
AutoProcessor.register(a_ , a_ )
# Now that the config is registered, it can be used as any other config with the auto-API
__snake_case = CustomFeatureExtractor.from_pretrained(a_ )
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = CustomTokenizer(a_ )
__snake_case = CustomProcessor(a_ , a_ )
with tempfile.TemporaryDirectory() as tmp_dir:
processor.save_pretrained(a_ )
__snake_case = AutoProcessor.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]
if CustomConfig in TOKENIZER_MAPPING._extra_content:
del TOKENIZER_MAPPING._extra_content[CustomConfig]
if CustomConfig in PROCESSOR_MAPPING._extra_content:
del PROCESSOR_MAPPING._extra_content[CustomConfig]
def A ( self : Union[str, Any] ):
"""simple docstring"""
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = False
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = False
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = """AutoFeatureExtractor"""
__SCREAMING_SNAKE_CASE = """AutoTokenizer"""
__SCREAMING_SNAKE_CASE = False
try:
AutoConfig.register("custom" , a_ )
AutoFeatureExtractor.register(a_ , a_ )
AutoTokenizer.register(a_ , slow_tokenizer_class=a_ )
AutoProcessor.register(a_ , a_ )
# If remote code is not set, the default is to use local classes.
__snake_case = AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor" )
self.assertEqual(processor.__class__.__name__ , "NewProcessor" )
self.assertFalse(processor.special_attribute_present )
self.assertFalse(processor.feature_extractor.special_attribute_present )
self.assertFalse(processor.tokenizer.special_attribute_present )
# If remote code is disabled, we load the local ones.
__snake_case = AutoProcessor.from_pretrained(
"hf-internal-testing/test_dynamic_processor" , trust_remote_code=a_ )
self.assertEqual(processor.__class__.__name__ , "NewProcessor" )
self.assertFalse(processor.special_attribute_present )
self.assertFalse(processor.feature_extractor.special_attribute_present )
self.assertFalse(processor.tokenizer.special_attribute_present )
# If remote is enabled, we load from the Hub.
__snake_case = AutoProcessor.from_pretrained(
"hf-internal-testing/test_dynamic_processor" , trust_remote_code=a_ )
self.assertEqual(processor.__class__.__name__ , "NewProcessor" )
self.assertTrue(processor.special_attribute_present )
self.assertTrue(processor.feature_extractor.special_attribute_present )
self.assertTrue(processor.tokenizer.special_attribute_present )
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]
if CustomConfig in TOKENIZER_MAPPING._extra_content:
del TOKENIZER_MAPPING._extra_content[CustomConfig]
if CustomConfig in PROCESSOR_MAPPING._extra_content:
del PROCESSOR_MAPPING._extra_content[CustomConfig]
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = AutoProcessor.from_pretrained("hf-internal-testing/tiny-random-bert" )
self.assertEqual(processor.__class__.__name__ , "BertTokenizerFast" )
def A ( self : str ):
"""simple docstring"""
__snake_case = AutoProcessor.from_pretrained("hf-internal-testing/tiny-random-convnext" )
self.assertEqual(processor.__class__.__name__ , "ConvNextImageProcessor" )
@is_staging_test
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
__SCREAMING_SNAKE_CASE = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""]
@classmethod
def A ( cls : Optional[Any] ):
"""simple docstring"""
__snake_case = TOKEN
HfFolder.save_token(a_ )
@classmethod
def A ( cls : str ):
"""simple docstring"""
try:
delete_repo(token=cls._token , repo_id="test-processor" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="valid_org/test-processor-org" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="test-dynamic-processor" )
except HTTPError:
pass
def A ( self : List[str] ):
"""simple docstring"""
__snake_case = WavaVecaProcessor.from_pretrained(a_ )
with tempfile.TemporaryDirectory() as tmp_dir:
processor.save_pretrained(
os.path.join(a_ , "test-processor" ) , push_to_hub=a_ , use_auth_token=self._token )
__snake_case = WavaVecaProcessor.from_pretrained(f'''{USER}/test-processor''' )
for k, v in processor.feature_extractor.__dict__.items():
self.assertEqual(a_ , getattr(new_processor.feature_extractor , a_ ) )
self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = WavaVecaProcessor.from_pretrained(a_ )
with tempfile.TemporaryDirectory() as tmp_dir:
processor.save_pretrained(
os.path.join(a_ , "test-processor-org" ) , push_to_hub=a_ , use_auth_token=self._token , organization="valid_org" , )
__snake_case = WavaVecaProcessor.from_pretrained("valid_org/test-processor-org" )
for k, v in processor.feature_extractor.__dict__.items():
self.assertEqual(a_ , getattr(new_processor.feature_extractor , a_ ) )
self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() )
def A ( self : Any ):
"""simple docstring"""
CustomFeatureExtractor.register_for_auto_class()
CustomTokenizer.register_for_auto_class()
CustomProcessor.register_for_auto_class()
__snake_case = CustomFeatureExtractor.from_pretrained(a_ )
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = CustomTokenizer(a_ )
__snake_case = CustomProcessor(a_ , a_ )
with tempfile.TemporaryDirectory() as tmp_dir:
create_repo(f'''{USER}/test-dynamic-processor''' , token=self._token )
__snake_case = Repository(a_ , clone_from=f'''{USER}/test-dynamic-processor''' , token=self._token )
processor.save_pretrained(a_ )
# This has added the proper auto_map field to the feature extractor config
self.assertDictEqual(
processor.feature_extractor.auto_map , {
"AutoFeatureExtractor": "custom_feature_extraction.CustomFeatureExtractor",
"AutoProcessor": "custom_processing.CustomProcessor",
} , )
# This has added the proper auto_map field to the tokenizer config
with open(os.path.join(a_ , "tokenizer_config.json" ) ) as f:
__snake_case = json.load(a_ )
self.assertDictEqual(
tokenizer_config["auto_map"] , {
"AutoTokenizer": ["custom_tokenization.CustomTokenizer", None],
"AutoProcessor": "custom_processing.CustomProcessor",
} , )
# The code has been copied from fixtures
self.assertTrue(os.path.isfile(os.path.join(a_ , "custom_feature_extraction.py" ) ) )
self.assertTrue(os.path.isfile(os.path.join(a_ , "custom_tokenization.py" ) ) )
self.assertTrue(os.path.isfile(os.path.join(a_ , "custom_processing.py" ) ) )
repo.push_to_hub()
__snake_case = AutoProcessor.from_pretrained(f'''{USER}/test-dynamic-processor''' , trust_remote_code=a_ )
# Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module
self.assertEqual(new_processor.__class__.__name__ , "CustomProcessor" )
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> str:
return " ".join(
"".join(word[::-1] ) if len(_UpperCAmelCase ) > 4 else word for word in sentence.split() )
if __name__ == "__main__":
import doctest
doctest.testmod()
print(reverse_long_words('''Hey wollef sroirraw'''))
| 69 | 1 |
'''simple docstring'''
import math
def __UpperCAmelCase ( _UpperCAmelCase : list , _UpperCAmelCase : int = 0 , _UpperCAmelCase : int = 0 ) -> list:
__snake_case = end or len(_UpperCAmelCase )
for i in range(_UpperCAmelCase , _UpperCAmelCase ):
__snake_case = i
__snake_case = array[i]
while temp_index != start and temp_index_value < array[temp_index - 1]:
__snake_case = array[temp_index - 1]
temp_index -= 1
__snake_case = temp_index_value
return array
def __UpperCAmelCase ( _UpperCAmelCase : list , _UpperCAmelCase : int , _UpperCAmelCase : int ) -> None: # Max Heap
__snake_case = index
__snake_case = 2 * index + 1 # Left Node
__snake_case = 2 * index + 2 # Right Node
if left_index < heap_size and array[largest] < array[left_index]:
__snake_case = left_index
if right_index < heap_size and array[largest] < array[right_index]:
__snake_case = right_index
if largest != index:
__snake_case , __snake_case = array[largest], array[index]
heapify(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
def __UpperCAmelCase ( _UpperCAmelCase : list ) -> list:
__snake_case = len(_UpperCAmelCase )
for i in range(n // 2 , -1 , -1 ):
heapify(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
for i in range(n - 1 , 0 , -1 ):
__snake_case , __snake_case = array[0], array[i]
heapify(_UpperCAmelCase , 0 , _UpperCAmelCase )
return array
def __UpperCAmelCase ( _UpperCAmelCase : list , _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : int ) -> int:
if (array[first_index] > array[middle_index]) != (
array[first_index] > array[last_index]
):
return array[first_index]
elif (array[middle_index] > array[first_index]) != (
array[middle_index] > array[last_index]
):
return array[middle_index]
else:
return array[last_index]
def __UpperCAmelCase ( _UpperCAmelCase : list , _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : int ) -> int:
__snake_case = low
__snake_case = high
while True:
while array[i] < pivot:
i += 1
j -= 1
while pivot < array[j]:
j -= 1
if i >= j:
return i
__snake_case , __snake_case = array[j], array[i]
i += 1
def __UpperCAmelCase ( _UpperCAmelCase : list ) -> list:
if len(_UpperCAmelCase ) == 0:
return array
__snake_case = 2 * math.ceil(math.loga(len(_UpperCAmelCase ) ) )
__snake_case = 16
return intro_sort(_UpperCAmelCase , 0 , len(_UpperCAmelCase ) , _UpperCAmelCase , _UpperCAmelCase )
def __UpperCAmelCase ( _UpperCAmelCase : list , _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : int ) -> list:
while end - start > size_threshold:
if max_depth == 0:
return heap_sort(_UpperCAmelCase )
max_depth -= 1
__snake_case = median_of_a(_UpperCAmelCase , _UpperCAmelCase , start + ((end - start) // 2) + 1 , end - 1 )
__snake_case = partition(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
intro_sort(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
__snake_case = p
return insertion_sort(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
if __name__ == "__main__":
import doctest
doctest.testmod()
a : Dict = input('''Enter numbers separated by a comma : ''').strip()
a : str = [float(item) for item in user_input.split(''',''')]
print(sort(unsorted))
| 69 |
'''simple docstring'''
import unittest
from transformers import MPNetConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
MPNetForMaskedLM,
MPNetForMultipleChoice,
MPNetForQuestionAnswering,
MPNetForSequenceClassification,
MPNetForTokenClassification,
MPNetModel,
)
class SCREAMING_SNAKE_CASE__ :
def __init__( self : str , a_ : Any , a_ : Union[str, Any]=13 , a_ : Any=7 , a_ : Any=True , a_ : Dict=True , a_ : Union[str, Any]=False , a_ : Tuple=True , a_ : str=99 , a_ : Tuple=64 , a_ : Tuple=5 , a_ : Union[str, Any]=4 , a_ : Dict=64 , a_ : Union[str, Any]="gelu" , a_ : Dict=0.1 , a_ : List[str]=0.1 , a_ : Dict=512 , a_ : Tuple=16 , a_ : str=2 , a_ : Any=0.02 , a_ : List[Any]=3 , a_ : Tuple=4 , a_ : Optional[int]=None , ):
"""simple docstring"""
__snake_case = parent
__snake_case = batch_size
__snake_case = seq_length
__snake_case = is_training
__snake_case = use_input_mask
__snake_case = use_token_type_ids
__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_act
__snake_case = hidden_dropout_prob
__snake_case = attention_probs_dropout_prob
__snake_case = max_position_embeddings
__snake_case = type_vocab_size
__snake_case = type_sequence_label_size
__snake_case = initializer_range
__snake_case = num_labels
__snake_case = num_choices
__snake_case = scope
def A ( self : int ):
"""simple docstring"""
return MPNetConfig.from_pretrained("microsoft/mpnet-base" )
def A ( self : str ):
"""simple docstring"""
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__snake_case = None
if self.use_input_mask:
__snake_case = random_attention_mask([self.batch_size, self.seq_length] )
__snake_case = None
__snake_case = None
__snake_case = None
if self.use_labels:
__snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__snake_case = ids_tensor([self.batch_size] , self.num_choices )
__snake_case = self.get_config()
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
def A ( self : List[str] ):
"""simple docstring"""
return MPNetConfig(
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 , initializer_range=self.initializer_range , )
def A ( self : Tuple , a_ : int , a_ : str , a_ : Optional[int] , a_ : List[Any] , a_ : str , a_ : Optional[Any] ):
"""simple docstring"""
__snake_case = MPNetModel(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , a_ )
__snake_case = model(a_ )
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 A ( self : Any , a_ : int , a_ : Tuple , a_ : str , a_ : int , a_ : str , a_ : List[Any] ):
"""simple docstring"""
__snake_case = MPNetForQuestionAnswering(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(
a_ , attention_mask=a_ , start_positions=a_ , end_positions=a_ , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def A ( self : Any , a_ : Any , a_ : int , a_ : Union[str, Any] , a_ : Dict , a_ : Optional[Any] , a_ : Any ):
"""simple docstring"""
__snake_case = self.num_labels
__snake_case = MPNetForSequenceClassification(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def A ( self : Optional[Any] , a_ : Any , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : List[Any] , a_ : List[Any] ):
"""simple docstring"""
__snake_case = self.num_choices
__snake_case = MPNetForMultipleChoice(config=a_ )
model.to(a_ )
model.eval()
__snake_case = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__snake_case = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__snake_case = model(
a_ , attention_mask=a_ , labels=a_ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def A ( self : Dict , a_ : List[str] , a_ : str , a_ : Union[str, Any] , a_ : str , a_ : Optional[int] , a_ : Optional[Any] ):
"""simple docstring"""
__snake_case = self.num_labels
__snake_case = MPNetForTokenClassification(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.prepare_config_and_inputs()
((__snake_case) , (__snake_case) , (__snake_case) , (__snake_case) , (__snake_case) , (__snake_case)) = config_and_inputs
__snake_case = {"input_ids": input_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = (
(
MPNetForMaskedLM,
MPNetForMultipleChoice,
MPNetForQuestionAnswering,
MPNetForSequenceClassification,
MPNetForTokenClassification,
MPNetModel,
)
if is_torch_available()
else ()
)
__SCREAMING_SNAKE_CASE = (
{
"""feature-extraction""": MPNetModel,
"""fill-mask""": MPNetForMaskedLM,
"""question-answering""": MPNetForQuestionAnswering,
"""text-classification""": MPNetForSequenceClassification,
"""token-classification""": MPNetForTokenClassification,
"""zero-shot""": MPNetForSequenceClassification,
}
if is_torch_available()
else {}
)
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = True
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = MPNetModelTester(self )
__snake_case = ConfigTester(self , config_class=a_ , hidden_size=37 )
def A ( self : List[Any] ):
"""simple docstring"""
self.config_tester.run_common_tests()
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_model(*a_ )
def A ( self : Dict ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_sequence_classification(*a_ )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_multiple_choice(*a_ )
def A ( self : int ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_token_classification(*a_ )
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_question_answering(*a_ )
@require_torch
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
@slow
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = MPNetModel.from_pretrained("microsoft/mpnet-base" )
__snake_case = torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] )
__snake_case = model(a_ )[0]
__snake_case = torch.Size((1, 11, 768) )
self.assertEqual(output.shape , a_ )
__snake_case = torch.tensor(
[[[-0.0550, 0.1943, -0.0740], [-0.0562, 0.2211, -0.0579], [-0.0437, 0.3337, -0.0641]]] )
# compare the actual values for a slice.
self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) )
| 69 | 1 |
'''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
a : Tuple = get_tests_dir('''fixtures''')
a : Dict = get_tests_dir('''fixtures/dummy_feature_extractor_config.json''')
a : int = get_tests_dir('''fixtures/dummy-config.json''')
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = 0
def A ( self : str ):
"""simple docstring"""
__snake_case = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h" )
self.assertIsInstance(a_ , a_ )
def A ( self : str ):
"""simple docstring"""
__snake_case = AutoFeatureExtractor.from_pretrained(a_ )
self.assertIsInstance(a_ , a_ )
def A ( self : str ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmpdirname:
__snake_case = WavaVecaConfig()
# remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
__snake_case = AutoFeatureExtractor.from_pretrained(a_ ).to_dict()
config_dict.pop("feature_extractor_type" )
__snake_case = WavaVecaFeatureExtractor(**a_ )
# save in new folder
model_config.save_pretrained(a_ )
config.save_pretrained(a_ )
__snake_case = AutoFeatureExtractor.from_pretrained(a_ )
# make sure private variable is not incorrectly saved
__snake_case = json.loads(config.to_json_string() )
self.assertTrue("_processor_class" not in dict_as_saved )
self.assertIsInstance(a_ , a_ )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = AutoFeatureExtractor.from_pretrained(a_ )
self.assertIsInstance(a_ , a_ )
def A ( self : Optional[Any] ):
"""simple docstring"""
with self.assertRaisesRegex(
a_ , "bert-base is not a local folder and is not a valid model identifier" ):
__snake_case = AutoFeatureExtractor.from_pretrained("bert-base" )
def A ( self : Dict ):
"""simple docstring"""
with self.assertRaisesRegex(
a_ , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ):
__snake_case = AutoFeatureExtractor.from_pretrained(a_ , revision="aaaaaa" )
def A ( self : Tuple ):
"""simple docstring"""
with self.assertRaisesRegex(
a_ , "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json." , ):
__snake_case = AutoFeatureExtractor.from_pretrained("hf-internal-testing/config-no-model" )
def A ( self : Tuple ):
"""simple docstring"""
with self.assertRaises(a_ ):
__snake_case = 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_ ):
__snake_case = AutoFeatureExtractor.from_pretrained(
"hf-internal-testing/test_dynamic_feature_extractor" , trust_remote_code=a_ )
__snake_case = 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_ )
__snake_case = AutoFeatureExtractor.from_pretrained(a_ , trust_remote_code=a_ )
self.assertEqual(reloaded_feature_extractor.__class__.__name__ , "NewFeatureExtractor" )
def A ( self : int ):
"""simple docstring"""
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
__snake_case = CustomFeatureExtractor.from_pretrained(a_ )
with tempfile.TemporaryDirectory() as tmp_dir:
feature_extractor.save_pretrained(a_ )
__snake_case = 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 A ( self : Dict ):
"""simple docstring"""
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = True
try:
AutoConfig.register("custom" , a_ )
AutoFeatureExtractor.register(a_ , a_ )
# If remote code is not set, the default is to use local
__snake_case = 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.
__snake_case = 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
__snake_case = 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]
| 69 |
'''simple docstring'''
# Logistic Regression from scratch
# In[62]:
# In[63]:
# importing all the required libraries
import numpy as np
from matplotlib import pyplot as plt
from sklearn import datasets
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> Optional[int]:
return 1 / (1 + np.exp(-z ))
def __UpperCAmelCase ( _UpperCAmelCase : Tuple , _UpperCAmelCase : Dict ) -> List[str]:
return (-y * np.log(_UpperCAmelCase ) - (1 - y) * np.log(1 - h )).mean()
def __UpperCAmelCase ( _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : List[Any] ) -> Optional[Any]:
__snake_case = np.dot(_UpperCAmelCase , _UpperCAmelCase )
return np.sum(y * scores - np.log(1 + np.exp(_UpperCAmelCase ) ) )
def __UpperCAmelCase ( _UpperCAmelCase : List[Any] , _UpperCAmelCase : str , _UpperCAmelCase : Dict , _UpperCAmelCase : List[str]=7_00_00 ) -> Union[str, Any]:
__snake_case = np.zeros(x.shape[1] )
for iterations in range(_UpperCAmelCase ):
__snake_case = np.dot(_UpperCAmelCase , _UpperCAmelCase )
__snake_case = sigmoid_function(_UpperCAmelCase )
__snake_case = np.dot(x.T , h - y ) / y.size
__snake_case = theta - alpha * gradient # updating the weights
__snake_case = np.dot(_UpperCAmelCase , _UpperCAmelCase )
__snake_case = sigmoid_function(_UpperCAmelCase )
__snake_case = cost_function(_UpperCAmelCase , _UpperCAmelCase )
if iterations % 1_00 == 0:
print(F'''loss: {j} \t''' ) # printing the loss after every 100 iterations
return theta
# In[68]:
if __name__ == "__main__":
a : int = datasets.load_iris()
a : int = iris.data[:, :2]
a : Optional[Any] = (iris.target != 0) * 1
a : Tuple = 0.1
a : List[str] = logistic_reg(alpha, x, y, max_iterations=70_000)
print('''theta: ''', theta) # printing the theta i.e our weights vector
def __UpperCAmelCase ( _UpperCAmelCase : Optional[int] ) -> Union[str, Any]:
return sigmoid_function(
np.dot(_UpperCAmelCase , _UpperCAmelCase ) ) # predicting the value of probability from the logistic regression algorithm
plt.figure(figsize=(10, 6))
plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color='''b''', label='''0''')
plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color='''r''', label='''1''')
((a) , (a)) : Any = (x[:, 0].min(), x[:, 0].max())
((a) , (a)) : Any = (x[:, 1].min(), x[:, 1].max())
((a) , (a)) : Any = np.meshgrid(np.linspace(xa_min, xa_max), np.linspace(xa_min, xa_max))
a : Optional[Any] = np.c_[xxa.ravel(), xxa.ravel()]
a : List[Any] = predict_prob(grid).reshape(xxa.shape)
plt.contour(xxa, xxa, probs, [0.5], linewidths=1, colors='''black''')
plt.legend()
plt.show()
| 69 | 1 |
'''simple docstring'''
# Logistic Regression from scratch
# In[62]:
# In[63]:
# importing all the required libraries
import numpy as np
from matplotlib import pyplot as plt
from sklearn import datasets
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> Optional[int]:
return 1 / (1 + np.exp(-z ))
def __UpperCAmelCase ( _UpperCAmelCase : Tuple , _UpperCAmelCase : Dict ) -> List[str]:
return (-y * np.log(_UpperCAmelCase ) - (1 - y) * np.log(1 - h )).mean()
def __UpperCAmelCase ( _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : List[Any] ) -> Optional[Any]:
__snake_case = np.dot(_UpperCAmelCase , _UpperCAmelCase )
return np.sum(y * scores - np.log(1 + np.exp(_UpperCAmelCase ) ) )
def __UpperCAmelCase ( _UpperCAmelCase : List[Any] , _UpperCAmelCase : str , _UpperCAmelCase : Dict , _UpperCAmelCase : List[str]=7_00_00 ) -> Union[str, Any]:
__snake_case = np.zeros(x.shape[1] )
for iterations in range(_UpperCAmelCase ):
__snake_case = np.dot(_UpperCAmelCase , _UpperCAmelCase )
__snake_case = sigmoid_function(_UpperCAmelCase )
__snake_case = np.dot(x.T , h - y ) / y.size
__snake_case = theta - alpha * gradient # updating the weights
__snake_case = np.dot(_UpperCAmelCase , _UpperCAmelCase )
__snake_case = sigmoid_function(_UpperCAmelCase )
__snake_case = cost_function(_UpperCAmelCase , _UpperCAmelCase )
if iterations % 1_00 == 0:
print(F'''loss: {j} \t''' ) # printing the loss after every 100 iterations
return theta
# In[68]:
if __name__ == "__main__":
a : int = datasets.load_iris()
a : int = iris.data[:, :2]
a : Optional[Any] = (iris.target != 0) * 1
a : Tuple = 0.1
a : List[str] = logistic_reg(alpha, x, y, max_iterations=70_000)
print('''theta: ''', theta) # printing the theta i.e our weights vector
def __UpperCAmelCase ( _UpperCAmelCase : Optional[int] ) -> Union[str, Any]:
return sigmoid_function(
np.dot(_UpperCAmelCase , _UpperCAmelCase ) ) # predicting the value of probability from the logistic regression algorithm
plt.figure(figsize=(10, 6))
plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color='''b''', label='''0''')
plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color='''r''', label='''1''')
((a) , (a)) : Any = (x[:, 0].min(), x[:, 0].max())
((a) , (a)) : Any = (x[:, 1].min(), x[:, 1].max())
((a) , (a)) : Any = np.meshgrid(np.linspace(xa_min, xa_max), np.linspace(xa_min, xa_max))
a : Optional[Any] = np.c_[xxa.ravel(), xxa.ravel()]
a : List[Any] = predict_prob(grid).reshape(xxa.shape)
plt.contour(xxa, xxa, probs, [0.5], linewidths=1, colors='''black''')
plt.legend()
plt.show()
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> bool:
return number & 1 == 0
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 | 1 |
'''simple docstring'''
from math import factorial
def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : float ) -> float:
if successes > trials:
raise ValueError("successes must be lower or equal to trials" )
if trials < 0 or successes < 0:
raise ValueError("the function is defined for non-negative integers" )
if not isinstance(_UpperCAmelCase , _UpperCAmelCase ) or not isinstance(_UpperCAmelCase , _UpperCAmelCase ):
raise ValueError("the function is defined for non-negative integers" )
if not 0 < prob < 1:
raise ValueError("prob has to be in range of 1 - 0" )
__snake_case = (prob**successes) * ((1 - prob) ** (trials - successes))
# Calculate the binomial coefficient: n! / k!(n-k)!
__snake_case = float(factorial(_UpperCAmelCase ) )
coefficient /= factorial(_UpperCAmelCase ) * factorial(trials - successes )
return probability * coefficient
if __name__ == "__main__":
from doctest import testmod
testmod()
print('''Probability of 2 successes out of 4 trails''')
print('''with probability of 0.75 is:''', end=''' ''')
print(binomial_distribution(2, 4, 0.75))
| 69 |
'''simple docstring'''
import argparse
from pathlib import Path
import torch
from transformers import OPTConfig, OPTModel
from transformers.utils import logging
logging.set_verbosity_info()
a : List[str] = logging.get_logger(__name__)
def __UpperCAmelCase ( _UpperCAmelCase : Dict ) -> Union[str, Any]:
__snake_case = torch.load(_UpperCAmelCase , map_location="cpu" )
if "model" in sd.keys():
__snake_case = torch.load(_UpperCAmelCase , map_location="cpu" )["model"]
# pop unnecessary weights
__snake_case = [
"decoder.version",
"decoder.output_projection.weight",
]
for key in keys_to_delete:
if key in sd:
sd.pop(_UpperCAmelCase )
__snake_case = {
"decoder.project_in_dim.weight": "decoder.project_in.weight",
"decoder.project_out_dim.weight": "decoder.project_out.weight",
"decoder.layer_norm.weight": "decoder.final_layer_norm.weight",
"decoder.layer_norm.bias": "decoder.final_layer_norm.bias",
}
for old_key, new_key in keys_to_rename.items():
if old_key in sd:
__snake_case = sd.pop(_UpperCAmelCase )
__snake_case = list(sd.keys() )
for key in keys:
if ".qkv_proj." in key:
__snake_case = sd[key]
# We split QKV in separate Q,K,V
__snake_case = key.replace(".qkv_proj." , ".q_proj." )
__snake_case = key.replace(".qkv_proj." , ".k_proj." )
__snake_case = key.replace(".qkv_proj." , ".v_proj." )
__snake_case = value.shape[0]
assert depth % 3 == 0
# `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming:
# https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97
__snake_case , __snake_case , __snake_case = torch.split(_UpperCAmelCase , depth // 3 , dim=0 )
__snake_case = q
__snake_case = k
__snake_case = v
del sd[key]
return sd
@torch.no_grad()
def __UpperCAmelCase ( _UpperCAmelCase : List[str] , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : int=None ) -> Any:
__snake_case = load_checkpoint(_UpperCAmelCase )
if config is not None:
__snake_case = OPTConfig.from_pretrained(_UpperCAmelCase )
else:
__snake_case = OPTConfig()
__snake_case = OPTModel(_UpperCAmelCase ).half().eval()
model.load_state_dict(_UpperCAmelCase )
# Check results
Path(_UpperCAmelCase ).mkdir(exist_ok=_UpperCAmelCase )
model.save_pretrained(_UpperCAmelCase )
if __name__ == "__main__":
a : int = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--fairseq_path''',
type=str,
help=(
'''path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:'''
''' https://huggingface.co/models?other=opt_metasq'''
),
)
parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
parser.add_argument('''--hf_config''', default=None, type=str, help='''Define HF config.''')
a : Optional[int] = parser.parse_args()
convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
| 69 | 1 |
'''simple docstring'''
import doctest
import logging
import os
import unittest
from pathlib import Path
from typing import List, Union
import transformers
from transformers.testing_utils import require_tf, require_torch, slow
a : Tuple = logging.getLogger()
@unittest.skip("""Temporarily disable the doc tests.""" )
@require_torch
@require_tf
@slow
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def A ( self : List[str] , a_ : Path , a_ : Union[str, None] = None , a_ : Union[List[str], None] = None , a_ : Union[str, List[str], None] = None , a_ : bool = True , ):
"""simple docstring"""
__snake_case = [file for file in os.listdir(a_ ) if os.path.isfile(os.path.join(a_ , a_ ) )]
if identifier is not None:
__snake_case = [file for file in files if identifier in file]
if n_identifier is not None:
if isinstance(a_ , a_ ):
for n_ in n_identifier:
__snake_case = [file for file in files if n_ not in file]
else:
__snake_case = [file for file in files if n_identifier not in file]
__snake_case = ignore_files or []
ignore_files.append("__init__.py" )
__snake_case = [file for file in files if file not in ignore_files]
for file in files:
# Open all files
print("Testing" , a_ )
if only_modules:
__snake_case = file.split("." )[0]
try:
__snake_case = getattr(a_ , a_ )
__snake_case = doctest.DocTestSuite(a_ )
__snake_case = unittest.TextTestRunner().run(a_ )
self.assertIs(len(result.failures ) , 0 )
except AttributeError:
logger.info(f'''{module_identifier} is not a module.''' )
else:
__snake_case = doctest.testfile(str(".." / directory / file ) , optionflags=doctest.ELLIPSIS )
self.assertIs(result.failed , 0 )
def A ( self : int ):
"""simple docstring"""
__snake_case = Path("src/transformers" )
__snake_case = "modeling"
__snake_case = [
"modeling_ctrl.py",
"modeling_tf_ctrl.py",
]
self.analyze_directory(a_ , identifier=a_ , ignore_files=a_ )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = Path("src/transformers" )
__snake_case = "tokenization"
self.analyze_directory(a_ , identifier=a_ )
def A ( self : Any ):
"""simple docstring"""
__snake_case = Path("src/transformers" )
__snake_case = "configuration"
self.analyze_directory(a_ , identifier=a_ )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = Path("src/transformers" )
__snake_case = ["configuration", "modeling", "tokenization"]
self.analyze_directory(a_ , n_identifier=a_ )
def A ( self : Optional[int] ):
"""simple docstring"""
__snake_case = Path("docs/source" )
__snake_case = ["favicon.ico"]
self.analyze_directory(a_ , ignore_files=a_ , only_modules=a_ )
| 69 |
'''simple docstring'''
from typing import List, Optional
from ...configuration_utils import PretrainedConfig
from ...utils import logging
a : List[str] = logging.get_logger(__name__)
a : Tuple = {
'''huggingface/autoformer-tourism-monthly''': '''https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json''',
}
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = """autoformer"""
__SCREAMING_SNAKE_CASE = {
"""hidden_size""": """d_model""",
"""num_attention_heads""": """encoder_attention_heads""",
"""num_hidden_layers""": """encoder_layers""",
}
def __init__( self : List[Any] , a_ : Optional[int] = None , a_ : Optional[int] = None , a_ : str = "student_t" , a_ : str = "nll" , a_ : int = 1 , a_ : List[int] = [1, 2, 3, 4, 5, 6, 7] , a_ : bool = True , a_ : int = 0 , a_ : int = 0 , a_ : int = 0 , a_ : int = 0 , a_ : Optional[List[int]] = None , a_ : Optional[List[int]] = None , a_ : int = 64 , a_ : int = 2 , a_ : int = 2 , a_ : int = 2 , a_ : int = 2 , a_ : int = 32 , a_ : int = 32 , a_ : str = "gelu" , a_ : float = 0.1 , a_ : float = 0.1 , a_ : float = 0.1 , a_ : float = 0.1 , a_ : float = 0.1 , a_ : int = 100 , a_ : float = 0.02 , a_ : bool = True , a_ : Union[str, Any]=True , a_ : int = 10 , a_ : int = 25 , a_ : int = 3 , **a_ : Tuple , ):
"""simple docstring"""
__snake_case = prediction_length
__snake_case = context_length if context_length is not None else prediction_length
__snake_case = distribution_output
__snake_case = loss
__snake_case = input_size
__snake_case = num_time_features
__snake_case = lags_sequence
__snake_case = scaling
__snake_case = num_dynamic_real_features
__snake_case = num_static_real_features
__snake_case = num_static_categorical_features
if cardinality is not None 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`" )
__snake_case = cardinality
else:
__snake_case = [0]
if embedding_dimension is not None 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`" )
__snake_case = embedding_dimension
else:
__snake_case = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality]
__snake_case = num_parallel_samples
# Transformer architecture configuration
__snake_case = input_size * len(self.lags_sequence ) + self._number_of_features
__snake_case = d_model
__snake_case = encoder_attention_heads
__snake_case = decoder_attention_heads
__snake_case = encoder_ffn_dim
__snake_case = decoder_ffn_dim
__snake_case = encoder_layers
__snake_case = decoder_layers
__snake_case = dropout
__snake_case = attention_dropout
__snake_case = activation_dropout
__snake_case = encoder_layerdrop
__snake_case = decoder_layerdrop
__snake_case = activation_function
__snake_case = init_std
__snake_case = use_cache
# Autoformer
__snake_case = label_length
__snake_case = moving_average
__snake_case = autocorrelation_factor
super().__init__(is_encoder_decoder=a_ , **a_ )
@property
def A ( self : Optional[int] ):
"""simple docstring"""
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
)
| 69 | 1 |
'''simple docstring'''
from typing import Optional
from .. import Features, NamedSplit
from ..packaged_modules.text.text import Text
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def __init__( self : int , a_ : NestedDataStructureLike[PathLike] , a_ : Optional[NamedSplit] = None , a_ : Optional[Features] = None , a_ : str = None , a_ : bool = False , a_ : bool = False , a_ : Optional[int] = None , **a_ : List[str] , ):
"""simple docstring"""
super().__init__(
a_ , split=a_ , features=a_ , cache_dir=a_ , keep_in_memory=a_ , streaming=a_ , num_proc=a_ , **a_ , )
__snake_case = path_or_paths if isinstance(a_ , a_ ) else {self.split: path_or_paths}
__snake_case = Text(
cache_dir=a_ , data_files=a_ , features=a_ , **a_ , )
def A ( self : str ):
"""simple docstring"""
if self.streaming:
__snake_case = self.builder.as_streaming_dataset(split=self.split )
# Build regular (map-style) dataset
else:
__snake_case = None
__snake_case = None
__snake_case = None
__snake_case = None
self.builder.download_and_prepare(
download_config=a_ , download_mode=a_ , verification_mode=a_ , base_path=a_ , num_proc=self.num_proc , )
__snake_case = self.builder.as_dataset(
split=self.split , verification_mode=a_ , in_memory=self.keep_in_memory )
return dataset
| 69 |
'''simple docstring'''
import unittest
from transformers import GPTSwaTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
a : List[Any] = get_tests_dir('''fixtures/test_sentencepiece_with_bytefallback.model''')
@require_sentencepiece
@require_tokenizers
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = GPTSwaTokenizer
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = True
__SCREAMING_SNAKE_CASE = False
def A ( self : int ):
"""simple docstring"""
super().setUp()
# We have a SentencePiece fixture for testing
__snake_case = GPTSwaTokenizer(a_ , eos_token="<unk>" , bos_token="<unk>" , pad_token="<unk>" )
tokenizer.save_pretrained(self.tmpdirname )
def A ( self : str , a_ : List[Any] ):
"""simple docstring"""
__snake_case = "This is a test"
__snake_case = "This is a test"
return input_text, output_text
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = "<s>"
__snake_case = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , "<unk>" )
self.assertEqual(vocab_keys[1] , "<s>" )
self.assertEqual(vocab_keys[-1] , "j" )
self.assertEqual(len(a_ ) , 2_000 )
def A ( self : Optional[int] ):
"""simple docstring"""
self.assertEqual(self.get_tokenizer().vocab_size , 2_000 )
def A ( self : Dict ):
"""simple docstring"""
__snake_case = GPTSwaTokenizer(a_ )
__snake_case = tokenizer.tokenize("This is a test" )
self.assertListEqual(a_ , ["▁This", "▁is", "▁a", "▁t", "est"] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , [465, 287, 265, 631, 842] )
__snake_case = tokenizer.tokenize("I was born in 92000, and this is falsé." )
# fmt: off
self.assertListEqual(
a_ , ["▁I", "▁was", "▁bor", "n", "▁in", "▁", "<0x39>", "2", "0", "0", "0", ",", "▁and", "▁this", "▁is", "▁f", "al", "s", "<0xC3>", "<0xA9>", "."] , )
# fmt: on
__snake_case = tokenizer.convert_tokens_to_ids(a_ )
self.assertListEqual(
a_ , [262, 272, 1_525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260] , )
__snake_case = tokenizer.convert_ids_to_tokens(a_ )
# fmt: off
self.assertListEqual(
a_ , ["▁I", "▁was", "▁bor", "n", "▁in", "▁", "<0x39>", "2", "0", "0", "0", ",", "▁and", "▁this", "▁is", "▁f", "al", "s", "<0xC3>", "<0xA9>", "."] )
# fmt: on
def A ( self : List[str] ):
"""simple docstring"""
__snake_case = GPTSwaTokenizer(a_ )
__snake_case = ["This is a test", "I was born in 92000, and this is falsé."]
__snake_case = [
[465, 287, 265, 631, 842],
[262, 272, 1_525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260],
]
# Test that encode_fast returns the same as tokenize + convert_tokens_to_ids
for text, expected_ids in zip(a_ , a_ ):
self.assertListEqual(tokenizer.encode_fast(a_ ) , a_ )
# Test that decode_fast returns the input text
for text, token_ids in zip(a_ , a_ ):
self.assertEqual(tokenizer.decode_fast(a_ ) , a_ )
@slow
def A ( self : Any ):
"""simple docstring"""
__snake_case = [
"<|python|>def fibonacci(n)\n if n < 0:\n print('Incorrect input')",
"Hey there, how are you doing this fine day?",
"This is a text with a trailing spaces followed by a dot .",
"Häj sväjs lillebrör! =)",
"Det är inget fel på Mr. Cool",
]
# fmt: off
__snake_case = {"input_ids": [[63_423, 5, 6_811, 14_954, 282, 816, 3_821, 63_466, 63_425, 63_462, 18, 63_978, 678, 301, 1_320, 63_423, 63_455, 63_458, 18, 63_982, 4_246, 3_940, 1_901, 47_789, 5_547, 18_994], [19_630, 1_100, 63_446, 1_342, 633, 544, 4_488, 593, 5_102, 2_416, 63_495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_652, 428, 268, 1_936, 515, 268, 58_593, 22_413, 9_106, 546, 268, 33_213, 63_979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [55_130, 63_450, 924, 63_449, 2_249, 4_062, 1_558, 318, 63_504, 21_498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2_827, 2_559, 332, 6_575, 63_443, 26_801, 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]], "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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [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], [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]]}
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=a_ , model_name="AI-Sweden/gpt-sw3-126m" , sequences=a_ , )
| 69 | 1 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> int:
assert column_title.isupper()
__snake_case = 0
__snake_case = len(_UpperCAmelCase ) - 1
__snake_case = 0
while index >= 0:
__snake_case = (ord(column_title[index] ) - 64) * pow(26 , _UpperCAmelCase )
answer += value
power += 1
index -= 1
return answer
if __name__ == "__main__":
from doctest import testmod
testmod()
| 69 |
'''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
a : Tuple = get_tests_dir('''fixtures''')
a : Dict = get_tests_dir('''fixtures/dummy_feature_extractor_config.json''')
a : int = get_tests_dir('''fixtures/dummy-config.json''')
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = 0
def A ( self : str ):
"""simple docstring"""
__snake_case = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h" )
self.assertIsInstance(a_ , a_ )
def A ( self : str ):
"""simple docstring"""
__snake_case = AutoFeatureExtractor.from_pretrained(a_ )
self.assertIsInstance(a_ , a_ )
def A ( self : str ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmpdirname:
__snake_case = WavaVecaConfig()
# remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
__snake_case = AutoFeatureExtractor.from_pretrained(a_ ).to_dict()
config_dict.pop("feature_extractor_type" )
__snake_case = WavaVecaFeatureExtractor(**a_ )
# save in new folder
model_config.save_pretrained(a_ )
config.save_pretrained(a_ )
__snake_case = AutoFeatureExtractor.from_pretrained(a_ )
# make sure private variable is not incorrectly saved
__snake_case = json.loads(config.to_json_string() )
self.assertTrue("_processor_class" not in dict_as_saved )
self.assertIsInstance(a_ , a_ )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = AutoFeatureExtractor.from_pretrained(a_ )
self.assertIsInstance(a_ , a_ )
def A ( self : Optional[Any] ):
"""simple docstring"""
with self.assertRaisesRegex(
a_ , "bert-base is not a local folder and is not a valid model identifier" ):
__snake_case = AutoFeatureExtractor.from_pretrained("bert-base" )
def A ( self : Dict ):
"""simple docstring"""
with self.assertRaisesRegex(
a_ , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ):
__snake_case = AutoFeatureExtractor.from_pretrained(a_ , revision="aaaaaa" )
def A ( self : Tuple ):
"""simple docstring"""
with self.assertRaisesRegex(
a_ , "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json." , ):
__snake_case = AutoFeatureExtractor.from_pretrained("hf-internal-testing/config-no-model" )
def A ( self : Tuple ):
"""simple docstring"""
with self.assertRaises(a_ ):
__snake_case = 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_ ):
__snake_case = AutoFeatureExtractor.from_pretrained(
"hf-internal-testing/test_dynamic_feature_extractor" , trust_remote_code=a_ )
__snake_case = 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_ )
__snake_case = AutoFeatureExtractor.from_pretrained(a_ , trust_remote_code=a_ )
self.assertEqual(reloaded_feature_extractor.__class__.__name__ , "NewFeatureExtractor" )
def A ( self : int ):
"""simple docstring"""
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
__snake_case = CustomFeatureExtractor.from_pretrained(a_ )
with tempfile.TemporaryDirectory() as tmp_dir:
feature_extractor.save_pretrained(a_ )
__snake_case = 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 A ( self : Dict ):
"""simple docstring"""
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = True
try:
AutoConfig.register("custom" , a_ )
AutoFeatureExtractor.register(a_ , a_ )
# If remote code is not set, the default is to use local
__snake_case = 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.
__snake_case = 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
__snake_case = 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]
| 69 | 1 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
a : Dict = {
'''configuration_luke''': ['''LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LukeConfig'''],
'''tokenization_luke''': ['''LukeTokenizer'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : List[Any] = [
'''LUKE_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''LukeForEntityClassification''',
'''LukeForEntityPairClassification''',
'''LukeForEntitySpanClassification''',
'''LukeForMultipleChoice''',
'''LukeForQuestionAnswering''',
'''LukeForSequenceClassification''',
'''LukeForTokenClassification''',
'''LukeForMaskedLM''',
'''LukeModel''',
'''LukePreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_luke import LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP, LukeConfig
from .tokenization_luke import LukeTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_luke import (
LUKE_PRETRAINED_MODEL_ARCHIVE_LIST,
LukeForEntityClassification,
LukeForEntityPairClassification,
LukeForEntitySpanClassification,
LukeForMaskedLM,
LukeForMultipleChoice,
LukeForQuestionAnswering,
LukeForSequenceClassification,
LukeForTokenClassification,
LukeModel,
LukePreTrainedModel,
)
else:
import sys
a : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> list:
# bit count represents no. of bits in the gray code
if bit_count < 0:
raise ValueError("The given input must be positive" )
# get the generated string sequence
__snake_case = gray_code_sequence_string(_UpperCAmelCase )
#
# convert them to integers
for i in range(len(_UpperCAmelCase ) ):
__snake_case = int(sequence[i] , 2 )
return sequence
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> list:
# The approach is a recursive one
# Base case achieved when either n = 0 or n=1
if bit_count == 0:
return ["0"]
if bit_count == 1:
return ["0", "1"]
__snake_case = 1 << bit_count # defines the length of the sequence
# 1<< n is equivalent to 2^n
# recursive answer will generate answer for n-1 bits
__snake_case = gray_code_sequence_string(bit_count - 1 )
__snake_case = []
# append 0 to first half of the smaller sequence generated
for i in range(seq_len // 2 ):
__snake_case = "0" + smaller_sequence[i]
sequence.append(_UpperCAmelCase )
# append 1 to second half ... start from the end of the list
for i in reversed(range(seq_len // 2 ) ):
__snake_case = "1" + smaller_sequence[i]
sequence.append(_UpperCAmelCase )
return sequence
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 | 1 |
'''simple docstring'''
from ...processing_utils import ProcessorMixin
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = ["""image_processor""", """feature_extractor"""]
__SCREAMING_SNAKE_CASE = """TvltImageProcessor"""
__SCREAMING_SNAKE_CASE = """TvltFeatureExtractor"""
def __init__( self : Optional[int] , a_ : int , a_ : Any ):
"""simple docstring"""
super().__init__(image_processor=a_ , feature_extractor=a_ )
__snake_case = image_processor
__snake_case = feature_extractor
def __call__( self : str , a_ : List[Any]=None , a_ : int=None , a_ : Optional[int]=None , a_ : List[Any]=None , a_ : Union[str, Any]=False , a_ : List[Any]=False , *a_ : Union[str, Any] , **a_ : str , ):
"""simple docstring"""
if images is None and audio is None:
raise ValueError("You need to specify either an `images` or `audio` input to process." )
__snake_case = None
if images is not None:
__snake_case = self.image_processor(a_ , mask_pixel=a_ , *a_ , **a_ )
if images_mixed is not None:
__snake_case = self.image_processor(a_ , is_mixed=a_ , *a_ , **a_ )
if audio is not None:
__snake_case = self.feature_extractor(
a_ , *a_ , sampling_rate=a_ , mask_audio=a_ , **a_ )
__snake_case = {}
if audio is not None:
output_dict.update(a_ )
if images is not None:
output_dict.update(a_ )
if images_mixed_dict is not None:
output_dict.update(a_ )
return output_dict
@property
def A ( self : Dict ):
"""simple docstring"""
__snake_case = self.image_processor.model_input_names
__snake_case = self.feature_extractor.model_input_names
return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names ) )
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : str , _UpperCAmelCase : str ) -> list:
__snake_case = len(_UpperCAmelCase )
__snake_case = []
for i in range(len(_UpperCAmelCase ) - pat_len + 1 ):
__snake_case = True
for j in range(_UpperCAmelCase ):
if s[i + j] != pattern[j]:
__snake_case = 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'''))
| 69 | 1 |
'''simple docstring'''
import math
class SCREAMING_SNAKE_CASE__ :
def A ( self : int , a_ : list[list[float]] , a_ : list[int] ):
"""simple docstring"""
__snake_case = 0.0
__snake_case = 0.0
for i in range(len(a_ ) ):
da += math.pow((sample[i] - weights[0][i]) , 2 )
da += math.pow((sample[i] - weights[1][i]) , 2 )
return 0 if da > da else 1
return 0
def A ( self : Union[str, Any] , a_ : list[list[int | float]] , a_ : list[int] , a_ : int , a_ : float ):
"""simple docstring"""
for i in range(len(a_ ) ):
weights[j][i] += alpha * (sample[i] - weights[j][i])
return weights
def __UpperCAmelCase ( ) -> None:
# Training Examples ( m, n )
__snake_case = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]]
# weight initialization ( n, C )
__snake_case = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]]
# training
__snake_case = SelfOrganizingMap()
__snake_case = 3
__snake_case = 0.5
for _ in range(_UpperCAmelCase ):
for j in range(len(_UpperCAmelCase ) ):
# training sample
__snake_case = training_samples[j]
# Compute the winning vector
__snake_case = self_organizing_map.get_winner(_UpperCAmelCase , _UpperCAmelCase )
# Update the winning vector
__snake_case = self_organizing_map.update(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
# classify test sample
__snake_case = [0, 0, 0, 1]
__snake_case = self_organizing_map.get_winner(_UpperCAmelCase , _UpperCAmelCase )
# results
print(F'''Clusters that the test sample belongs to : {winner}''' )
print(F'''Weights that have been trained : {weights}''' )
# running the main() function
if __name__ == "__main__":
main()
| 69 |
'''simple docstring'''
a : Dict = range(2, 20 + 1)
a : Optional[int] = [10**k for k in range(ks[-1] + 1)]
a : dict[int, dict[int, list[list[int]]]] = {}
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Dict , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[Any] ) -> int:
__snake_case = sum(a_i[j] for j in range(_UpperCAmelCase , len(_UpperCAmelCase ) ) )
__snake_case = sum(a_i[j] * base[j] for j in range(min(len(_UpperCAmelCase ) , _UpperCAmelCase ) ) )
__snake_case , __snake_case = 0, 0
__snake_case = n - i
__snake_case = memo.get(_UpperCAmelCase )
if sub_memo is not None:
__snake_case = sub_memo.get(_UpperCAmelCase )
if jumps is not None and len(_UpperCAmelCase ) > 0:
# find and make the largest jump without going over
__snake_case = -1
for _k in range(len(_UpperCAmelCase ) - 1 , -1 , -1 ):
if jumps[_k][2] <= k and jumps[_k][1] <= max_dn:
__snake_case = _k
break
if max_jump >= 0:
__snake_case , __snake_case , __snake_case = jumps[max_jump]
# since the difference between jumps is cached, add c
__snake_case = diff + c
for j in range(min(_UpperCAmelCase , len(_UpperCAmelCase ) ) ):
__snake_case , __snake_case = divmod(_UpperCAmelCase , 10 )
if new_c > 0:
add(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
else:
__snake_case = []
else:
__snake_case = {c: []}
__snake_case = sub_memo
if dn >= max_dn or c + diff >= base[k]:
return diff, dn
if k > ks[0]:
while True:
# keep doing smaller jumps
__snake_case , __snake_case = next_term(_UpperCAmelCase , k - 1 , i + dn , _UpperCAmelCase )
diff += _diff
dn += terms_jumped
if dn >= max_dn or c + diff >= base[k]:
break
else:
# would be too small a jump, just compute sequential terms instead
__snake_case , __snake_case = compute(_UpperCAmelCase , _UpperCAmelCase , i + dn , _UpperCAmelCase )
diff += _diff
dn += terms_jumped
__snake_case = sub_memo[c]
# keep jumps sorted by # of terms skipped
__snake_case = 0
while j < len(_UpperCAmelCase ):
if jumps[j][1] > dn:
break
j += 1
# cache the jump for this value digitsum(b) and c
sub_memo[c].insert(_UpperCAmelCase , (diff, dn, k) )
return (diff, dn)
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[int] ) -> Optional[int]:
if i >= n:
return 0, i
if k > len(_UpperCAmelCase ):
a_i.extend([0 for _ in range(k - len(_UpperCAmelCase ) )] )
# note: a_i -> b * 10^k + c
# ds_b -> digitsum(b)
# ds_c -> digitsum(c)
__snake_case = i
__snake_case , __snake_case , __snake_case = 0, 0, 0
for j in range(len(_UpperCAmelCase ) ):
if j >= k:
ds_b += a_i[j]
else:
ds_c += a_i[j]
while i < n:
i += 1
__snake_case = ds_c + ds_b
diff += addend
__snake_case = 0
for j in range(_UpperCAmelCase ):
__snake_case = a_i[j] + addend
__snake_case , __snake_case = divmod(_UpperCAmelCase , 10 )
ds_c += a_i[j]
if addend > 0:
break
if addend > 0:
add(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
return diff, i - start_i
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Tuple , _UpperCAmelCase : str ) -> Tuple:
for j in range(_UpperCAmelCase , len(_UpperCAmelCase ) ):
__snake_case = digits[j] + addend
if s >= 10:
__snake_case , __snake_case = divmod(_UpperCAmelCase , 10 )
__snake_case = addend // 10 + quotient
else:
__snake_case = s
__snake_case = addend // 10
if addend == 0:
break
while addend > 0:
__snake_case , __snake_case = divmod(_UpperCAmelCase , 10 )
digits.append(_UpperCAmelCase )
def __UpperCAmelCase ( _UpperCAmelCase : int = 10**15 ) -> int:
__snake_case = [1]
__snake_case = 1
__snake_case = 0
while True:
__snake_case , __snake_case = next_term(_UpperCAmelCase , 20 , i + dn , _UpperCAmelCase )
dn += terms_jumped
if dn == n - i:
break
__snake_case = 0
for j in range(len(_UpperCAmelCase ) ):
a_n += digits[j] * 10**j
return a_n
if __name__ == "__main__":
print(F'''{solution() = }''')
| 69 | 1 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int = 60_08_51_47_51_43 ) -> int:
try:
__snake_case = int(_UpperCAmelCase )
except (TypeError, ValueError):
raise TypeError("Parameter n must be int or castable to int." )
if n <= 0:
raise ValueError("Parameter n must be greater than or equal to one." )
__snake_case = 1
__snake_case = 2
while i * i <= n:
while n % i == 0:
__snake_case = i
n //= i
i += 1
if n > 1:
__snake_case = n
return int(_UpperCAmelCase )
if __name__ == "__main__":
print(F'''{solution() = }''')
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : List[Any]=2_81_23 ) -> str:
__snake_case = [1] * (limit + 1)
for i in range(2 , int(limit**0.5 ) + 1 ):
sum_divs[i * i] += i
for k in range(i + 1 , limit // i + 1 ):
sum_divs[k * i] += k + i
__snake_case = set()
__snake_case = 0
for n in range(1 , limit + 1 ):
if sum_divs[n] > n:
abundants.add(_UpperCAmelCase )
if not any((n - a in abundants) for a in abundants ):
res += n
return res
if __name__ == "__main__":
print(solution())
| 69 | 1 |
'''simple docstring'''
from typing import Optional, Tuple, Union
import torch
from einops import rearrange, reduce
from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel
from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput
from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput
a : Dict = 8
def __UpperCAmelCase ( _UpperCAmelCase : Optional[int] , _UpperCAmelCase : Any=BITS ) -> Any:
__snake_case = x.device
__snake_case = (x * 2_55).int().clamp(0 , 2_55 )
__snake_case = 2 ** torch.arange(bits - 1 , -1 , -1 , device=_UpperCAmelCase )
__snake_case = rearrange(_UpperCAmelCase , "d -> d 1 1" )
__snake_case = rearrange(_UpperCAmelCase , "b c h w -> b c 1 h w" )
__snake_case = ((x & mask) != 0).float()
__snake_case = rearrange(_UpperCAmelCase , "b c d h w -> b (c d) h w" )
__snake_case = bits * 2 - 1
return bits
def __UpperCAmelCase ( _UpperCAmelCase : Any , _UpperCAmelCase : Union[str, Any]=BITS ) -> List[Any]:
__snake_case = x.device
__snake_case = (x > 0).int()
__snake_case = 2 ** torch.arange(bits - 1 , -1 , -1 , device=_UpperCAmelCase , dtype=torch.intaa )
__snake_case = rearrange(_UpperCAmelCase , "d -> d 1 1" )
__snake_case = rearrange(_UpperCAmelCase , "b (c d) h w -> b c d h w" , d=8 )
__snake_case = reduce(x * mask , "b c d h w -> b c h w" , "sum" )
return (dec / 2_55).clamp(0.0 , 1.0 )
def __UpperCAmelCase ( self : Optional[Any] , _UpperCAmelCase : torch.FloatTensor , _UpperCAmelCase : int , _UpperCAmelCase : torch.FloatTensor , _UpperCAmelCase : float = 0.0 , _UpperCAmelCase : bool = True , _UpperCAmelCase : int=None , _UpperCAmelCase : bool = True , ) -> Union[DDIMSchedulerOutput, Tuple]:
if self.num_inference_steps is None:
raise ValueError(
"Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" )
# See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf
# Ideally, read DDIM paper in-detail understanding
# Notation (<variable name> -> <name in paper>
# - pred_noise_t -> e_theta(x_t, t)
# - pred_original_sample -> f_theta(x_t, t) or x_0
# - std_dev_t -> sigma_t
# - eta -> η
# - pred_sample_direction -> "direction pointing to x_t"
# - pred_prev_sample -> "x_t-1"
# 1. get previous step value (=t-1)
__snake_case = timestep - self.config.num_train_timesteps // self.num_inference_steps
# 2. compute alphas, betas
__snake_case = self.alphas_cumprod[timestep]
__snake_case = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
__snake_case = 1 - alpha_prod_t
# 3. compute predicted original sample from predicted noise also called
# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
__snake_case = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
# 4. Clip "predicted x_0"
__snake_case = self.bit_scale
if self.config.clip_sample:
__snake_case = torch.clamp(_UpperCAmelCase , -scale , _UpperCAmelCase )
# 5. compute variance: "sigma_t(η)" -> see formula (16)
# σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
__snake_case = self._get_variance(_UpperCAmelCase , _UpperCAmelCase )
__snake_case = eta * variance ** 0.5
if use_clipped_model_output:
# the model_output is always re-derived from the clipped x_0 in Glide
__snake_case = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5
# 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
__snake_case = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output
# 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
__snake_case = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction
if eta > 0:
# randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072
__snake_case = model_output.device if torch.is_tensor(_UpperCAmelCase ) else "cpu"
__snake_case = torch.randn(model_output.shape , dtype=model_output.dtype , generator=_UpperCAmelCase ).to(_UpperCAmelCase )
__snake_case = self._get_variance(_UpperCAmelCase , _UpperCAmelCase ) ** 0.5 * eta * noise
__snake_case = prev_sample + variance
if not return_dict:
return (prev_sample,)
return DDIMSchedulerOutput(prev_sample=_UpperCAmelCase , pred_original_sample=_UpperCAmelCase )
def __UpperCAmelCase ( self : Tuple , _UpperCAmelCase : torch.FloatTensor , _UpperCAmelCase : int , _UpperCAmelCase : torch.FloatTensor , _UpperCAmelCase : Dict="epsilon" , _UpperCAmelCase : Dict=None , _UpperCAmelCase : bool = True , ) -> Union[DDPMSchedulerOutput, Tuple]:
__snake_case = timestep
if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]:
__snake_case , __snake_case = torch.split(_UpperCAmelCase , sample.shape[1] , dim=1 )
else:
__snake_case = None
# 1. compute alphas, betas
__snake_case = self.alphas_cumprod[t]
__snake_case = self.alphas_cumprod[t - 1] if t > 0 else self.one
__snake_case = 1 - alpha_prod_t
__snake_case = 1 - alpha_prod_t_prev
# 2. compute predicted original sample from predicted noise also called
# "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf
if prediction_type == "epsilon":
__snake_case = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
elif prediction_type == "sample":
__snake_case = model_output
else:
raise ValueError(F'''Unsupported prediction_type {prediction_type}.''' )
# 3. Clip "predicted x_0"
__snake_case = self.bit_scale
if self.config.clip_sample:
__snake_case = torch.clamp(_UpperCAmelCase , -scale , _UpperCAmelCase )
# 4. Compute coefficients for pred_original_sample x_0 and current sample x_t
# See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
__snake_case = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t
__snake_case = self.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t
# 5. Compute predicted previous sample µ_t
# See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
__snake_case = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample
# 6. Add noise
__snake_case = 0
if t > 0:
__snake_case = torch.randn(
model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=_UpperCAmelCase ).to(model_output.device )
__snake_case = (self._get_variance(_UpperCAmelCase , predicted_variance=_UpperCAmelCase ) ** 0.5) * noise
__snake_case = pred_prev_sample + variance
if not return_dict:
return (pred_prev_sample,)
return DDPMSchedulerOutput(prev_sample=_UpperCAmelCase , pred_original_sample=_UpperCAmelCase )
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def __init__( self : Union[str, Any] , a_ : UNetaDConditionModel , a_ : Union[DDIMScheduler, DDPMScheduler] , a_ : Optional[float] = 1.0 , ):
"""simple docstring"""
super().__init__()
__snake_case = bit_scale
__snake_case = (
ddim_bit_scheduler_step if isinstance(a_ , a_ ) else ddpm_bit_scheduler_step
)
self.register_modules(unet=a_ , scheduler=a_ )
@torch.no_grad()
def __call__( self : int , a_ : Optional[int] = 256 , a_ : Optional[int] = 256 , a_ : Optional[int] = 50 , a_ : Optional[torch.Generator] = None , a_ : Optional[int] = 1 , a_ : Optional[str] = "pil" , a_ : bool = True , **a_ : Dict , ):
"""simple docstring"""
__snake_case = torch.randn(
(batch_size, self.unet.config.in_channels, height, width) , generator=a_ , )
__snake_case = decimal_to_bits(a_ ) * self.bit_scale
__snake_case = latents.to(self.device )
self.scheduler.set_timesteps(a_ )
for t in self.progress_bar(self.scheduler.timesteps ):
# predict the noise residual
__snake_case = self.unet(a_ , a_ ).sample
# compute the previous noisy sample x_t -> x_t-1
__snake_case = self.scheduler.step(a_ , a_ , a_ ).prev_sample
__snake_case = bits_to_decimal(a_ )
if output_type == "pil":
__snake_case = self.numpy_to_pil(a_ )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=a_ )
| 69 |
'''simple docstring'''
import unittest
from transformers import AutoTokenizer, FalconConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
FalconForCausalLM,
FalconForQuestionAnswering,
FalconForSequenceClassification,
FalconForTokenClassification,
FalconModel,
)
class SCREAMING_SNAKE_CASE__ :
def __init__( self : str , a_ : List[str] , a_ : Tuple=3 , a_ : Any=7 , a_ : Any=True , a_ : Union[str, Any]=True , a_ : Tuple=False , a_ : Optional[int]=True , a_ : Any=99 , a_ : Dict=32 , a_ : Dict=5 , a_ : List[Any]=4 , a_ : Any=37 , a_ : Any="gelu" , a_ : List[str]=0.1 , a_ : Dict=0.1 , a_ : Optional[Any]=512 , a_ : List[Any]=16 , a_ : Any=2 , a_ : str=0.02 , a_ : Any=3 , a_ : List[Any]=4 , a_ : List[str]=None , ):
"""simple docstring"""
__snake_case = parent
__snake_case = batch_size
__snake_case = seq_length
__snake_case = is_training
__snake_case = use_input_mask
__snake_case = use_token_type_ids
__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_act
__snake_case = hidden_dropout_prob
__snake_case = attention_probs_dropout_prob
__snake_case = max_position_embeddings
__snake_case = type_vocab_size
__snake_case = type_sequence_label_size
__snake_case = initializer_range
__snake_case = num_labels
__snake_case = num_choices
__snake_case = scope
def A ( self : Any ):
"""simple docstring"""
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__snake_case = None
if self.use_input_mask:
__snake_case = random_attention_mask([self.batch_size, self.seq_length] )
__snake_case = None
__snake_case = None
__snake_case = None
__snake_case = None
if self.use_labels:
__snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__snake_case = ids_tensor([self.batch_size] , self.num_choices )
__snake_case = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def A ( self : Optional[int] ):
"""simple docstring"""
return FalconConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a_ , initializer_range=self.initializer_range , pad_token_id=1 , new_decoder_architecture=a_ , )
def A ( self : List[str] , a_ : Dict , a_ : Tuple , a_ : Optional[Any] , a_ : Dict , a_ : Dict , a_ : Dict , a_ : Union[str, Any] ):
"""simple docstring"""
__snake_case = FalconModel(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ )
__snake_case = model(a_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def A ( self : List[Any] , a_ : List[Any] , a_ : Union[str, Any] , a_ : Optional[Any] , a_ : Any , a_ : List[Any] , a_ : Optional[Any] , a_ : Union[str, Any] , a_ : Tuple , a_ : Optional[int] , ):
"""simple docstring"""
__snake_case = True
__snake_case = FalconModel(a_ )
model.to(a_ )
model.eval()
__snake_case = model(
a_ , attention_mask=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , )
__snake_case = model(
a_ , attention_mask=a_ , encoder_hidden_states=a_ , )
__snake_case = model(a_ , attention_mask=a_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def A ( self : Optional[int] , a_ : int , a_ : int , a_ : List[Any] , a_ : str , a_ : List[str] , a_ : str , a_ : str , a_ : Union[str, Any] , a_ : Optional[int] , ):
"""simple docstring"""
__snake_case = FalconForCausalLM(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def A ( self : List[Any] , a_ : Optional[int] , a_ : Optional[Any] , a_ : str , a_ : Tuple , a_ : str , a_ : List[Any] , a_ : Optional[Any] , a_ : Any , a_ : Dict , ):
"""simple docstring"""
__snake_case = True
__snake_case = True
__snake_case = FalconForCausalLM(config=a_ )
model.to(a_ )
model.eval()
# first forward pass
__snake_case = model(
a_ , attention_mask=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , use_cache=a_ , )
__snake_case = outputs.past_key_values
# create hypothetical multiple next token and extent to next_input_ids
__snake_case = ids_tensor((self.batch_size, 3) , config.vocab_size )
__snake_case = ids_tensor((self.batch_size, 3) , vocab_size=2 )
# append to next input_ids and
__snake_case = torch.cat([input_ids, next_tokens] , dim=-1 )
__snake_case = torch.cat([input_mask, next_mask] , dim=-1 )
__snake_case = model(
a_ , attention_mask=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , output_hidden_states=a_ , )["hidden_states"][0]
__snake_case = model(
a_ , attention_mask=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , past_key_values=a_ , output_hidden_states=a_ , )["hidden_states"][0]
# select random slice
__snake_case = ids_tensor((1,) , output_from_past.shape[-1] ).item()
__snake_case = output_from_no_past[:, -3:, random_slice_idx].detach()
__snake_case = output_from_past[:, :, random_slice_idx].detach()
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] )
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = self.prepare_config_and_inputs()
(
(
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) ,
) = config_and_inputs
__snake_case = {"input_ids": input_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = (
(
FalconModel,
FalconForCausalLM,
FalconForSequenceClassification,
FalconForTokenClassification,
FalconForQuestionAnswering,
)
if is_torch_available()
else ()
)
__SCREAMING_SNAKE_CASE = (FalconForCausalLM,) if is_torch_available() else ()
__SCREAMING_SNAKE_CASE = (
{
"""feature-extraction""": FalconModel,
"""text-classification""": FalconForSequenceClassification,
"""text-generation""": FalconForCausalLM,
"""question-answering""": FalconForQuestionAnswering,
"""token-classification""": FalconForTokenClassification,
"""zero-shot""": FalconForSequenceClassification,
}
if is_torch_available()
else {}
)
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = False
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = FalconModelTester(self )
__snake_case = ConfigTester(self , config_class=a_ , hidden_size=37 )
def A ( self : Optional[Any] ):
"""simple docstring"""
self.config_tester.run_common_tests()
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*a_ )
def A ( self : List[str] ):
"""simple docstring"""
__snake_case , *__snake_case = self.model_tester.prepare_config_and_inputs()
for alibi in [True, False]:
__snake_case = alibi
self.model_tester.create_and_check_model(a_ , *a_ )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = 3
__snake_case = input_dict["input_ids"]
__snake_case = input_ids.ne(1 ).to(a_ )
__snake_case = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size )
__snake_case = FalconForSequenceClassification(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) )
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = 3
__snake_case = "single_label_classification"
__snake_case = input_dict["input_ids"]
__snake_case = input_ids.ne(1 ).to(a_ )
__snake_case = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size )
__snake_case = FalconForSequenceClassification(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = input_dict["input_ids"]
__snake_case = FalconForCausalLM(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , use_cache=a_ )
__snake_case = input_ids.shape[0]
__snake_case = model._convert_to_rw_cache(result.past_key_values )
__snake_case = model._convert_cache_to_standard_format(a_ , a_ )
for layer in range(len(a_ ) ):
for tensor_idx in range(2 ):
self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3 )
self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4 )
self.assertTrue(
torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx] ) )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = 3
__snake_case = "multi_label_classification"
__snake_case = input_dict["input_ids"]
__snake_case = input_ids.ne(1 ).to(a_ )
__snake_case = ids_tensor(
[self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float )
__snake_case = FalconForSequenceClassification(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) )
def A ( self : Dict ):
"""simple docstring"""
for model_class in self.all_generative_model_classes:
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
# If it doesn't support cache, pass the test
if not hasattr(a_ , "use_cache" ):
return
__snake_case = model_class(a_ ).to(a_ )
if "use_cache" not in inputs:
__snake_case = True
__snake_case = model(**a_ )
# If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format)
if "past_key_values" not in outputs:
return
__snake_case = (
getattr(a_ , "decoder_layers" , a_ )
or getattr(a_ , "num_decoder_layers" , a_ )
or config.num_hidden_layers
)
__snake_case = getattr(a_ , "num_kv_heads" , config.num_attention_heads )
__snake_case = getattr(a_ , "d_model" , config.hidden_size )
__snake_case = embed_dim // num_attention_heads
__snake_case = outputs["past_key_values"]
self.assertEqual(len(a_ ) , a_ )
__snake_case , __snake_case = inputs["input_ids"].shape
for i in range(a_ ):
if config.new_decoder_architecture:
__snake_case = config.num_attention_heads
elif config.multi_query:
__snake_case = 1
self.assertEqual(len(past_kv[0] ) , 2 ) # K V for the decoder = 2
self.assertEqual(
past_kv[i][0].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) )
self.assertEqual(
past_kv[i][1].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) )
@require_torch
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
@slow
def A ( self : Any ):
"""simple docstring"""
__snake_case = AutoTokenizer.from_pretrained("Rocketknight1/falcon-rw-1b" )
__snake_case = FalconForCausalLM.from_pretrained("Rocketknight1/falcon-rw-1b" )
model.eval()
model.to(a_ )
__snake_case = tokenizer("My favorite food is" , return_tensors="pt" ).to(a_ )
__snake_case = (
"My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday."
)
__snake_case = model.generate(**a_ , do_sample=a_ , max_new_tokens=19 )
__snake_case = tokenizer.batch_decode(a_ )[0]
self.assertEqual(a_ , a_ )
@slow
def A ( self : Optional[int] ):
"""simple docstring"""
for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]:
__snake_case = AutoTokenizer.from_pretrained(a_ )
__snake_case = FalconForCausalLM.from_pretrained(a_ )
model.eval()
model.to(a_ )
__snake_case = tokenizer("My favorite food is" , return_tensors="pt" ).to(a_ )
# We just test that these run without errors - the models are randomly initialized
# and so the actual text outputs will be garbage
model.generate(**a_ , do_sample=a_ , max_new_tokens=4 )
model.generate(**a_ , do_sample=a_ , max_new_tokens=4 )
model.generate(**a_ , num_beams=2 , max_new_tokens=4 )
@slow
def A ( self : Any ):
"""simple docstring"""
with torch.no_grad():
for repo in [
"Rocketknight1/falcon-rw-1b",
"Rocketknight1/tiny-random-falcon-7b",
"Rocketknight1/tiny-random-falcon-40b",
]:
__snake_case = AutoTokenizer.from_pretrained(a_ )
__snake_case = FalconForCausalLM.from_pretrained(a_ )
model.eval()
model.to(device=a_ )
__snake_case = tokenizer("My favorite food is" , return_tensors="pt" ).to(a_ )
# Test results are the same with and without cache
__snake_case = model.generate(**a_ , do_sample=a_ , max_new_tokens=20 , use_cache=a_ )
__snake_case = model.generate(**a_ , do_sample=a_ , max_new_tokens=20 , use_cache=a_ )
self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0 )
| 69 | 1 |
'''simple docstring'''
from __future__ import annotations
import math
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> list[int]:
if num <= 0:
__snake_case = F'''{num}: Invalid input, please enter a positive integer.'''
raise ValueError(_UpperCAmelCase )
__snake_case = [True] * (num + 1)
__snake_case = []
__snake_case = 2
__snake_case = int(math.sqrt(_UpperCAmelCase ) )
while start <= end:
# If start is a prime
if sieve[start] is True:
prime.append(_UpperCAmelCase )
# Set multiples of start be False
for i in range(start * start , num + 1 , _UpperCAmelCase ):
if sieve[i] is True:
__snake_case = False
start += 1
for j in range(end + 1 , num + 1 ):
if sieve[j] is True:
prime.append(_UpperCAmelCase )
return prime
if __name__ == "__main__":
print(prime_sieve(int(input('''Enter a positive integer: ''').strip())))
| 69 |
'''simple docstring'''
import mpmath # for roots of unity
import numpy as np
class SCREAMING_SNAKE_CASE__ :
def __init__( self : Tuple , a_ : Optional[int]=None , a_ : int=None ):
"""simple docstring"""
__snake_case = list(poly_a or [0] )[:]
__snake_case = list(poly_b or [0] )[:]
# Remove leading zero coefficients
while self.polyA[-1] == 0:
self.polyA.pop()
__snake_case = len(self.polyA )
while self.polyB[-1] == 0:
self.polyB.pop()
__snake_case = len(self.polyB )
# Add 0 to make lengths equal a power of 2
__snake_case = int(
2 ** np.ceil(np.loga(len(self.polyA ) + len(self.polyB ) - 1 ) ) )
while len(self.polyA ) < self.c_max_length:
self.polyA.append(0 )
while len(self.polyB ) < self.c_max_length:
self.polyB.append(0 )
# A complex root used for the fourier transform
__snake_case = complex(mpmath.root(x=1 , n=self.c_max_length , k=1 ) )
# The product
__snake_case = self.__multiply()
def A ( self : Any , a_ : Optional[Any] ):
"""simple docstring"""
__snake_case = [[x] for x in self.polyA] if which == "A" else [[x] for x in self.polyB]
# Corner case
if len(a_ ) <= 1:
return dft[0]
#
__snake_case = self.c_max_length // 2
while next_ncol > 0:
__snake_case = [[] for i in range(a_ )]
__snake_case = self.root**next_ncol
# First half of next step
__snake_case = 1
for j in range(self.c_max_length // (next_ncol * 2) ):
for i in range(a_ ):
new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j] )
current_root *= root
# Second half of next step
__snake_case = 1
for j in range(self.c_max_length // (next_ncol * 2) ):
for i in range(a_ ):
new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j] )
current_root *= root
# Update
__snake_case = new_dft
__snake_case = next_ncol // 2
return dft[0]
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = self.__dft("A" )
__snake_case = self.__dft("B" )
__snake_case = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length )]]
del dft_a
del dft_b
# Corner Case
if len(inverce_c[0] ) <= 1:
return inverce_c[0]
# Inverse DFT
__snake_case = 2
while next_ncol <= self.c_max_length:
__snake_case = [[] for i in range(a_ )]
__snake_case = self.root ** (next_ncol // 2)
__snake_case = 1
# First half of next step
for j in range(self.c_max_length // next_ncol ):
for i in range(next_ncol // 2 ):
# Even positions
new_inverse_c[i].append(
(
inverce_c[i][j]
+ inverce_c[i][j + self.c_max_length // next_ncol]
)
/ 2 )
# Odd positions
new_inverse_c[i + next_ncol // 2].append(
(
inverce_c[i][j]
- inverce_c[i][j + self.c_max_length // next_ncol]
)
/ (2 * current_root) )
current_root *= root
# Update
__snake_case = new_inverse_c
next_ncol *= 2
# Unpack
__snake_case = [round(x[0].real , 8 ) + round(x[0].imag , 8 ) * 1j for x in inverce_c]
# Remove leading 0's
while inverce_c[-1] == 0:
inverce_c.pop()
return inverce_c
def __str__( self : Optional[int] ):
"""simple docstring"""
__snake_case = "A = " + " + ".join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.polyA[: self.len_A] ) )
__snake_case = "B = " + " + ".join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.polyB[: self.len_B] ) )
__snake_case = "A*B = " + " + ".join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.product ) )
return f'''{a}\n{b}\n{c}'''
# Unit tests
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 | 1 |
'''simple docstring'''
import inspect
import unittest
import numpy as np
from transformers import ViTConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor
if is_flax_available():
import jax
from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def __init__( self : str , a_ : Dict , a_ : Optional[Any]=13 , a_ : Union[str, Any]=30 , a_ : str=2 , a_ : Union[str, Any]=3 , a_ : Optional[Any]=True , a_ : Dict=True , a_ : Optional[Any]=32 , a_ : str=5 , a_ : Union[str, Any]=4 , a_ : Optional[int]=37 , a_ : Optional[Any]="gelu" , a_ : Optional[Any]=0.1 , a_ : Any=0.1 , a_ : Optional[Any]=10 , a_ : Optional[Any]=0.02 , ):
"""simple docstring"""
__snake_case = parent
__snake_case = batch_size
__snake_case = image_size
__snake_case = patch_size
__snake_case = num_channels
__snake_case = is_training
__snake_case = use_labels
__snake_case = hidden_size
__snake_case = num_hidden_layers
__snake_case = num_attention_heads
__snake_case = intermediate_size
__snake_case = hidden_act
__snake_case = hidden_dropout_prob
__snake_case = attention_probs_dropout_prob
__snake_case = type_sequence_label_size
__snake_case = initializer_range
# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
__snake_case = (image_size // patch_size) ** 2
__snake_case = num_patches + 1
def A ( self : str ):
"""simple docstring"""
__snake_case = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
__snake_case = ViTConfig(
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 , 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=a_ , initializer_range=self.initializer_range , )
return config, pixel_values
def A ( self : Union[str, Any] , a_ : str , a_ : Union[str, Any] ):
"""simple docstring"""
__snake_case = FlaxViTModel(config=a_ )
__snake_case = model(a_ )
# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
__snake_case = (self.image_size, self.image_size)
__snake_case = (self.patch_size, self.patch_size)
__snake_case = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, num_patches + 1, self.hidden_size) )
def A ( self : List[str] , a_ : Dict , a_ : str ):
"""simple docstring"""
__snake_case = self.type_sequence_label_size
__snake_case = FlaxViTForImageClassification(config=a_ )
__snake_case = model(a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
# test greyscale images
__snake_case = 1
__snake_case = FlaxViTForImageClassification(a_ )
__snake_case = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
__snake_case = model(a_ )
def A ( self : Any ):
"""simple docstring"""
__snake_case = self.prepare_config_and_inputs()
(
(
__snake_case
) , (
__snake_case
) ,
) = config_and_inputs
__snake_case = {"pixel_values": pixel_values}
return config, inputs_dict
@require_flax
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else ()
def A ( self : str ):
"""simple docstring"""
__snake_case = FlaxViTModelTester(self )
__snake_case = ConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 )
def A ( self : Any ):
"""simple docstring"""
self.config_tester.run_common_tests()
def A ( self : List[str] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*a_ )
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*a_ )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__snake_case = model_class(a_ )
__snake_case = inspect.signature(model.__call__ )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__snake_case = [*signature.parameters.keys()]
__snake_case = ["pixel_values"]
self.assertListEqual(arg_names[:1] , a_ )
def A ( self : List[str] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
with self.subTest(model_class.__name__ ):
__snake_case = self._prepare_for_class(a_ , a_ )
__snake_case = model_class(a_ )
@jax.jit
def model_jitted(a_ : Dict , **a_ : str ):
return model(pixel_values=a_ , **a_ )
with self.subTest("JIT Enabled" ):
__snake_case = model_jitted(**a_ ).to_tuple()
with self.subTest("JIT Disabled" ):
with jax.disable_jit():
__snake_case = model_jitted(**a_ ).to_tuple()
self.assertEqual(len(a_ ) , len(a_ ) )
for jitted_output, output in zip(a_ , a_ ):
self.assertEqual(jitted_output.shape , output.shape )
@slow
def A ( self : Union[str, Any] ):
"""simple docstring"""
for model_class_name in self.all_model_classes:
__snake_case = model_class_name.from_pretrained("google/vit-base-patch16-224" )
__snake_case = model(np.ones((1, 3, 224, 224) ) )
self.assertIsNotNone(a_ )
| 69 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
a : List[Any] = {
'''configuration_table_transformer''': [
'''TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''TableTransformerConfig''',
'''TableTransformerOnnxConfig''',
]
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : Tuple = [
'''TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TableTransformerForObjectDetection''',
'''TableTransformerModel''',
'''TableTransformerPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_table_transformer import (
TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
TableTransformerConfig,
TableTransformerOnnxConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_table_transformer import (
TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TableTransformerForObjectDetection,
TableTransformerModel,
TableTransformerPreTrainedModel,
)
else:
import sys
a : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 69 | 1 |
'''simple docstring'''
from math import pi
def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : int ) -> float:
return 2 * pi * radius * (angle / 3_60)
if __name__ == "__main__":
print(arc_length(90, 10))
| 69 |
'''simple docstring'''
import json
import os
import torch
from diffusers import UNetaDModel
os.makedirs('''hub/hopper-medium-v2/unet/hor32''', exist_ok=True)
os.makedirs('''hub/hopper-medium-v2/unet/hor128''', exist_ok=True)
os.makedirs('''hub/hopper-medium-v2/value_function''', exist_ok=True)
def __UpperCAmelCase ( _UpperCAmelCase : List[str] ) -> str:
if hor == 1_28:
__snake_case = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D")
__snake_case = (32, 1_28, 2_56)
__snake_case = ("UpResnetBlock1D", "UpResnetBlock1D")
elif hor == 32:
__snake_case = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D")
__snake_case = (32, 64, 1_28, 2_56)
__snake_case = ("UpResnetBlock1D", "UpResnetBlock1D", "UpResnetBlock1D")
__snake_case = torch.load(F'''/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch''' )
__snake_case = model.state_dict()
__snake_case = {
"down_block_types": down_block_types,
"block_out_channels": block_out_channels,
"up_block_types": up_block_types,
"layers_per_block": 1,
"use_timestep_embedding": True,
"out_block_type": "OutConv1DBlock",
"norm_num_groups": 8,
"downsample_each_block": False,
"in_channels": 14,
"out_channels": 14,
"extra_in_channels": 0,
"time_embedding_type": "positional",
"flip_sin_to_cos": False,
"freq_shift": 1,
"sample_size": 6_55_36,
"mid_block_type": "MidResTemporalBlock1D",
"act_fn": "mish",
}
__snake_case = UNetaDModel(**_UpperCAmelCase )
print(F'''length of state dict: {len(state_dict.keys() )}''' )
print(F'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' )
__snake_case = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) )
for k, v in mapping.items():
__snake_case = state_dict.pop(_UpperCAmelCase )
hf_value_function.load_state_dict(_UpperCAmelCase )
torch.save(hf_value_function.state_dict() , F'''hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin''' )
with open(F'''hub/hopper-medium-v2/unet/hor{hor}/config.json''' , "w" ) as f:
json.dump(_UpperCAmelCase , _UpperCAmelCase )
def __UpperCAmelCase ( ) -> List[Any]:
__snake_case = {
"in_channels": 14,
"down_block_types": ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D"),
"up_block_types": (),
"out_block_type": "ValueFunction",
"mid_block_type": "ValueFunctionMidBlock1D",
"block_out_channels": (32, 64, 1_28, 2_56),
"layers_per_block": 1,
"downsample_each_block": True,
"sample_size": 6_55_36,
"out_channels": 14,
"extra_in_channels": 0,
"time_embedding_type": "positional",
"use_timestep_embedding": True,
"flip_sin_to_cos": False,
"freq_shift": 1,
"norm_num_groups": 8,
"act_fn": "mish",
}
__snake_case = torch.load("/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch" )
__snake_case = model
__snake_case = UNetaDModel(**_UpperCAmelCase )
print(F'''length of state dict: {len(state_dict.keys() )}''' )
print(F'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' )
__snake_case = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) )
for k, v in mapping.items():
__snake_case = state_dict.pop(_UpperCAmelCase )
hf_value_function.load_state_dict(_UpperCAmelCase )
torch.save(hf_value_function.state_dict() , "hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin" )
with open("hub/hopper-medium-v2/value_function/config.json" , "w" ) as f:
json.dump(_UpperCAmelCase , _UpperCAmelCase )
if __name__ == "__main__":
unet(32)
# unet(128)
value_function()
| 69 | 1 |
'''simple docstring'''
from string import ascii_uppercase
a : str = {str(ord(c) - 55): c for c in ascii_uppercase}
def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : int ) -> str:
if isinstance(_UpperCAmelCase , _UpperCAmelCase ):
raise TypeError("int() can't convert non-string with explicit base" )
if num < 0:
raise ValueError("parameter must be positive int" )
if isinstance(_UpperCAmelCase , _UpperCAmelCase ):
raise TypeError("'str' object cannot be interpreted as an integer" )
if isinstance(_UpperCAmelCase , _UpperCAmelCase ):
raise TypeError("'float' object cannot be interpreted as an integer" )
if base in (0, 1):
raise ValueError("base must be >= 2" )
if base > 36:
raise ValueError("base must be <= 36" )
__snake_case = ""
__snake_case = 0
__snake_case = 0
while div != 1:
__snake_case , __snake_case = divmod(_UpperCAmelCase , _UpperCAmelCase )
if base >= 11 and 9 < mod < 36:
__snake_case = ALPHABET_VALUES[str(_UpperCAmelCase )]
else:
__snake_case = str(_UpperCAmelCase )
new_value += actual_value
__snake_case = num // base
__snake_case = div
if div == 0:
return str(new_value[::-1] )
elif div == 1:
new_value += str(_UpperCAmelCase )
return str(new_value[::-1] )
return new_value[::-1]
if __name__ == "__main__":
import doctest
doctest.testmod()
for base in range(2, 37):
for num in range(1_000):
assert int(decimal_to_any(num, base), base) == num, (
num,
base,
decimal_to_any(num, base),
int(decimal_to_any(num, base), base),
)
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int = 1_00_00_00 ) -> int:
__snake_case = 1
__snake_case = 1
__snake_case = {1: 1}
for inputa in range(2 , _UpperCAmelCase ):
__snake_case = 0
__snake_case = inputa
while True:
if number in counters:
counter += counters[number]
break
if number % 2 == 0:
number //= 2
counter += 1
else:
__snake_case = (3 * number) + 1
counter += 1
if inputa not in counters:
__snake_case = counter
if counter > pre_counter:
__snake_case = inputa
__snake_case = counter
return largest_number
if __name__ == "__main__":
print(solution(int(input().strip())))
| 69 | 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 SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = GPTSanJapaneseTokenizer
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = {"""do_clean_text""": False, """add_prefix_space""": False}
def A ( self : Dict ):
"""simple docstring"""
super().setUp()
# fmt: off
__snake_case = ["こん", "こんに", "にちは", "ばんは", "世界,㔺界", "、", "。", "<BR>", "<SP>", "<TAB>", "<URL>", "<EMAIL>", "<TEL>", "<DATE>", "<PRICE>", "<BLOCK>", "<KIGOU>", "<U2000U2BFF>", "<|emoji1|>", "<unk>", "<|bagoftoken|>", "<|endoftext|>"]
# fmt: on
__snake_case = {"emoji": {"\ud83d\ude00": "<|emoji1|>"}, "emoji_inv": {"<|emoji1|>": "\ud83d\ude00"}} # 😀
__snake_case = {"unk_token": "<unk>"}
__snake_case = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
__snake_case = 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(a_ ) )
def A ( self : Any , **a_ : Union[str, Any] ):
"""simple docstring"""
kwargs.update(self.special_tokens_map )
return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **a_ )
def A ( self : Tuple , a_ : List[str] ):
"""simple docstring"""
__snake_case = "こんにちは、世界。 \nこんばんは、㔺界。😀"
__snake_case = "こんにちは、世界。 \nこんばんは、世界。😀"
return input_text, output_text
def A ( self : str , a_ : Tuple ):
"""simple docstring"""
__snake_case , __snake_case = self.get_input_output_texts(a_ )
__snake_case = tokenizer.encode(a_ , add_special_tokens=a_ )
__snake_case = tokenizer.decode(a_ , clean_up_tokenization_spaces=a_ )
return text, ids
def A ( self : Optional[Any] ):
"""simple docstring"""
pass # TODO add if relevant
def A ( self : int ):
"""simple docstring"""
pass # TODO add if relevant
def A ( self : Dict ):
"""simple docstring"""
pass # TODO add if relevant
def A ( self : List[str] ):
"""simple docstring"""
__snake_case = self.get_tokenizer()
# Testing tokenization
__snake_case = "こんにちは、世界。 こんばんは、㔺界。"
__snake_case = ["こん", "にちは", "、", "世界", "。", "<SP>", "こん", "ばんは", "、", "㔺界", "。"]
__snake_case = tokenizer.tokenize(a_ )
self.assertListEqual(a_ , a_ )
# Testing conversion to ids without special tokens
__snake_case = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6]
__snake_case = tokenizer.convert_tokens_to_ids(a_ )
self.assertListEqual(a_ , a_ )
# Testing conversion to ids with special tokens
__snake_case = tokens + [tokenizer.unk_token]
__snake_case = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19]
__snake_case = tokenizer.convert_tokens_to_ids(a_ )
self.assertListEqual(a_ , a_ )
def A ( self : Any ):
"""simple docstring"""
__snake_case = self.get_tokenizer()
# Testing tokenization
__snake_case = "こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。"
__snake_case = "こんにちは、、、、世界。こんばんは、、、、世界。"
__snake_case = tokenizer.encode(a_ )
__snake_case = tokenizer.decode(a_ )
self.assertEqual(a_ , a_ )
@slow
def A ( self : Dict ):
"""simple docstring"""
__snake_case = self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese" )
# Testing tokenization
__snake_case = "こんにちは、世界。"
__snake_case = "こんばんは、㔺界。😀"
__snake_case = "こんにちは、世界。こんばんは、世界。😀"
__snake_case = tokenizer.encode(prefix_text + input_text )
__snake_case = tokenizer.encode("" , prefix_text=prefix_text + input_text )
__snake_case = tokenizer.encode(a_ , prefix_text=a_ )
__snake_case = tokenizer.decode(a_ )
__snake_case = tokenizer.decode(a_ )
__snake_case = tokenizer.decode(a_ )
self.assertEqual(a_ , a_ )
self.assertEqual(a_ , a_ )
self.assertEqual(a_ , a_ )
@slow
def A ( self : Any ):
"""simple docstring"""
__snake_case = self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese" )
# Testing tokenization
__snake_case = "こんにちは、世界。"
__snake_case = "こんばんは、㔺界。😀"
__snake_case = len(tokenizer.encode(a_ ) ) - 2
__snake_case = len(tokenizer.encode(a_ ) ) - 2
__snake_case = [1] + [0] * (len_prefix + len_text + 1)
__snake_case = [1] * (len_prefix + len_text + 1) + [0]
__snake_case = [1] + [1] * (len_prefix) + [0] * (len_text + 1)
__snake_case = tokenizer(prefix_text + input_text ).token_type_ids
__snake_case = tokenizer("" , prefix_text=prefix_text + input_text ).token_type_ids
__snake_case = tokenizer(a_ , prefix_text=a_ ).token_type_ids
self.assertListEqual(a_ , a_ )
self.assertListEqual(a_ , a_ )
self.assertListEqual(a_ , a_ )
@slow
def A ( self : Dict ):
"""simple docstring"""
__snake_case = self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese" )
__snake_case = tokenizer.encode("あンいワ" )
__snake_case = tokenizer.encode("" , prefix_text="あンいワ" )
__snake_case = tokenizer.encode("いワ" , prefix_text="あン" )
self.assertEqual(tokenizer.decode(a_ ) , tokenizer.decode(a_ ) )
self.assertEqual(tokenizer.decode(a_ ) , tokenizer.decode(a_ ) )
self.assertNotEqual(a_ , a_ )
self.assertNotEqual(a_ , a_ )
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 : str ):
"""simple docstring"""
__snake_case = self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese" )
__snake_case = [["武田信玄", "は、"], ["織田信長", "の配下の、"]]
__snake_case = tokenizer(a_ , padding=a_ )
__snake_case = tokenizer.batch_encode_plus(a_ , padding=a_ )
# fmt: off
__snake_case = [[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]]
__snake_case = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]]
__snake_case = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]]
# fmt: on
self.assertListEqual(x_token.input_ids , a_ )
self.assertListEqual(x_token.token_type_ids , a_ )
self.assertListEqual(x_token.attention_mask , a_ )
self.assertListEqual(x_token_a.input_ids , a_ )
self.assertListEqual(x_token_a.token_type_ids , a_ )
self.assertListEqual(x_token_a.attention_mask , a_ )
def A ( self : List[str] ):
"""simple docstring"""
pass
def A ( self : int ):
"""simple docstring"""
pass
| 69 |
'''simple docstring'''
from ...processing_utils import ProcessorMixin
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = """SpeechT5FeatureExtractor"""
__SCREAMING_SNAKE_CASE = """SpeechT5Tokenizer"""
def __init__( self : List[Any] , a_ : str , a_ : str ):
"""simple docstring"""
super().__init__(a_ , a_ )
def __call__( self : Dict , *a_ : Tuple , **a_ : List[str] ):
"""simple docstring"""
__snake_case = kwargs.pop("audio" , a_ )
__snake_case = kwargs.pop("text" , a_ )
__snake_case = kwargs.pop("text_target" , a_ )
__snake_case = kwargs.pop("audio_target" , a_ )
__snake_case = kwargs.pop("sampling_rate" , a_ )
if audio is not None and text is not None:
raise ValueError(
"Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?" )
if audio_target is not None and text_target is not None:
raise ValueError(
"Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?" )
if audio is None and audio_target is None and text is None and text_target is None:
raise ValueError(
"You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process." )
if audio is not None:
__snake_case = self.feature_extractor(a_ , *a_ , sampling_rate=a_ , **a_ )
elif text is not None:
__snake_case = self.tokenizer(a_ , **a_ )
else:
__snake_case = None
if audio_target is not None:
__snake_case = self.feature_extractor(audio_target=a_ , *a_ , sampling_rate=a_ , **a_ )
__snake_case = targets["input_values"]
elif text_target is not None:
__snake_case = self.tokenizer(a_ , **a_ )
__snake_case = targets["input_ids"]
else:
__snake_case = None
if inputs is None:
return targets
if targets is not None:
__snake_case = labels
__snake_case = targets.get("attention_mask" )
if decoder_attention_mask is not None:
__snake_case = decoder_attention_mask
return inputs
def A ( self : List[str] , *a_ : str , **a_ : Dict ):
"""simple docstring"""
__snake_case = kwargs.pop("input_values" , a_ )
__snake_case = kwargs.pop("input_ids" , a_ )
__snake_case = kwargs.pop("labels" , a_ )
if input_values is not None and input_ids is not None:
raise ValueError("Cannot process both `input_values` and `input_ids` inputs." )
if input_values is None and input_ids is None and labels is None:
raise ValueError(
"You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded." )
if input_values is not None:
__snake_case = self.feature_extractor.pad(a_ , *a_ , **a_ )
elif input_ids is not None:
__snake_case = self.tokenizer.pad(a_ , **a_ )
else:
__snake_case = None
if labels is not None:
if "input_ids" in labels or (isinstance(a_ , a_ ) and "input_ids" in labels[0]):
__snake_case = self.tokenizer.pad(a_ , **a_ )
__snake_case = targets["input_ids"]
else:
__snake_case = self.feature_extractor.feature_size
__snake_case = self.feature_extractor.num_mel_bins
__snake_case = self.feature_extractor.pad(a_ , *a_ , **a_ )
__snake_case = feature_size_hack
__snake_case = targets["input_values"]
else:
__snake_case = None
if inputs is None:
return targets
if targets is not None:
__snake_case = labels
__snake_case = targets.get("attention_mask" )
if decoder_attention_mask is not None:
__snake_case = decoder_attention_mask
return inputs
def A ( self : List[str] , *a_ : Any , **a_ : List[str] ):
"""simple docstring"""
return self.tokenizer.batch_decode(*a_ , **a_ )
def A ( self : Optional[int] , *a_ : Union[str, Any] , **a_ : str ):
"""simple docstring"""
return self.tokenizer.decode(*a_ , **a_ )
| 69 | 1 |
'''simple docstring'''
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
a : Dict = logging.get_logger(__name__)
a : Tuple = {
'''google/mobilenet_v2_1.4_224''': '''https://huggingface.co/google/mobilenet_v2_1.4_224/resolve/main/config.json''',
'''google/mobilenet_v2_1.0_224''': '''https://huggingface.co/google/mobilenet_v2_1.0_224/resolve/main/config.json''',
'''google/mobilenet_v2_0.75_160''': '''https://huggingface.co/google/mobilenet_v2_0.75_160/resolve/main/config.json''',
'''google/mobilenet_v2_0.35_96''': '''https://huggingface.co/google/mobilenet_v2_0.35_96/resolve/main/config.json''',
# See all MobileNetV2 models at https://huggingface.co/models?filter=mobilenet_v2
}
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = """mobilenet_v2"""
def __init__( self : int , a_ : int=3 , a_ : Tuple=224 , a_ : List[str]=1.0 , a_ : Any=8 , a_ : int=8 , a_ : Tuple=6 , a_ : int=32 , a_ : List[str]=True , a_ : Optional[int]=True , a_ : Any="relu6" , a_ : Tuple=True , a_ : List[Any]=0.8 , a_ : Any=0.02 , a_ : Any=0.001 , a_ : Dict=255 , **a_ : str , ):
"""simple docstring"""
super().__init__(**a_ )
if depth_multiplier <= 0:
raise ValueError("depth_multiplier must be greater than zero." )
__snake_case = num_channels
__snake_case = image_size
__snake_case = depth_multiplier
__snake_case = depth_divisible_by
__snake_case = min_depth
__snake_case = expand_ratio
__snake_case = output_stride
__snake_case = first_layer_is_expansion
__snake_case = finegrained_output
__snake_case = hidden_act
__snake_case = tf_padding
__snake_case = classifier_dropout_prob
__snake_case = initializer_range
__snake_case = layer_norm_eps
__snake_case = semantic_loss_ignore_index
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = version.parse("""1.11""" )
@property
def A ( self : Optional[int] ):
"""simple docstring"""
return OrderedDict([("pixel_values", {0: "batch"})] )
@property
def A ( self : Optional[int] ):
"""simple docstring"""
if self.task == "image-classification":
return OrderedDict([("logits", {0: "batch"})] )
else:
return OrderedDict([("last_hidden_state", {0: "batch"}), ("pooler_output", {0: "batch"})] )
@property
def A ( self : Optional[int] ):
"""simple docstring"""
return 1e-4
| 69 |
'''simple docstring'''
import re
from pathlib import Path
from unittest import TestCase
import pytest
@pytest.mark.integration
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def A ( self : Optional[Any] , a_ : str ):
"""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 A ( self : Any , a_ : str ):
"""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 A ( self : Optional[int] ):
"""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 A ( self : Optional[Any] ):
"""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.''' )
| 69 | 1 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
a : Optional[Any] = {
'''configuration_rag''': ['''RagConfig'''],
'''retrieval_rag''': ['''RagRetriever'''],
'''tokenization_rag''': ['''RagTokenizer'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : Tuple = [
'''RagModel''',
'''RagPreTrainedModel''',
'''RagSequenceForGeneration''',
'''RagTokenForGeneration''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : Dict = [
'''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
a : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 69 |
'''simple docstring'''
import os
from shutil import copyfile
from typing import List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
a : Optional[Any] = logging.get_logger(__name__)
a : Dict = {'''vocab_file''': '''sentencepiece.model'''}
a : Tuple = {
'''vocab_file''': {
'''google/rembert''': '''https://huggingface.co/google/rembert/resolve/main/sentencepiece.model''',
},
}
a : str = {
'''google/rembert''': 256,
}
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES
__SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP
__SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__( self : Optional[Any] , a_ : int , a_ : Any=False , a_ : List[Any]=True , a_ : List[Any]=True , a_ : List[Any]="[CLS]" , a_ : List[Any]="[SEP]" , a_ : List[Any]="[UNK]" , a_ : str="[SEP]" , a_ : List[str]="[PAD]" , a_ : Optional[int]="[CLS]" , a_ : List[str]="[MASK]" , **a_ : str , ):
"""simple docstring"""
super().__init__(
do_lower_case=a_ , remove_space=a_ , keep_accents=a_ , bos_token=a_ , eos_token=a_ , unk_token=a_ , sep_token=a_ , pad_token=a_ , cls_token=a_ , mask_token=a_ , **a_ , )
__snake_case = do_lower_case
__snake_case = remove_space
__snake_case = keep_accents
__snake_case = vocab_file
__snake_case = spm.SentencePieceProcessor()
self.sp_model.Load(a_ )
@property
def A ( self : Optional[Any] ):
"""simple docstring"""
return len(self.sp_model )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = {self.convert_ids_to_tokens(a_ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self : Dict ):
"""simple docstring"""
__snake_case = self.__dict__.copy()
__snake_case = None
return state
def __setstate__( self : str , a_ : Optional[int] ):
"""simple docstring"""
__snake_case = d
__snake_case = spm.SentencePieceProcessor()
self.sp_model.Load(self.vocab_file )
def A ( self : Tuple , a_ : Optional[int] , a_ : int=False ):
"""simple docstring"""
__snake_case = self.sp_model.EncodeAsPieces(a_ )
return pieces
def A ( self : Any , a_ : Optional[Any] ):
"""simple docstring"""
return self.sp_model.PieceToId(a_ )
def A ( self : Optional[Any] , a_ : List[str] ):
"""simple docstring"""
return self.sp_model.IdToPiece(a_ )
def A ( self : Optional[Any] , a_ : int ):
"""simple docstring"""
__snake_case = self.sp_model.decode_pieces(a_ )
return out_string
def A ( self : Union[str, Any] , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
__snake_case = [self.sep_token_id]
__snake_case = [self.cls_token_id]
if token_ids_a is None:
return cls + token_ids_a + sep
return cls + token_ids_a + sep + token_ids_a + sep
def A ( self : List[str] , a_ : List[int] , a_ : Optional[List[int]] = None , a_ : bool = False ):
"""simple docstring"""
if already_has_special_tokens:
if token_ids_a is not None:
raise ValueError(
"You should not supply a second sequence if the provided sequence of "
"ids is already formatted with special tokens for the model." )
return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]
if token_ids_a is not None:
return [1] + ([0] * len(a_ )) + [1] + ([0] * len(a_ )) + [1]
return [1] + ([0] * len(a_ )) + [1]
def A ( self : Tuple , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
__snake_case = [self.sep_token_id]
__snake_case = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def A ( self : List[Any] , a_ : str , a_ : Optional[str] = None ):
"""simple docstring"""
if not os.path.isdir(a_ ):
logger.error("Vocabulary path ({}) should be a directory".format(a_ ) )
return
__snake_case = 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_ ):
copyfile(self.vocab_file , a_ )
return (out_vocab_file,)
| 69 | 1 |
'''simple docstring'''
import numpy as np
def __UpperCAmelCase ( _UpperCAmelCase : np.array ) -> np.array:
return (2 / (1 + np.exp(-2 * vector ))) - 1
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 |
'''simple docstring'''
import os
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from huggingface_hub import HfFolder, delete_repo
from huggingface_hub.file_download import http_get
from requests.exceptions import HTTPError
from transformers import (
AlbertTokenizer,
AutoTokenizer,
BertTokenizer,
BertTokenizerFast,
GPTaTokenizerFast,
is_tokenizers_available,
)
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers
from transformers.tokenization_utils import Trie
sys.path.append(str(Path(__file__).parent.parent / '''utils'''))
from test_module.custom_tokenization import CustomTokenizer # noqa E402
if is_tokenizers_available():
from test_module.custom_tokenization_fast import CustomTokenizerFast
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = mock.Mock()
__snake_case = 500
__snake_case = {}
__snake_case = HTTPError
__snake_case = {}
# Download this model to make sure it's in the cache.
__snake_case = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" )
# Under the mock environment we get a 500 error when trying to reach the tokenizer.
with mock.patch("requests.Session.request" , return_value=a_ ) as mock_head:
__snake_case = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" )
# This check we did call the fake head request
mock_head.assert_called()
@require_tokenizers
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = mock.Mock()
__snake_case = 500
__snake_case = {}
__snake_case = HTTPError
__snake_case = {}
# Download this model to make sure it's in the cache.
__snake_case = GPTaTokenizerFast.from_pretrained("gpt2" )
# Under the mock environment we get a 500 error when trying to reach the tokenizer.
with mock.patch("requests.Session.request" , return_value=a_ ) as mock_head:
__snake_case = GPTaTokenizerFast.from_pretrained("gpt2" )
# This check we did call the fake head request
mock_head.assert_called()
def A ( self : Optional[Any] ):
"""simple docstring"""
try:
__snake_case = tempfile.mktemp()
with open(a_ , "wb" ) as f:
http_get("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" , a_ )
__snake_case = AlbertTokenizer.from_pretrained(a_ )
finally:
os.remove(a_ )
# Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in
# the current folder and have the right name.
if os.path.isfile("tokenizer.json" ):
# We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it.
return
try:
with open("tokenizer.json" , "wb" ) as f:
http_get("https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json" , a_ )
__snake_case = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" )
# The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000
self.assertEqual(tokenizer.vocab_size , 1_000 )
# Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file.
finally:
os.remove("tokenizer.json" )
def A ( self : str ):
"""simple docstring"""
__snake_case = AlbertTokenizer.from_pretrained("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" )
@is_staging_test
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
__SCREAMING_SNAKE_CASE = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""]
@classmethod
def A ( cls : List[Any] ):
"""simple docstring"""
__snake_case = TOKEN
HfFolder.save_token(a_ )
@classmethod
def A ( cls : List[Any] ):
"""simple docstring"""
try:
delete_repo(token=cls._token , repo_id="test-tokenizer" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="valid_org/test-tokenizer-org" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="test-dynamic-tokenizer" )
except HTTPError:
pass
def A ( self : int ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = BertTokenizer(a_ )
tokenizer.push_to_hub("test-tokenizer" , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
# Reset repo
delete_repo(token=self._token , repo_id="test-tokenizer" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(a_ , repo_id="test-tokenizer" , push_to_hub=a_ , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
def A ( self : int ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = BertTokenizer(a_ )
tokenizer.push_to_hub("valid_org/test-tokenizer-org" , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
# Reset repo
delete_repo(token=self._token , repo_id="valid_org/test-tokenizer-org" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(
a_ , repo_id="valid_org/test-tokenizer-org" , push_to_hub=a_ , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
@require_tokenizers
def A ( self : List[str] ):
"""simple docstring"""
CustomTokenizer.register_for_auto_class()
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = CustomTokenizer(a_ )
# No fast custom tokenizer
tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token )
__snake_case = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=a_ )
# Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module
self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizer" )
# Fast and slow custom tokenizer
CustomTokenizerFast.register_for_auto_class()
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = BertTokenizerFast.from_pretrained(a_ )
bert_tokenizer.save_pretrained(a_ )
__snake_case = CustomTokenizerFast.from_pretrained(a_ )
tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token )
__snake_case = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=a_ )
# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizerFast" )
__snake_case = AutoTokenizer.from_pretrained(
f'''{USER}/test-dynamic-tokenizer''' , use_fast=a_ , trust_remote_code=a_ )
# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizer" )
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def A ( self : Optional[int] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("Hello 友達" )
self.assertEqual(trie.data , {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}} )
trie.add("Hello" )
trie.data
self.assertEqual(trie.data , {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}} )
def A ( self : str ):
"""simple docstring"""
__snake_case = Trie()
self.assertEqual(trie.split("[CLS] This is a extra_id_100" ) , ["[CLS] This is a extra_id_100"] )
trie.add("[CLS]" )
trie.add("extra_id_1" )
trie.add("extra_id_100" )
self.assertEqual(trie.split("[CLS] This is a extra_id_100" ) , ["[CLS]", " This is a ", "extra_id_100"] )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("A" )
self.assertEqual(trie.split("ABC" ) , ["A", "BC"] )
self.assertEqual(trie.split("BCA" ) , ["BC", "A"] )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("TOKEN]" )
trie.add("[SPECIAL_TOKEN]" )
self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] )
def A ( self : str ):
"""simple docstring"""
__snake_case = Trie()
trie.add("A" )
trie.add("P" )
trie.add("[SPECIAL_TOKEN]" )
self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] )
def A ( self : Optional[int] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("AB" )
trie.add("B" )
trie.add("C" )
self.assertEqual(trie.split("ABC" ) , ["AB", "C"] )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = Trie()
trie.add("ABC" )
trie.add("B" )
trie.add("CD" )
self.assertEqual(trie.split("ABCD" ) , ["ABC", "D"] )
def A ( self : Any ):
"""simple docstring"""
__snake_case = Trie()
__snake_case = trie.cut_text("ABC" , [0, 0, 2, 1, 2, 3] )
self.assertEqual(a_ , ["AB", "C"] )
| 69 | 1 |
'''simple docstring'''
a : Dict = range(2, 20 + 1)
a : Optional[int] = [10**k for k in range(ks[-1] + 1)]
a : dict[int, dict[int, list[list[int]]]] = {}
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Dict , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[Any] ) -> int:
__snake_case = sum(a_i[j] for j in range(_UpperCAmelCase , len(_UpperCAmelCase ) ) )
__snake_case = sum(a_i[j] * base[j] for j in range(min(len(_UpperCAmelCase ) , _UpperCAmelCase ) ) )
__snake_case , __snake_case = 0, 0
__snake_case = n - i
__snake_case = memo.get(_UpperCAmelCase )
if sub_memo is not None:
__snake_case = sub_memo.get(_UpperCAmelCase )
if jumps is not None and len(_UpperCAmelCase ) > 0:
# find and make the largest jump without going over
__snake_case = -1
for _k in range(len(_UpperCAmelCase ) - 1 , -1 , -1 ):
if jumps[_k][2] <= k and jumps[_k][1] <= max_dn:
__snake_case = _k
break
if max_jump >= 0:
__snake_case , __snake_case , __snake_case = jumps[max_jump]
# since the difference between jumps is cached, add c
__snake_case = diff + c
for j in range(min(_UpperCAmelCase , len(_UpperCAmelCase ) ) ):
__snake_case , __snake_case = divmod(_UpperCAmelCase , 10 )
if new_c > 0:
add(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
else:
__snake_case = []
else:
__snake_case = {c: []}
__snake_case = sub_memo
if dn >= max_dn or c + diff >= base[k]:
return diff, dn
if k > ks[0]:
while True:
# keep doing smaller jumps
__snake_case , __snake_case = next_term(_UpperCAmelCase , k - 1 , i + dn , _UpperCAmelCase )
diff += _diff
dn += terms_jumped
if dn >= max_dn or c + diff >= base[k]:
break
else:
# would be too small a jump, just compute sequential terms instead
__snake_case , __snake_case = compute(_UpperCAmelCase , _UpperCAmelCase , i + dn , _UpperCAmelCase )
diff += _diff
dn += terms_jumped
__snake_case = sub_memo[c]
# keep jumps sorted by # of terms skipped
__snake_case = 0
while j < len(_UpperCAmelCase ):
if jumps[j][1] > dn:
break
j += 1
# cache the jump for this value digitsum(b) and c
sub_memo[c].insert(_UpperCAmelCase , (diff, dn, k) )
return (diff, dn)
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[int] ) -> Optional[int]:
if i >= n:
return 0, i
if k > len(_UpperCAmelCase ):
a_i.extend([0 for _ in range(k - len(_UpperCAmelCase ) )] )
# note: a_i -> b * 10^k + c
# ds_b -> digitsum(b)
# ds_c -> digitsum(c)
__snake_case = i
__snake_case , __snake_case , __snake_case = 0, 0, 0
for j in range(len(_UpperCAmelCase ) ):
if j >= k:
ds_b += a_i[j]
else:
ds_c += a_i[j]
while i < n:
i += 1
__snake_case = ds_c + ds_b
diff += addend
__snake_case = 0
for j in range(_UpperCAmelCase ):
__snake_case = a_i[j] + addend
__snake_case , __snake_case = divmod(_UpperCAmelCase , 10 )
ds_c += a_i[j]
if addend > 0:
break
if addend > 0:
add(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
return diff, i - start_i
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Tuple , _UpperCAmelCase : str ) -> Tuple:
for j in range(_UpperCAmelCase , len(_UpperCAmelCase ) ):
__snake_case = digits[j] + addend
if s >= 10:
__snake_case , __snake_case = divmod(_UpperCAmelCase , 10 )
__snake_case = addend // 10 + quotient
else:
__snake_case = s
__snake_case = addend // 10
if addend == 0:
break
while addend > 0:
__snake_case , __snake_case = divmod(_UpperCAmelCase , 10 )
digits.append(_UpperCAmelCase )
def __UpperCAmelCase ( _UpperCAmelCase : int = 10**15 ) -> int:
__snake_case = [1]
__snake_case = 1
__snake_case = 0
while True:
__snake_case , __snake_case = next_term(_UpperCAmelCase , 20 , i + dn , _UpperCAmelCase )
dn += terms_jumped
if dn == n - i:
break
__snake_case = 0
for j in range(len(_UpperCAmelCase ) ):
a_n += digits[j] * 10**j
return a_n
if __name__ == "__main__":
print(F'''{solution() = }''')
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> int:
assert (
isinstance(_UpperCAmelCase , _UpperCAmelCase ) and number_of_steps > 0
), F'''number_of_steps needs to be positive integer, your input {number_of_steps}'''
if number_of_steps == 1:
return 1
__snake_case , __snake_case = 1, 1
for _ in range(number_of_steps - 1 ):
__snake_case , __snake_case = current + previous, current
return current
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 | 1 |
'''simple docstring'''
import warnings
from ...utils import logging
from .image_processing_mobilevit import MobileViTImageProcessor
a : Dict = logging.get_logger(__name__)
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def __init__( self : Dict , *a_ : Any , **a_ : Tuple ):
"""simple docstring"""
warnings.warn(
"The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers."
" Please use MobileViTImageProcessor instead." , a_ , )
super().__init__(*a_ , **a_ )
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> str:
return " ".join(
"".join(word[::-1] ) if len(_UpperCAmelCase ) > 4 else word for word in sentence.split() )
if __name__ == "__main__":
import doctest
doctest.testmod()
print(reverse_long_words('''Hey wollef sroirraw'''))
| 69 | 1 |
'''simple docstring'''
import torch
from diffusers import DDPMParallelScheduler
from .test_schedulers import SchedulerCommonTest
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = (DDPMParallelScheduler,)
def A ( self : Tuple , **a_ : Union[str, Any] ):
"""simple docstring"""
__snake_case = {
"num_train_timesteps": 1_000,
"beta_start": 0.0001,
"beta_end": 0.02,
"beta_schedule": "linear",
"variance_type": "fixed_small",
"clip_sample": True,
}
config.update(**a_ )
return config
def A ( self : int ):
"""simple docstring"""
for timesteps in [1, 5, 100, 1_000]:
self.check_over_configs(num_train_timesteps=a_ )
def A ( self : Union[str, Any] ):
"""simple docstring"""
for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ):
self.check_over_configs(beta_start=a_ , beta_end=a_ )
def A ( self : List[Any] ):
"""simple docstring"""
for schedule in ["linear", "squaredcos_cap_v2"]:
self.check_over_configs(beta_schedule=a_ )
def A ( self : Dict ):
"""simple docstring"""
for variance in ["fixed_small", "fixed_large", "other"]:
self.check_over_configs(variance_type=a_ )
def A ( self : List[Any] ):
"""simple docstring"""
for clip_sample in [True, False]:
self.check_over_configs(clip_sample=a_ )
def A ( self : List[str] ):
"""simple docstring"""
self.check_over_configs(thresholding=a_ )
for threshold in [0.5, 1.0, 2.0]:
for prediction_type in ["epsilon", "sample", "v_prediction"]:
self.check_over_configs(
thresholding=a_ , prediction_type=a_ , sample_max_value=a_ , )
def A ( self : Optional[Any] ):
"""simple docstring"""
for prediction_type in ["epsilon", "sample", "v_prediction"]:
self.check_over_configs(prediction_type=a_ )
def A ( self : List[str] ):
"""simple docstring"""
for t in [0, 500, 999]:
self.check_over_forward(time_step=a_ )
def A ( self : Any ):
"""simple docstring"""
__snake_case = self.scheduler_classes[0]
__snake_case = self.get_scheduler_config()
__snake_case = scheduler_class(**a_ )
assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1e-5
assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.00979 ) ) < 1e-5
assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.02 ) ) < 1e-5
def A ( self : Dict ):
"""simple docstring"""
__snake_case = self.scheduler_classes[0]
__snake_case = self.get_scheduler_config()
__snake_case = scheduler_class(**a_ )
__snake_case = len(a_ )
__snake_case = self.dummy_model()
__snake_case = self.dummy_sample_deter
__snake_case = self.dummy_sample_deter + 0.1
__snake_case = self.dummy_sample_deter - 0.1
__snake_case = samplea.shape[0]
__snake_case = torch.stack([samplea, samplea, samplea] , dim=0 )
__snake_case = torch.arange(a_ )[0:3, None].repeat(1 , a_ )
__snake_case = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) )
__snake_case = scheduler.batch_step_no_noise(a_ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) )
__snake_case = torch.sum(torch.abs(a_ ) )
__snake_case = torch.mean(torch.abs(a_ ) )
assert abs(result_sum.item() - 1153.1833 ) < 1e-2
assert abs(result_mean.item() - 0.5005 ) < 1e-3
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = self.scheduler_classes[0]
__snake_case = self.get_scheduler_config()
__snake_case = scheduler_class(**a_ )
__snake_case = len(a_ )
__snake_case = self.dummy_model()
__snake_case = self.dummy_sample_deter
__snake_case = torch.manual_seed(0 )
for t in reversed(range(a_ ) ):
# 1. predict noise residual
__snake_case = model(a_ , a_ )
# 2. predict previous mean of sample x_t-1
__snake_case = scheduler.step(a_ , a_ , a_ , generator=a_ ).prev_sample
__snake_case = pred_prev_sample
__snake_case = torch.sum(torch.abs(a_ ) )
__snake_case = torch.mean(torch.abs(a_ ) )
assert abs(result_sum.item() - 258.9606 ) < 1e-2
assert abs(result_mean.item() - 0.3372 ) < 1e-3
def A ( self : Dict ):
"""simple docstring"""
__snake_case = self.scheduler_classes[0]
__snake_case = self.get_scheduler_config(prediction_type="v_prediction" )
__snake_case = scheduler_class(**a_ )
__snake_case = len(a_ )
__snake_case = self.dummy_model()
__snake_case = self.dummy_sample_deter
__snake_case = torch.manual_seed(0 )
for t in reversed(range(a_ ) ):
# 1. predict noise residual
__snake_case = model(a_ , a_ )
# 2. predict previous mean of sample x_t-1
__snake_case = scheduler.step(a_ , a_ , a_ , generator=a_ ).prev_sample
__snake_case = pred_prev_sample
__snake_case = torch.sum(torch.abs(a_ ) )
__snake_case = torch.mean(torch.abs(a_ ) )
assert abs(result_sum.item() - 202.0296 ) < 1e-2
assert abs(result_mean.item() - 0.2631 ) < 1e-3
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = self.scheduler_classes[0]
__snake_case = self.get_scheduler_config()
__snake_case = scheduler_class(**a_ )
__snake_case = [100, 87, 50, 1, 0]
scheduler.set_timesteps(timesteps=a_ )
__snake_case = scheduler.timesteps
for i, timestep in enumerate(a_ ):
if i == len(a_ ) - 1:
__snake_case = -1
else:
__snake_case = timesteps[i + 1]
__snake_case = scheduler.previous_timestep(a_ )
__snake_case = prev_t.item()
self.assertEqual(a_ , a_ )
def A ( self : str ):
"""simple docstring"""
__snake_case = self.scheduler_classes[0]
__snake_case = self.get_scheduler_config()
__snake_case = scheduler_class(**a_ )
__snake_case = [100, 87, 50, 51, 0]
with self.assertRaises(a_ , msg="`custom_timesteps` must be in descending order." ):
scheduler.set_timesteps(timesteps=a_ )
def A ( self : Any ):
"""simple docstring"""
__snake_case = self.scheduler_classes[0]
__snake_case = self.get_scheduler_config()
__snake_case = scheduler_class(**a_ )
__snake_case = [100, 87, 50, 1, 0]
__snake_case = len(a_ )
with self.assertRaises(a_ , msg="Can only pass one of `num_inference_steps` or `custom_timesteps`." ):
scheduler.set_timesteps(num_inference_steps=a_ , timesteps=a_ )
def A ( self : Any ):
"""simple docstring"""
__snake_case = self.scheduler_classes[0]
__snake_case = self.get_scheduler_config()
__snake_case = scheduler_class(**a_ )
__snake_case = [scheduler.config.num_train_timesteps]
with self.assertRaises(
a_ , msg="`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}" , ):
scheduler.set_timesteps(timesteps=a_ )
| 69 |
'''simple docstring'''
import unittest
from transformers import MPNetConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
MPNetForMaskedLM,
MPNetForMultipleChoice,
MPNetForQuestionAnswering,
MPNetForSequenceClassification,
MPNetForTokenClassification,
MPNetModel,
)
class SCREAMING_SNAKE_CASE__ :
def __init__( self : str , a_ : Any , a_ : Union[str, Any]=13 , a_ : Any=7 , a_ : Any=True , a_ : Dict=True , a_ : Union[str, Any]=False , a_ : Tuple=True , a_ : str=99 , a_ : Tuple=64 , a_ : Tuple=5 , a_ : Union[str, Any]=4 , a_ : Dict=64 , a_ : Union[str, Any]="gelu" , a_ : Dict=0.1 , a_ : List[str]=0.1 , a_ : Dict=512 , a_ : Tuple=16 , a_ : str=2 , a_ : Any=0.02 , a_ : List[Any]=3 , a_ : Tuple=4 , a_ : Optional[int]=None , ):
"""simple docstring"""
__snake_case = parent
__snake_case = batch_size
__snake_case = seq_length
__snake_case = is_training
__snake_case = use_input_mask
__snake_case = use_token_type_ids
__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_act
__snake_case = hidden_dropout_prob
__snake_case = attention_probs_dropout_prob
__snake_case = max_position_embeddings
__snake_case = type_vocab_size
__snake_case = type_sequence_label_size
__snake_case = initializer_range
__snake_case = num_labels
__snake_case = num_choices
__snake_case = scope
def A ( self : int ):
"""simple docstring"""
return MPNetConfig.from_pretrained("microsoft/mpnet-base" )
def A ( self : str ):
"""simple docstring"""
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__snake_case = None
if self.use_input_mask:
__snake_case = random_attention_mask([self.batch_size, self.seq_length] )
__snake_case = None
__snake_case = None
__snake_case = None
if self.use_labels:
__snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__snake_case = ids_tensor([self.batch_size] , self.num_choices )
__snake_case = self.get_config()
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
def A ( self : List[str] ):
"""simple docstring"""
return MPNetConfig(
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 , initializer_range=self.initializer_range , )
def A ( self : Tuple , a_ : int , a_ : str , a_ : Optional[int] , a_ : List[Any] , a_ : str , a_ : Optional[Any] ):
"""simple docstring"""
__snake_case = MPNetModel(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , a_ )
__snake_case = model(a_ )
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 A ( self : Any , a_ : int , a_ : Tuple , a_ : str , a_ : int , a_ : str , a_ : List[Any] ):
"""simple docstring"""
__snake_case = MPNetForQuestionAnswering(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(
a_ , attention_mask=a_ , start_positions=a_ , end_positions=a_ , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def A ( self : Any , a_ : Any , a_ : int , a_ : Union[str, Any] , a_ : Dict , a_ : Optional[Any] , a_ : Any ):
"""simple docstring"""
__snake_case = self.num_labels
__snake_case = MPNetForSequenceClassification(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def A ( self : Optional[Any] , a_ : Any , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : List[Any] , a_ : List[Any] ):
"""simple docstring"""
__snake_case = self.num_choices
__snake_case = MPNetForMultipleChoice(config=a_ )
model.to(a_ )
model.eval()
__snake_case = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__snake_case = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__snake_case = model(
a_ , attention_mask=a_ , labels=a_ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def A ( self : Dict , a_ : List[str] , a_ : str , a_ : Union[str, Any] , a_ : str , a_ : Optional[int] , a_ : Optional[Any] ):
"""simple docstring"""
__snake_case = self.num_labels
__snake_case = MPNetForTokenClassification(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.prepare_config_and_inputs()
((__snake_case) , (__snake_case) , (__snake_case) , (__snake_case) , (__snake_case) , (__snake_case)) = config_and_inputs
__snake_case = {"input_ids": input_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = (
(
MPNetForMaskedLM,
MPNetForMultipleChoice,
MPNetForQuestionAnswering,
MPNetForSequenceClassification,
MPNetForTokenClassification,
MPNetModel,
)
if is_torch_available()
else ()
)
__SCREAMING_SNAKE_CASE = (
{
"""feature-extraction""": MPNetModel,
"""fill-mask""": MPNetForMaskedLM,
"""question-answering""": MPNetForQuestionAnswering,
"""text-classification""": MPNetForSequenceClassification,
"""token-classification""": MPNetForTokenClassification,
"""zero-shot""": MPNetForSequenceClassification,
}
if is_torch_available()
else {}
)
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = True
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = MPNetModelTester(self )
__snake_case = ConfigTester(self , config_class=a_ , hidden_size=37 )
def A ( self : List[Any] ):
"""simple docstring"""
self.config_tester.run_common_tests()
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_model(*a_ )
def A ( self : Dict ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_sequence_classification(*a_ )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_multiple_choice(*a_ )
def A ( self : int ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_token_classification(*a_ )
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_question_answering(*a_ )
@require_torch
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
@slow
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = MPNetModel.from_pretrained("microsoft/mpnet-base" )
__snake_case = torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] )
__snake_case = model(a_ )[0]
__snake_case = torch.Size((1, 11, 768) )
self.assertEqual(output.shape , a_ )
__snake_case = torch.tensor(
[[[-0.0550, 0.1943, -0.0740], [-0.0562, 0.2211, -0.0579], [-0.0437, 0.3337, -0.0641]]] )
# compare the actual values for a slice.
self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) )
| 69 | 1 |
'''simple docstring'''
from typing import List, Optional, Tuple
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_herbert import HerbertTokenizer
a : str = logging.get_logger(__name__)
a : int = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''}
a : Optional[Any] = {
'''vocab_file''': {
'''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json'''
},
'''merges_file''': {
'''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt'''
},
}
a : Union[str, Any] = {'''allegro/herbert-base-cased''': 514}
a : str = {}
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES
__SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP
__SCREAMING_SNAKE_CASE = PRETRAINED_INIT_CONFIGURATION
__SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__SCREAMING_SNAKE_CASE = HerbertTokenizer
def __init__( self : Optional[Any] , a_ : str=None , a_ : Dict=None , a_ : Any=None , a_ : Any="<s>" , a_ : List[str]="<unk>" , a_ : int="<pad>" , a_ : Dict="<mask>" , a_ : Optional[int]="</s>" , **a_ : Optional[int] , ):
"""simple docstring"""
super().__init__(
a_ , a_ , tokenizer_file=a_ , cls_token=a_ , unk_token=a_ , pad_token=a_ , mask_token=a_ , sep_token=a_ , **a_ , )
def A ( self : Optional[Any] , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
__snake_case = [self.cls_token_id]
__snake_case = [self.sep_token_id]
if token_ids_a is None:
return cls + token_ids_a + sep
return cls + token_ids_a + sep + token_ids_a + sep
def A ( self : Tuple , a_ : List[int] , a_ : Optional[List[int]] = None , a_ : bool = False ):
"""simple docstring"""
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=a_ , token_ids_a=a_ , already_has_special_tokens=a_ )
if token_ids_a is None:
return [1] + ([0] * len(a_ )) + [1]
return [1] + ([0] * len(a_ )) + [1] + ([0] * len(a_ )) + [1]
def A ( self : Optional[int] , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
__snake_case = [self.sep_token_id]
__snake_case = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def A ( self : Union[str, Any] , a_ : str , a_ : Optional[str] = None ):
"""simple docstring"""
__snake_case = self._tokenizer.model.save(a_ , name=a_ )
return tuple(a_ )
| 69 |
'''simple docstring'''
# Logistic Regression from scratch
# In[62]:
# In[63]:
# importing all the required libraries
import numpy as np
from matplotlib import pyplot as plt
from sklearn import datasets
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> Optional[int]:
return 1 / (1 + np.exp(-z ))
def __UpperCAmelCase ( _UpperCAmelCase : Tuple , _UpperCAmelCase : Dict ) -> List[str]:
return (-y * np.log(_UpperCAmelCase ) - (1 - y) * np.log(1 - h )).mean()
def __UpperCAmelCase ( _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : List[Any] ) -> Optional[Any]:
__snake_case = np.dot(_UpperCAmelCase , _UpperCAmelCase )
return np.sum(y * scores - np.log(1 + np.exp(_UpperCAmelCase ) ) )
def __UpperCAmelCase ( _UpperCAmelCase : List[Any] , _UpperCAmelCase : str , _UpperCAmelCase : Dict , _UpperCAmelCase : List[str]=7_00_00 ) -> Union[str, Any]:
__snake_case = np.zeros(x.shape[1] )
for iterations in range(_UpperCAmelCase ):
__snake_case = np.dot(_UpperCAmelCase , _UpperCAmelCase )
__snake_case = sigmoid_function(_UpperCAmelCase )
__snake_case = np.dot(x.T , h - y ) / y.size
__snake_case = theta - alpha * gradient # updating the weights
__snake_case = np.dot(_UpperCAmelCase , _UpperCAmelCase )
__snake_case = sigmoid_function(_UpperCAmelCase )
__snake_case = cost_function(_UpperCAmelCase , _UpperCAmelCase )
if iterations % 1_00 == 0:
print(F'''loss: {j} \t''' ) # printing the loss after every 100 iterations
return theta
# In[68]:
if __name__ == "__main__":
a : int = datasets.load_iris()
a : int = iris.data[:, :2]
a : Optional[Any] = (iris.target != 0) * 1
a : Tuple = 0.1
a : List[str] = logistic_reg(alpha, x, y, max_iterations=70_000)
print('''theta: ''', theta) # printing the theta i.e our weights vector
def __UpperCAmelCase ( _UpperCAmelCase : Optional[int] ) -> Union[str, Any]:
return sigmoid_function(
np.dot(_UpperCAmelCase , _UpperCAmelCase ) ) # predicting the value of probability from the logistic regression algorithm
plt.figure(figsize=(10, 6))
plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color='''b''', label='''0''')
plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color='''r''', label='''1''')
((a) , (a)) : Any = (x[:, 0].min(), x[:, 0].max())
((a) , (a)) : Any = (x[:, 1].min(), x[:, 1].max())
((a) , (a)) : Any = np.meshgrid(np.linspace(xa_min, xa_max), np.linspace(xa_min, xa_max))
a : Optional[Any] = np.c_[xxa.ravel(), xxa.ravel()]
a : List[Any] = predict_prob(grid).reshape(xxa.shape)
plt.contour(xxa, xxa, probs, [0.5], linewidths=1, colors='''black''')
plt.legend()
plt.show()
| 69 | 1 |
'''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.
from pathlib import Path
import torch
from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter
a : List[str] = '''Create a default config file for Accelerate with only a few flags set.'''
def __UpperCAmelCase ( _UpperCAmelCase : Any="no" , _UpperCAmelCase : str = default_json_config_file , _UpperCAmelCase : bool = False ) -> Tuple:
__snake_case = Path(_UpperCAmelCase )
path.parent.mkdir(parents=_UpperCAmelCase , exist_ok=_UpperCAmelCase )
if path.exists():
print(
F'''Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.''' )
return False
__snake_case = mixed_precision.lower()
if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
raise ValueError(
F'''`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}''' )
__snake_case = {
"compute_environment": "LOCAL_MACHINE",
"mixed_precision": mixed_precision,
}
if torch.cuda.is_available():
__snake_case = torch.cuda.device_count()
__snake_case = num_gpus
__snake_case = False
if num_gpus > 1:
__snake_case = "MULTI_GPU"
else:
__snake_case = "NO"
elif is_xpu_available() and use_xpu:
__snake_case = torch.xpu.device_count()
__snake_case = num_xpus
__snake_case = False
if num_xpus > 1:
__snake_case = "MULTI_XPU"
else:
__snake_case = "NO"
elif is_npu_available():
__snake_case = torch.npu.device_count()
__snake_case = num_npus
__snake_case = False
if num_npus > 1:
__snake_case = "MULTI_NPU"
else:
__snake_case = "NO"
else:
__snake_case = 0
__snake_case = True
__snake_case = 1
__snake_case = "NO"
__snake_case = ClusterConfig(**_UpperCAmelCase )
config.to_json_file(_UpperCAmelCase )
return path
def __UpperCAmelCase ( _UpperCAmelCase : Optional[int] , _UpperCAmelCase : List[str] ) -> List[Any]:
__snake_case = parser.add_parser("default" , parents=_UpperCAmelCase , help=_UpperCAmelCase , formatter_class=_UpperCAmelCase )
parser.add_argument(
"--config_file" , default=_UpperCAmelCase , 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'."
) , dest="save_location" , )
parser.add_argument(
"--mixed_precision" , choices=["no", "fp16", "bf16"] , type=_UpperCAmelCase , help="Whether or not to use mixed precision training. "
"Choose between FP16 and BF16 (bfloat16) training. "
"BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later." , default="no" , )
parser.set_defaults(func=_UpperCAmelCase )
return parser
def __UpperCAmelCase ( _UpperCAmelCase : List[Any] ) -> List[str]:
__snake_case = write_basic_config(args.mixed_precision , args.save_location )
if config_file:
print(F'''accelerate configuration saved at {config_file}''' )
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> bool:
return number & 1 == 0
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 | 1 |
'''simple docstring'''
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 ( _UpperCAmelCase : Tuple , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Tuple=None ) -> Optional[Any]:
# set parameter of one layer
assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match'''
__snake_case = nn.Parameter(_UpperCAmelCase )
if bias is not None:
assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match'''
__snake_case = nn.Parameter(_UpperCAmelCase )
def __UpperCAmelCase ( _UpperCAmelCase : Tuple , _UpperCAmelCase : List[Any] , _UpperCAmelCase : Optional[int] ) -> Optional[int]:
# set torch weights for 1-to-1 comparison
__snake_case = np.asarray(weights[0] )
__snake_case = np.asarray(weights[1] )
__snake_case = np.asarray(weights[2] )
set_param(
torch_layer.self_attention.query_key , torch.tensor(_UpperCAmelCase ).transpose(1 , 2 ).contiguous().view(-1 , _UpperCAmelCase ) , )
set_param(
torch_layer.self_attention.value , torch.tensor(_UpperCAmelCase ).transpose(1 , 2 ).contiguous().view(-1 , _UpperCAmelCase ) , )
set_param(
torch_layer.output.dense , torch.tensor(_UpperCAmelCase ).view(-1 , _UpperCAmelCase ).contiguous().transpose(0 , 1 ) , )
def __UpperCAmelCase ( _UpperCAmelCase : str , _UpperCAmelCase : List[str] , _UpperCAmelCase : List[Any] ) -> Optional[int]:
# set torch weights for 1-to-1 comparison
__snake_case = np.asarray(weights[0] )
__snake_case = np.asarray(weights[1] )
__snake_case = np.asarray(weights[2] )
__snake_case = np.asarray(weights[3] )
set_param(
torch_layer.self_attention.query , torch.tensor(_UpperCAmelCase ).transpose(1 , 2 ).contiguous().view(-1 , _UpperCAmelCase ) , )
set_param(
torch_layer.self_attention.key , torch.tensor(_UpperCAmelCase ).transpose(1 , 2 ).contiguous().view(-1 , _UpperCAmelCase ) , )
set_param(
torch_layer.self_attention.value , torch.tensor(_UpperCAmelCase ).transpose(1 , 2 ).contiguous().view(-1 , _UpperCAmelCase ) , )
set_param(
torch_layer.output.dense , torch.tensor(_UpperCAmelCase ).view(-1 , _UpperCAmelCase ).contiguous().transpose(0 , 1 ) , )
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : List[Any] , _UpperCAmelCase : Any ) -> Optional[Any]:
# layernorm 1
__snake_case = weights[0][0][0]
__snake_case = np.asarray(layer_norm_a[0] )
__snake_case = np.asarray(layer_norm_a[1] )
set_param(
torch_block.attention.layer_norm , torch.tensor(_UpperCAmelCase ) , torch.tensor(_UpperCAmelCase ) , )
# lsh weights + output
__snake_case = weights[0][1]
if len(_UpperCAmelCase ) < 4:
set_layer_weights_in_torch_lsh(_UpperCAmelCase , torch_block.attention , _UpperCAmelCase )
else:
set_layer_weights_in_torch_local(_UpperCAmelCase , torch_block.attention , _UpperCAmelCase )
# intermediate weighs
__snake_case = weights[2][0][1][2]
# Chunked Feed Forward
if len(_UpperCAmelCase ) == 4:
__snake_case = intermediate_weights[2]
# layernorm 2
__snake_case = np.asarray(intermediate_weights[0][0] )
__snake_case = np.asarray(intermediate_weights[0][1] )
set_param(
torch_block.feed_forward.layer_norm , torch.tensor(_UpperCAmelCase ) , torch.tensor(_UpperCAmelCase ) , )
# intermediate dense
__snake_case = np.asarray(intermediate_weights[1][0] )
__snake_case = np.asarray(intermediate_weights[1][1] )
set_param(
torch_block.feed_forward.dense.dense , torch.tensor(_UpperCAmelCase ).transpose(0 , 1 ).contiguous() , torch.tensor(_UpperCAmelCase ) , )
# intermediate out
__snake_case = np.asarray(intermediate_weights[4][0] )
__snake_case = np.asarray(intermediate_weights[4][1] )
set_param(
torch_block.feed_forward.output.dense , torch.tensor(_UpperCAmelCase ).transpose(0 , 1 ).contiguous() , torch.tensor(_UpperCAmelCase ) , )
def __UpperCAmelCase ( _UpperCAmelCase : Optional[int] , _UpperCAmelCase : Dict , _UpperCAmelCase : Union[str, Any] ) -> Optional[int]:
# reformer model
__snake_case = torch_model.reformer
# word embeds
__snake_case = np.asarray(weights[1] )
set_param(
torch_model_reformer.embeddings.word_embeddings , torch.tensor(_UpperCAmelCase ) , )
if isinstance(weights[3] , _UpperCAmelCase ):
__snake_case = torch_model_reformer.embeddings.position_embeddings
for emb_idx in range(len(position_embeddings.weights ) ):
__snake_case = 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'''
__snake_case = nn.Parameter(torch.tensor(_UpperCAmelCase ) )
__snake_case = weights[5]
assert len(torch_model_reformer.encoder.layers ) * 4 == len(
_UpperCAmelCase ), "HF and trax model do not have the same number of layers"
for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ):
__snake_case = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)]
set_block_weights_in_torch(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
# output layer norm
__snake_case = np.asarray(weights[7][0] )
__snake_case = np.asarray(weights[7][1] )
set_param(
torch_model_reformer.encoder.layer_norm , torch.tensor(_UpperCAmelCase ) , torch.tensor(_UpperCAmelCase ) , )
# output embeddings
__snake_case = np.asarray(weights[9][0] )
__snake_case = np.asarray(weights[9][1] )
set_param(
torch_model.lm_head.decoder , torch.tensor(_UpperCAmelCase ).transpose(0 , 1 ).contiguous() , torch.tensor(_UpperCAmelCase ) , )
def __UpperCAmelCase ( _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : int , _UpperCAmelCase : Union[str, Any] ) -> str:
# Initialise PyTorch model
__snake_case = ReformerConfig.from_json_file(_UpperCAmelCase )
print(F'''Building PyTorch model from configuration: {config}''' )
__snake_case = ReformerModelWithLMHead(_UpperCAmelCase )
with open(_UpperCAmelCase , "rb" ) as f:
__snake_case = pickle.load(_UpperCAmelCase )["weights"]
set_model_weights_in_torch(_UpperCAmelCase , _UpperCAmelCase , config.hidden_size )
# Save pytorch-model
print(F'''Save PyTorch model to {pytorch_dump_path}''' )
torch.save(model.state_dict() , _UpperCAmelCase )
if __name__ == "__main__":
a : Optional[Any] = 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.'''
)
a : Union[str, Any] = parser.parse_args()
convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
| 69 |
'''simple docstring'''
import argparse
from pathlib import Path
import torch
from transformers import OPTConfig, OPTModel
from transformers.utils import logging
logging.set_verbosity_info()
a : List[str] = logging.get_logger(__name__)
def __UpperCAmelCase ( _UpperCAmelCase : Dict ) -> Union[str, Any]:
__snake_case = torch.load(_UpperCAmelCase , map_location="cpu" )
if "model" in sd.keys():
__snake_case = torch.load(_UpperCAmelCase , map_location="cpu" )["model"]
# pop unnecessary weights
__snake_case = [
"decoder.version",
"decoder.output_projection.weight",
]
for key in keys_to_delete:
if key in sd:
sd.pop(_UpperCAmelCase )
__snake_case = {
"decoder.project_in_dim.weight": "decoder.project_in.weight",
"decoder.project_out_dim.weight": "decoder.project_out.weight",
"decoder.layer_norm.weight": "decoder.final_layer_norm.weight",
"decoder.layer_norm.bias": "decoder.final_layer_norm.bias",
}
for old_key, new_key in keys_to_rename.items():
if old_key in sd:
__snake_case = sd.pop(_UpperCAmelCase )
__snake_case = list(sd.keys() )
for key in keys:
if ".qkv_proj." in key:
__snake_case = sd[key]
# We split QKV in separate Q,K,V
__snake_case = key.replace(".qkv_proj." , ".q_proj." )
__snake_case = key.replace(".qkv_proj." , ".k_proj." )
__snake_case = key.replace(".qkv_proj." , ".v_proj." )
__snake_case = value.shape[0]
assert depth % 3 == 0
# `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming:
# https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97
__snake_case , __snake_case , __snake_case = torch.split(_UpperCAmelCase , depth // 3 , dim=0 )
__snake_case = q
__snake_case = k
__snake_case = v
del sd[key]
return sd
@torch.no_grad()
def __UpperCAmelCase ( _UpperCAmelCase : List[str] , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : int=None ) -> Any:
__snake_case = load_checkpoint(_UpperCAmelCase )
if config is not None:
__snake_case = OPTConfig.from_pretrained(_UpperCAmelCase )
else:
__snake_case = OPTConfig()
__snake_case = OPTModel(_UpperCAmelCase ).half().eval()
model.load_state_dict(_UpperCAmelCase )
# Check results
Path(_UpperCAmelCase ).mkdir(exist_ok=_UpperCAmelCase )
model.save_pretrained(_UpperCAmelCase )
if __name__ == "__main__":
a : int = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--fairseq_path''',
type=str,
help=(
'''path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:'''
''' https://huggingface.co/models?other=opt_metasq'''
),
)
parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
parser.add_argument('''--hf_config''', default=None, type=str, help='''Define HF config.''')
a : Optional[int] = parser.parse_args()
convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
| 69 | 1 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> str:
return " ".join(
"".join(word[::-1] ) if len(_UpperCAmelCase ) > 4 else word for word in sentence.split() )
if __name__ == "__main__":
import doctest
doctest.testmod()
print(reverse_long_words('''Hey wollef sroirraw'''))
| 69 |
'''simple docstring'''
from typing import List, Optional
from ...configuration_utils import PretrainedConfig
from ...utils import logging
a : List[str] = logging.get_logger(__name__)
a : Tuple = {
'''huggingface/autoformer-tourism-monthly''': '''https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json''',
}
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = """autoformer"""
__SCREAMING_SNAKE_CASE = {
"""hidden_size""": """d_model""",
"""num_attention_heads""": """encoder_attention_heads""",
"""num_hidden_layers""": """encoder_layers""",
}
def __init__( self : List[Any] , a_ : Optional[int] = None , a_ : Optional[int] = None , a_ : str = "student_t" , a_ : str = "nll" , a_ : int = 1 , a_ : List[int] = [1, 2, 3, 4, 5, 6, 7] , a_ : bool = True , a_ : int = 0 , a_ : int = 0 , a_ : int = 0 , a_ : int = 0 , a_ : Optional[List[int]] = None , a_ : Optional[List[int]] = None , a_ : int = 64 , a_ : int = 2 , a_ : int = 2 , a_ : int = 2 , a_ : int = 2 , a_ : int = 32 , a_ : int = 32 , a_ : str = "gelu" , a_ : float = 0.1 , a_ : float = 0.1 , a_ : float = 0.1 , a_ : float = 0.1 , a_ : float = 0.1 , a_ : int = 100 , a_ : float = 0.02 , a_ : bool = True , a_ : Union[str, Any]=True , a_ : int = 10 , a_ : int = 25 , a_ : int = 3 , **a_ : Tuple , ):
"""simple docstring"""
__snake_case = prediction_length
__snake_case = context_length if context_length is not None else prediction_length
__snake_case = distribution_output
__snake_case = loss
__snake_case = input_size
__snake_case = num_time_features
__snake_case = lags_sequence
__snake_case = scaling
__snake_case = num_dynamic_real_features
__snake_case = num_static_real_features
__snake_case = num_static_categorical_features
if cardinality is not None 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`" )
__snake_case = cardinality
else:
__snake_case = [0]
if embedding_dimension is not None 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`" )
__snake_case = embedding_dimension
else:
__snake_case = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality]
__snake_case = num_parallel_samples
# Transformer architecture configuration
__snake_case = input_size * len(self.lags_sequence ) + self._number_of_features
__snake_case = d_model
__snake_case = encoder_attention_heads
__snake_case = decoder_attention_heads
__snake_case = encoder_ffn_dim
__snake_case = decoder_ffn_dim
__snake_case = encoder_layers
__snake_case = decoder_layers
__snake_case = dropout
__snake_case = attention_dropout
__snake_case = activation_dropout
__snake_case = encoder_layerdrop
__snake_case = decoder_layerdrop
__snake_case = activation_function
__snake_case = init_std
__snake_case = use_cache
# Autoformer
__snake_case = label_length
__snake_case = moving_average
__snake_case = autocorrelation_factor
super().__init__(is_encoder_decoder=a_ , **a_ )
@property
def A ( self : Optional[int] ):
"""simple docstring"""
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
)
| 69 | 1 |
'''simple docstring'''
import unittest
import numpy as np
import torch
from torch import nn
from transformers import (
CLIPImageProcessor,
CLIPTextConfig,
CLIPTextModelWithProjection,
CLIPTokenizer,
CLIPVisionConfig,
CLIPVisionModelWithProjection,
)
from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = KandinskyVaaPriorPipeline
__SCREAMING_SNAKE_CASE = ["""prompt"""]
__SCREAMING_SNAKE_CASE = ["""prompt""", """negative_prompt"""]
__SCREAMING_SNAKE_CASE = [
"""num_images_per_prompt""",
"""generator""",
"""num_inference_steps""",
"""latents""",
"""negative_prompt""",
"""guidance_scale""",
"""output_type""",
"""return_dict""",
]
__SCREAMING_SNAKE_CASE = False
@property
def A ( self : List[Any] ):
"""simple docstring"""
return 32
@property
def A ( self : str ):
"""simple docstring"""
return 32
@property
def A ( self : List[Any] ):
"""simple docstring"""
return self.time_input_dim
@property
def A ( self : Any ):
"""simple docstring"""
return self.time_input_dim * 4
@property
def A ( self : int ):
"""simple docstring"""
return 100
@property
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )
return tokenizer
@property
def A ( self : Union[str, Any] ):
"""simple docstring"""
torch.manual_seed(0 )
__snake_case = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , )
return CLIPTextModelWithProjection(a_ )
@property
def A ( self : Any ):
"""simple docstring"""
torch.manual_seed(0 )
__snake_case = {
"num_attention_heads": 2,
"attention_head_dim": 12,
"embedding_dim": self.text_embedder_hidden_size,
"num_layers": 1,
}
__snake_case = PriorTransformer(**a_ )
# clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
__snake_case = nn.Parameter(torch.ones(model.clip_std.shape ) )
return model
@property
def A ( self : Dict ):
"""simple docstring"""
torch.manual_seed(0 )
__snake_case = CLIPVisionConfig(
hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , )
__snake_case = CLIPVisionModelWithProjection(a_ )
return model
@property
def A ( self : int ):
"""simple docstring"""
__snake_case = CLIPImageProcessor(
crop_size=224 , do_center_crop=a_ , do_normalize=a_ , do_resize=a_ , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , )
return image_processor
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = self.dummy_prior
__snake_case = self.dummy_image_encoder
__snake_case = self.dummy_text_encoder
__snake_case = self.dummy_tokenizer
__snake_case = self.dummy_image_processor
__snake_case = UnCLIPScheduler(
variance_type="fixed_small_log" , prediction_type="sample" , num_train_timesteps=1_000 , clip_sample=a_ , clip_sample_range=10.0 , )
__snake_case = {
"prior": prior,
"image_encoder": image_encoder,
"text_encoder": text_encoder,
"tokenizer": tokenizer,
"scheduler": scheduler,
"image_processor": image_processor,
}
return components
def A ( self : Union[str, Any] , a_ : int , a_ : List[str]=0 ):
"""simple docstring"""
if str(a_ ).startswith("mps" ):
__snake_case = torch.manual_seed(a_ )
else:
__snake_case = torch.Generator(device=a_ ).manual_seed(a_ )
__snake_case = {
"prompt": "horse",
"generator": generator,
"guidance_scale": 4.0,
"num_inference_steps": 2,
"output_type": "np",
}
return inputs
def A ( self : List[str] ):
"""simple docstring"""
__snake_case = "cpu"
__snake_case = self.get_dummy_components()
__snake_case = self.pipeline_class(**a_ )
__snake_case = pipe.to(a_ )
pipe.set_progress_bar_config(disable=a_ )
__snake_case = pipe(**self.get_dummy_inputs(a_ ) )
__snake_case = output.image_embeds
__snake_case = pipe(
**self.get_dummy_inputs(a_ ) , return_dict=a_ , )[0]
__snake_case = image[0, -10:]
__snake_case = image_from_tuple[0, -10:]
assert image.shape == (1, 32)
__snake_case = np.array(
[-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
@skip_mps
def A ( self : Dict ):
"""simple docstring"""
__snake_case = torch_device == "cpu"
__snake_case = True
__snake_case = False
self._test_inference_batch_single_identical(
test_max_difference=a_ , relax_max_difference=a_ , test_mean_pixel_difference=a_ , )
@skip_mps
def A ( self : Any ):
"""simple docstring"""
__snake_case = torch_device == "cpu"
__snake_case = False
self._test_attention_slicing_forward_pass(
test_max_difference=a_ , test_mean_pixel_difference=a_ , )
| 69 |
'''simple docstring'''
import unittest
from transformers import GPTSwaTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
a : List[Any] = get_tests_dir('''fixtures/test_sentencepiece_with_bytefallback.model''')
@require_sentencepiece
@require_tokenizers
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = GPTSwaTokenizer
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = True
__SCREAMING_SNAKE_CASE = False
def A ( self : int ):
"""simple docstring"""
super().setUp()
# We have a SentencePiece fixture for testing
__snake_case = GPTSwaTokenizer(a_ , eos_token="<unk>" , bos_token="<unk>" , pad_token="<unk>" )
tokenizer.save_pretrained(self.tmpdirname )
def A ( self : str , a_ : List[Any] ):
"""simple docstring"""
__snake_case = "This is a test"
__snake_case = "This is a test"
return input_text, output_text
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = "<s>"
__snake_case = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , "<unk>" )
self.assertEqual(vocab_keys[1] , "<s>" )
self.assertEqual(vocab_keys[-1] , "j" )
self.assertEqual(len(a_ ) , 2_000 )
def A ( self : Optional[int] ):
"""simple docstring"""
self.assertEqual(self.get_tokenizer().vocab_size , 2_000 )
def A ( self : Dict ):
"""simple docstring"""
__snake_case = GPTSwaTokenizer(a_ )
__snake_case = tokenizer.tokenize("This is a test" )
self.assertListEqual(a_ , ["▁This", "▁is", "▁a", "▁t", "est"] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , [465, 287, 265, 631, 842] )
__snake_case = tokenizer.tokenize("I was born in 92000, and this is falsé." )
# fmt: off
self.assertListEqual(
a_ , ["▁I", "▁was", "▁bor", "n", "▁in", "▁", "<0x39>", "2", "0", "0", "0", ",", "▁and", "▁this", "▁is", "▁f", "al", "s", "<0xC3>", "<0xA9>", "."] , )
# fmt: on
__snake_case = tokenizer.convert_tokens_to_ids(a_ )
self.assertListEqual(
a_ , [262, 272, 1_525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260] , )
__snake_case = tokenizer.convert_ids_to_tokens(a_ )
# fmt: off
self.assertListEqual(
a_ , ["▁I", "▁was", "▁bor", "n", "▁in", "▁", "<0x39>", "2", "0", "0", "0", ",", "▁and", "▁this", "▁is", "▁f", "al", "s", "<0xC3>", "<0xA9>", "."] )
# fmt: on
def A ( self : List[str] ):
"""simple docstring"""
__snake_case = GPTSwaTokenizer(a_ )
__snake_case = ["This is a test", "I was born in 92000, and this is falsé."]
__snake_case = [
[465, 287, 265, 631, 842],
[262, 272, 1_525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260],
]
# Test that encode_fast returns the same as tokenize + convert_tokens_to_ids
for text, expected_ids in zip(a_ , a_ ):
self.assertListEqual(tokenizer.encode_fast(a_ ) , a_ )
# Test that decode_fast returns the input text
for text, token_ids in zip(a_ , a_ ):
self.assertEqual(tokenizer.decode_fast(a_ ) , a_ )
@slow
def A ( self : Any ):
"""simple docstring"""
__snake_case = [
"<|python|>def fibonacci(n)\n if n < 0:\n print('Incorrect input')",
"Hey there, how are you doing this fine day?",
"This is a text with a trailing spaces followed by a dot .",
"Häj sväjs lillebrör! =)",
"Det är inget fel på Mr. Cool",
]
# fmt: off
__snake_case = {"input_ids": [[63_423, 5, 6_811, 14_954, 282, 816, 3_821, 63_466, 63_425, 63_462, 18, 63_978, 678, 301, 1_320, 63_423, 63_455, 63_458, 18, 63_982, 4_246, 3_940, 1_901, 47_789, 5_547, 18_994], [19_630, 1_100, 63_446, 1_342, 633, 544, 4_488, 593, 5_102, 2_416, 63_495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_652, 428, 268, 1_936, 515, 268, 58_593, 22_413, 9_106, 546, 268, 33_213, 63_979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [55_130, 63_450, 924, 63_449, 2_249, 4_062, 1_558, 318, 63_504, 21_498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2_827, 2_559, 332, 6_575, 63_443, 26_801, 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]], "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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [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], [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]]}
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=a_ , model_name="AI-Sweden/gpt-sw3-126m" , sequences=a_ , )
| 69 | 1 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_sentencepiece_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
a : Tuple = {'''configuration_mbart''': ['''MBART_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MBartConfig''', '''MBartOnnxConfig''']}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : Tuple = ['''MBartTokenizer''']
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : Any = ['''MBartTokenizerFast''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : Any = [
'''MBART_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''MBartForCausalLM''',
'''MBartForConditionalGeneration''',
'''MBartForQuestionAnswering''',
'''MBartForSequenceClassification''',
'''MBartModel''',
'''MBartPreTrainedModel''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : str = [
'''TFMBartForConditionalGeneration''',
'''TFMBartModel''',
'''TFMBartPreTrainedModel''',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : int = [
'''FlaxMBartForConditionalGeneration''',
'''FlaxMBartForQuestionAnswering''',
'''FlaxMBartForSequenceClassification''',
'''FlaxMBartModel''',
'''FlaxMBartPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_mbart import MBartTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_mbart_fast import MBartTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mbart import (
MBART_PRETRAINED_MODEL_ARCHIVE_LIST,
MBartForCausalLM,
MBartForConditionalGeneration,
MBartForQuestionAnswering,
MBartForSequenceClassification,
MBartModel,
MBartPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_mbart import (
FlaxMBartForConditionalGeneration,
FlaxMBartForQuestionAnswering,
FlaxMBartForSequenceClassification,
FlaxMBartModel,
FlaxMBartPreTrainedModel,
)
else:
import sys
a : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 69 |
'''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
a : Tuple = get_tests_dir('''fixtures''')
a : Dict = get_tests_dir('''fixtures/dummy_feature_extractor_config.json''')
a : int = get_tests_dir('''fixtures/dummy-config.json''')
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = 0
def A ( self : str ):
"""simple docstring"""
__snake_case = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h" )
self.assertIsInstance(a_ , a_ )
def A ( self : str ):
"""simple docstring"""
__snake_case = AutoFeatureExtractor.from_pretrained(a_ )
self.assertIsInstance(a_ , a_ )
def A ( self : str ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmpdirname:
__snake_case = WavaVecaConfig()
# remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
__snake_case = AutoFeatureExtractor.from_pretrained(a_ ).to_dict()
config_dict.pop("feature_extractor_type" )
__snake_case = WavaVecaFeatureExtractor(**a_ )
# save in new folder
model_config.save_pretrained(a_ )
config.save_pretrained(a_ )
__snake_case = AutoFeatureExtractor.from_pretrained(a_ )
# make sure private variable is not incorrectly saved
__snake_case = json.loads(config.to_json_string() )
self.assertTrue("_processor_class" not in dict_as_saved )
self.assertIsInstance(a_ , a_ )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = AutoFeatureExtractor.from_pretrained(a_ )
self.assertIsInstance(a_ , a_ )
def A ( self : Optional[Any] ):
"""simple docstring"""
with self.assertRaisesRegex(
a_ , "bert-base is not a local folder and is not a valid model identifier" ):
__snake_case = AutoFeatureExtractor.from_pretrained("bert-base" )
def A ( self : Dict ):
"""simple docstring"""
with self.assertRaisesRegex(
a_ , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ):
__snake_case = AutoFeatureExtractor.from_pretrained(a_ , revision="aaaaaa" )
def A ( self : Tuple ):
"""simple docstring"""
with self.assertRaisesRegex(
a_ , "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json." , ):
__snake_case = AutoFeatureExtractor.from_pretrained("hf-internal-testing/config-no-model" )
def A ( self : Tuple ):
"""simple docstring"""
with self.assertRaises(a_ ):
__snake_case = 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_ ):
__snake_case = AutoFeatureExtractor.from_pretrained(
"hf-internal-testing/test_dynamic_feature_extractor" , trust_remote_code=a_ )
__snake_case = 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_ )
__snake_case = AutoFeatureExtractor.from_pretrained(a_ , trust_remote_code=a_ )
self.assertEqual(reloaded_feature_extractor.__class__.__name__ , "NewFeatureExtractor" )
def A ( self : int ):
"""simple docstring"""
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
__snake_case = CustomFeatureExtractor.from_pretrained(a_ )
with tempfile.TemporaryDirectory() as tmp_dir:
feature_extractor.save_pretrained(a_ )
__snake_case = 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 A ( self : Dict ):
"""simple docstring"""
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = True
try:
AutoConfig.register("custom" , a_ )
AutoFeatureExtractor.register(a_ , a_ )
# If remote code is not set, the default is to use local
__snake_case = 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.
__snake_case = 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
__snake_case = 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]
| 69 | 1 |
'''simple docstring'''
from __future__ import annotations
a : Optional[Any] = '''Muhammad Umer Farooq'''
a : int = '''MIT'''
a : Dict = '''1.0.0'''
a : Optional[int] = '''Muhammad Umer Farooq'''
a : Optional[Any] = '''contact@muhammadumerfarooq.me'''
a : Union[str, Any] = '''Alpha'''
import re
from html.parser import HTMLParser
from urllib import parse
import requests
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def __init__( self : Optional[Any] , a_ : str ):
"""simple docstring"""
super().__init__()
__snake_case = []
__snake_case = domain
def A ( self : str , a_ : str , a_ : list[tuple[str, str | None]] ):
"""simple docstring"""
if tag == "a":
# Check the list of defined attributes.
for name, value in attrs:
# If href is defined, and not empty nor # print it.
if name == "href" and value != "#" and value != "":
# If not already in urls.
if value not in self.urls:
__snake_case = parse.urljoin(self.domain , a_ )
self.urls.append(a_ )
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> str:
return ".".join(get_sub_domain_name(_UpperCAmelCase ).split("." )[-2:] )
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> str:
return parse.urlparse(_UpperCAmelCase ).netloc
def __UpperCAmelCase ( _UpperCAmelCase : str = "https://github.com" ) -> list[str]:
__snake_case = get_domain_name(_UpperCAmelCase )
# Initialize the parser
__snake_case = Parser(_UpperCAmelCase )
try:
# Open URL
__snake_case = requests.get(_UpperCAmelCase )
# pass the raw HTML to the parser to get links
parser.feed(r.text )
# Get links and loop through
__snake_case = set()
for link in parser.urls:
# open URL.
# read = requests.get(link)
try:
__snake_case = requests.get(_UpperCAmelCase )
# Get the valid email.
__snake_case = re.findall("[a-zA-Z0-9]+@" + domain , read.text )
# If not in list then append it.
for email in emails:
valid_emails.add(_UpperCAmelCase )
except ValueError:
pass
except ValueError:
raise SystemExit(1 )
# Finally return a sorted list of email addresses with no duplicates.
return sorted(_UpperCAmelCase )
if __name__ == "__main__":
a : Any = emails_from_url('''https://github.com''')
print(F'''{len(emails)} emails found:''')
print('''\n'''.join(sorted(emails)))
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> list:
# bit count represents no. of bits in the gray code
if bit_count < 0:
raise ValueError("The given input must be positive" )
# get the generated string sequence
__snake_case = gray_code_sequence_string(_UpperCAmelCase )
#
# convert them to integers
for i in range(len(_UpperCAmelCase ) ):
__snake_case = int(sequence[i] , 2 )
return sequence
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> list:
# The approach is a recursive one
# Base case achieved when either n = 0 or n=1
if bit_count == 0:
return ["0"]
if bit_count == 1:
return ["0", "1"]
__snake_case = 1 << bit_count # defines the length of the sequence
# 1<< n is equivalent to 2^n
# recursive answer will generate answer for n-1 bits
__snake_case = gray_code_sequence_string(bit_count - 1 )
__snake_case = []
# append 0 to first half of the smaller sequence generated
for i in range(seq_len // 2 ):
__snake_case = "0" + smaller_sequence[i]
sequence.append(_UpperCAmelCase )
# append 1 to second half ... start from the end of the list
for i in reversed(range(seq_len // 2 ) ):
__snake_case = "1" + smaller_sequence[i]
sequence.append(_UpperCAmelCase )
return sequence
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 | 1 |
'''simple docstring'''
# Lint as: python3
import dataclasses
import re
from dataclasses import dataclass
from functools import total_ordering
from typing import Optional, Union
a : Tuple = re.compile(r'''^(?P<major>\d+)''' r'''\.(?P<minor>\d+)''' r'''\.(?P<patch>\d+)$''')
@total_ordering
@dataclass
class SCREAMING_SNAKE_CASE__ :
__SCREAMING_SNAKE_CASE = 42
__SCREAMING_SNAKE_CASE = None
__SCREAMING_SNAKE_CASE = None
__SCREAMING_SNAKE_CASE = None
__SCREAMING_SNAKE_CASE = None
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case , __snake_case , __snake_case = _str_to_version_tuple(self.version_str )
def __repr__( self : Tuple ):
"""simple docstring"""
return f'''{self.tuple[0]}.{self.tuple[1]}.{self.tuple[2]}'''
@property
def A ( self : List[Any] ):
"""simple docstring"""
return self.major, self.minor, self.patch
def A ( self : Tuple , a_ : str ):
"""simple docstring"""
if isinstance(a_ , a_ ):
return Version(a_ )
elif isinstance(a_ , a_ ):
return other
raise TypeError(f'''{other} (type {type(a_ )}) cannot be compared to version.''' )
def __eq__( self : str , a_ : Tuple ):
"""simple docstring"""
try:
__snake_case = self._validate_operand(a_ )
except (TypeError, ValueError):
return False
else:
return self.tuple == other.tuple
def __lt__( self : Optional[Any] , a_ : Union[str, Any] ):
"""simple docstring"""
__snake_case = self._validate_operand(a_ )
return self.tuple < other.tuple
def __hash__( self : Union[str, Any] ):
"""simple docstring"""
return hash(_version_tuple_to_str(self.tuple ) )
@classmethod
def A ( cls : Optional[int] , a_ : Optional[Any] ):
"""simple docstring"""
__snake_case = {f.name for f in dataclasses.fields(cls )}
return cls(**{k: v for k, v in dic.items() if k in field_names} )
def A ( self : List[Any] ):
"""simple docstring"""
return self.version_str
def __UpperCAmelCase ( _UpperCAmelCase : List[Any] ) -> List[Any]:
__snake_case = _VERSION_REG.match(_UpperCAmelCase )
if not res:
raise ValueError(F'''Invalid version \'{version_str}\'. Format should be x.y.z with {{x,y,z}} being digits.''' )
return tuple(int(_UpperCAmelCase ) for v in [res.group("major" ), res.group("minor" ), res.group("patch" )] )
def __UpperCAmelCase ( _UpperCAmelCase : List[str] ) -> List[Any]:
return ".".join(str(_UpperCAmelCase ) for v in version_tuple )
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : str , _UpperCAmelCase : str ) -> list:
__snake_case = len(_UpperCAmelCase )
__snake_case = []
for i in range(len(_UpperCAmelCase ) - pat_len + 1 ):
__snake_case = True
for j in range(_UpperCAmelCase ):
if s[i + j] != pattern[j]:
__snake_case = 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'''))
| 69 | 1 |
'''simple docstring'''
from operator import delitem, getitem, setitem
import pytest
from data_structures.hashing.hash_map import HashMap
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] ) -> Optional[Any]:
return getitem, k
def __UpperCAmelCase ( _UpperCAmelCase : Dict , _UpperCAmelCase : List[str] ) -> str:
return setitem, k, v
def __UpperCAmelCase ( _UpperCAmelCase : Dict ) -> Union[str, Any]:
return delitem, k
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : int , *_UpperCAmelCase : Union[str, Any] ) -> Optional[int]:
try:
return fun(_UpperCAmelCase , *_UpperCAmelCase ), None
except Exception as e:
return None, e
a : Optional[int] = (
_set('''key_a''', '''val_a'''),
_set('''key_b''', '''val_b'''),
)
a : Any = [
_set('''key_a''', '''val_a'''),
_set('''key_a''', '''val_b'''),
]
a : List[str] = [
_set('''key_a''', '''val_a'''),
_set('''key_b''', '''val_b'''),
_del('''key_a'''),
_del('''key_b'''),
_set('''key_a''', '''val_a'''),
_del('''key_a'''),
]
a : Dict = [
_get('''key_a'''),
_del('''key_a'''),
_set('''key_a''', '''val_a'''),
_del('''key_a'''),
_del('''key_a'''),
_get('''key_a'''),
]
a : List[Any] = [
*[_set(x, x) for x in range(5)], # guaranteed upsize
]
a : Dict = [
*[_set(x, x) for x in range(5)], # guaranteed upsize
*[_del(x) for x in range(5)],
_set('''key_a''', '''val_b'''),
]
@pytest.mark.parametrize(
"operations" , (
pytest.param(_add_items , id="add items" ),
pytest.param(_overwrite_items , id="overwrite items" ),
pytest.param(_delete_items , id="delete items" ),
pytest.param(_access_absent_items , id="access absent items" ),
pytest.param(_add_with_resize_up , id="add with resize up" ),
pytest.param(_add_with_resize_down , id="add with resize down" ),
) , )
def __UpperCAmelCase ( _UpperCAmelCase : Tuple ) -> int:
__snake_case = HashMap(initial_block_size=4 )
__snake_case = {}
for _, (fun, *args) in enumerate(_UpperCAmelCase ):
__snake_case , __snake_case = _run_operation(_UpperCAmelCase , _UpperCAmelCase , *_UpperCAmelCase )
__snake_case , __snake_case = _run_operation(_UpperCAmelCase , _UpperCAmelCase , *_UpperCAmelCase )
assert my_res == py_res
assert str(_UpperCAmelCase ) == str(_UpperCAmelCase )
assert set(_UpperCAmelCase ) == set(_UpperCAmelCase )
assert len(_UpperCAmelCase ) == len(_UpperCAmelCase )
assert set(my.items() ) == set(py.items() )
def __UpperCAmelCase ( ) -> Tuple:
def is_public(_UpperCAmelCase : str ) -> bool:
return not name.startswith("_" )
__snake_case = {name for name in dir({} ) if is_public(_UpperCAmelCase )}
__snake_case = {name for name in dir(HashMap() ) if is_public(_UpperCAmelCase )}
assert dict_public_names > hash_public_names
| 69 |
'''simple docstring'''
a : Dict = range(2, 20 + 1)
a : Optional[int] = [10**k for k in range(ks[-1] + 1)]
a : dict[int, dict[int, list[list[int]]]] = {}
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Dict , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[Any] ) -> int:
__snake_case = sum(a_i[j] for j in range(_UpperCAmelCase , len(_UpperCAmelCase ) ) )
__snake_case = sum(a_i[j] * base[j] for j in range(min(len(_UpperCAmelCase ) , _UpperCAmelCase ) ) )
__snake_case , __snake_case = 0, 0
__snake_case = n - i
__snake_case = memo.get(_UpperCAmelCase )
if sub_memo is not None:
__snake_case = sub_memo.get(_UpperCAmelCase )
if jumps is not None and len(_UpperCAmelCase ) > 0:
# find and make the largest jump without going over
__snake_case = -1
for _k in range(len(_UpperCAmelCase ) - 1 , -1 , -1 ):
if jumps[_k][2] <= k and jumps[_k][1] <= max_dn:
__snake_case = _k
break
if max_jump >= 0:
__snake_case , __snake_case , __snake_case = jumps[max_jump]
# since the difference between jumps is cached, add c
__snake_case = diff + c
for j in range(min(_UpperCAmelCase , len(_UpperCAmelCase ) ) ):
__snake_case , __snake_case = divmod(_UpperCAmelCase , 10 )
if new_c > 0:
add(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
else:
__snake_case = []
else:
__snake_case = {c: []}
__snake_case = sub_memo
if dn >= max_dn or c + diff >= base[k]:
return diff, dn
if k > ks[0]:
while True:
# keep doing smaller jumps
__snake_case , __snake_case = next_term(_UpperCAmelCase , k - 1 , i + dn , _UpperCAmelCase )
diff += _diff
dn += terms_jumped
if dn >= max_dn or c + diff >= base[k]:
break
else:
# would be too small a jump, just compute sequential terms instead
__snake_case , __snake_case = compute(_UpperCAmelCase , _UpperCAmelCase , i + dn , _UpperCAmelCase )
diff += _diff
dn += terms_jumped
__snake_case = sub_memo[c]
# keep jumps sorted by # of terms skipped
__snake_case = 0
while j < len(_UpperCAmelCase ):
if jumps[j][1] > dn:
break
j += 1
# cache the jump for this value digitsum(b) and c
sub_memo[c].insert(_UpperCAmelCase , (diff, dn, k) )
return (diff, dn)
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[int] ) -> Optional[int]:
if i >= n:
return 0, i
if k > len(_UpperCAmelCase ):
a_i.extend([0 for _ in range(k - len(_UpperCAmelCase ) )] )
# note: a_i -> b * 10^k + c
# ds_b -> digitsum(b)
# ds_c -> digitsum(c)
__snake_case = i
__snake_case , __snake_case , __snake_case = 0, 0, 0
for j in range(len(_UpperCAmelCase ) ):
if j >= k:
ds_b += a_i[j]
else:
ds_c += a_i[j]
while i < n:
i += 1
__snake_case = ds_c + ds_b
diff += addend
__snake_case = 0
for j in range(_UpperCAmelCase ):
__snake_case = a_i[j] + addend
__snake_case , __snake_case = divmod(_UpperCAmelCase , 10 )
ds_c += a_i[j]
if addend > 0:
break
if addend > 0:
add(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
return diff, i - start_i
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Tuple , _UpperCAmelCase : str ) -> Tuple:
for j in range(_UpperCAmelCase , len(_UpperCAmelCase ) ):
__snake_case = digits[j] + addend
if s >= 10:
__snake_case , __snake_case = divmod(_UpperCAmelCase , 10 )
__snake_case = addend // 10 + quotient
else:
__snake_case = s
__snake_case = addend // 10
if addend == 0:
break
while addend > 0:
__snake_case , __snake_case = divmod(_UpperCAmelCase , 10 )
digits.append(_UpperCAmelCase )
def __UpperCAmelCase ( _UpperCAmelCase : int = 10**15 ) -> int:
__snake_case = [1]
__snake_case = 1
__snake_case = 0
while True:
__snake_case , __snake_case = next_term(_UpperCAmelCase , 20 , i + dn , _UpperCAmelCase )
dn += terms_jumped
if dn == n - i:
break
__snake_case = 0
for j in range(len(_UpperCAmelCase ) ):
a_n += digits[j] * 10**j
return a_n
if __name__ == "__main__":
print(F'''{solution() = }''')
| 69 | 1 |
'''simple docstring'''
import inspect
import re
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_config_docstrings.py
a : List[Any] = '''src/transformers'''
# This is to make sure the transformers module imported is the one in the repo.
a : str = direct_transformers_import(PATH_TO_TRANSFORMERS)
a : Any = transformers.models.auto.configuration_auto.CONFIG_MAPPING
# Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`.
# For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)`
a : List[str] = re.compile(r'''\[(.+?)\]\((https://huggingface\.co/.+?)\)''')
a : List[Any] = {
'''DecisionTransformerConfig''',
'''EncoderDecoderConfig''',
'''MusicgenConfig''',
'''RagConfig''',
'''SpeechEncoderDecoderConfig''',
'''TimmBackboneConfig''',
'''VisionEncoderDecoderConfig''',
'''VisionTextDualEncoderConfig''',
'''LlamaConfig''',
}
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] ) -> Dict:
__snake_case = None
# source code of `config_class`
__snake_case = inspect.getsource(_UpperCAmelCase )
__snake_case = _re_checkpoint.findall(_UpperCAmelCase )
# Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link.
# For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')`
for ckpt_name, ckpt_link in checkpoints:
# allow the link to end with `/`
if ckpt_link.endswith("/" ):
__snake_case = ckpt_link[:-1]
# verify the checkpoint name corresponds to the checkpoint link
__snake_case = F'''https://huggingface.co/{ckpt_name}'''
if ckpt_link == ckpt_link_from_name:
__snake_case = ckpt_name
break
return checkpoint
def __UpperCAmelCase ( ) -> Optional[int]:
__snake_case = []
for config_class in list(CONFIG_MAPPING.values() ):
# Skip deprecated models
if "models.deprecated" in config_class.__module__:
continue
__snake_case = get_checkpoint_from_config_class(_UpperCAmelCase )
__snake_case = config_class.__name__
if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK:
configs_without_checkpoint.append(_UpperCAmelCase )
if len(_UpperCAmelCase ) > 0:
__snake_case = "\n".join(sorted(_UpperCAmelCase ) )
raise ValueError(F'''The following configurations don\'t contain any valid checkpoint:\n{message}''' )
if __name__ == "__main__":
check_config_docstrings_have_checkpoints()
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : List[Any]=2_81_23 ) -> str:
__snake_case = [1] * (limit + 1)
for i in range(2 , int(limit**0.5 ) + 1 ):
sum_divs[i * i] += i
for k in range(i + 1 , limit // i + 1 ):
sum_divs[k * i] += k + i
__snake_case = set()
__snake_case = 0
for n in range(1 , limit + 1 ):
if sum_divs[n] > n:
abundants.add(_UpperCAmelCase )
if not any((n - a in abundants) for a in abundants ):
res += n
return res
if __name__ == "__main__":
print(solution())
| 69 | 1 |
'''simple docstring'''
from typing import List, Optional
from ...configuration_utils import PretrainedConfig
from ...utils import logging
a : List[str] = logging.get_logger(__name__)
a : Tuple = {
'''huggingface/autoformer-tourism-monthly''': '''https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json''',
}
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = """autoformer"""
__SCREAMING_SNAKE_CASE = {
"""hidden_size""": """d_model""",
"""num_attention_heads""": """encoder_attention_heads""",
"""num_hidden_layers""": """encoder_layers""",
}
def __init__( self : List[Any] , a_ : Optional[int] = None , a_ : Optional[int] = None , a_ : str = "student_t" , a_ : str = "nll" , a_ : int = 1 , a_ : List[int] = [1, 2, 3, 4, 5, 6, 7] , a_ : bool = True , a_ : int = 0 , a_ : int = 0 , a_ : int = 0 , a_ : int = 0 , a_ : Optional[List[int]] = None , a_ : Optional[List[int]] = None , a_ : int = 64 , a_ : int = 2 , a_ : int = 2 , a_ : int = 2 , a_ : int = 2 , a_ : int = 32 , a_ : int = 32 , a_ : str = "gelu" , a_ : float = 0.1 , a_ : float = 0.1 , a_ : float = 0.1 , a_ : float = 0.1 , a_ : float = 0.1 , a_ : int = 100 , a_ : float = 0.02 , a_ : bool = True , a_ : Union[str, Any]=True , a_ : int = 10 , a_ : int = 25 , a_ : int = 3 , **a_ : Tuple , ):
"""simple docstring"""
__snake_case = prediction_length
__snake_case = context_length if context_length is not None else prediction_length
__snake_case = distribution_output
__snake_case = loss
__snake_case = input_size
__snake_case = num_time_features
__snake_case = lags_sequence
__snake_case = scaling
__snake_case = num_dynamic_real_features
__snake_case = num_static_real_features
__snake_case = num_static_categorical_features
if cardinality is not None 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`" )
__snake_case = cardinality
else:
__snake_case = [0]
if embedding_dimension is not None 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`" )
__snake_case = embedding_dimension
else:
__snake_case = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality]
__snake_case = num_parallel_samples
# Transformer architecture configuration
__snake_case = input_size * len(self.lags_sequence ) + self._number_of_features
__snake_case = d_model
__snake_case = encoder_attention_heads
__snake_case = decoder_attention_heads
__snake_case = encoder_ffn_dim
__snake_case = decoder_ffn_dim
__snake_case = encoder_layers
__snake_case = decoder_layers
__snake_case = dropout
__snake_case = attention_dropout
__snake_case = activation_dropout
__snake_case = encoder_layerdrop
__snake_case = decoder_layerdrop
__snake_case = activation_function
__snake_case = init_std
__snake_case = use_cache
# Autoformer
__snake_case = label_length
__snake_case = moving_average
__snake_case = autocorrelation_factor
super().__init__(is_encoder_decoder=a_ , **a_ )
@property
def A ( self : Optional[int] ):
"""simple docstring"""
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
)
| 69 |
'''simple docstring'''
import unittest
from transformers import AutoTokenizer, FalconConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
FalconForCausalLM,
FalconForQuestionAnswering,
FalconForSequenceClassification,
FalconForTokenClassification,
FalconModel,
)
class SCREAMING_SNAKE_CASE__ :
def __init__( self : str , a_ : List[str] , a_ : Tuple=3 , a_ : Any=7 , a_ : Any=True , a_ : Union[str, Any]=True , a_ : Tuple=False , a_ : Optional[int]=True , a_ : Any=99 , a_ : Dict=32 , a_ : Dict=5 , a_ : List[Any]=4 , a_ : Any=37 , a_ : Any="gelu" , a_ : List[str]=0.1 , a_ : Dict=0.1 , a_ : Optional[Any]=512 , a_ : List[Any]=16 , a_ : Any=2 , a_ : str=0.02 , a_ : Any=3 , a_ : List[Any]=4 , a_ : List[str]=None , ):
"""simple docstring"""
__snake_case = parent
__snake_case = batch_size
__snake_case = seq_length
__snake_case = is_training
__snake_case = use_input_mask
__snake_case = use_token_type_ids
__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_act
__snake_case = hidden_dropout_prob
__snake_case = attention_probs_dropout_prob
__snake_case = max_position_embeddings
__snake_case = type_vocab_size
__snake_case = type_sequence_label_size
__snake_case = initializer_range
__snake_case = num_labels
__snake_case = num_choices
__snake_case = scope
def A ( self : Any ):
"""simple docstring"""
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__snake_case = None
if self.use_input_mask:
__snake_case = random_attention_mask([self.batch_size, self.seq_length] )
__snake_case = None
__snake_case = None
__snake_case = None
__snake_case = None
if self.use_labels:
__snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__snake_case = ids_tensor([self.batch_size] , self.num_choices )
__snake_case = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def A ( self : Optional[int] ):
"""simple docstring"""
return FalconConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a_ , initializer_range=self.initializer_range , pad_token_id=1 , new_decoder_architecture=a_ , )
def A ( self : List[str] , a_ : Dict , a_ : Tuple , a_ : Optional[Any] , a_ : Dict , a_ : Dict , a_ : Dict , a_ : Union[str, Any] ):
"""simple docstring"""
__snake_case = FalconModel(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ )
__snake_case = model(a_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def A ( self : List[Any] , a_ : List[Any] , a_ : Union[str, Any] , a_ : Optional[Any] , a_ : Any , a_ : List[Any] , a_ : Optional[Any] , a_ : Union[str, Any] , a_ : Tuple , a_ : Optional[int] , ):
"""simple docstring"""
__snake_case = True
__snake_case = FalconModel(a_ )
model.to(a_ )
model.eval()
__snake_case = model(
a_ , attention_mask=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , )
__snake_case = model(
a_ , attention_mask=a_ , encoder_hidden_states=a_ , )
__snake_case = model(a_ , attention_mask=a_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def A ( self : Optional[int] , a_ : int , a_ : int , a_ : List[Any] , a_ : str , a_ : List[str] , a_ : str , a_ : str , a_ : Union[str, Any] , a_ : Optional[int] , ):
"""simple docstring"""
__snake_case = FalconForCausalLM(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def A ( self : List[Any] , a_ : Optional[int] , a_ : Optional[Any] , a_ : str , a_ : Tuple , a_ : str , a_ : List[Any] , a_ : Optional[Any] , a_ : Any , a_ : Dict , ):
"""simple docstring"""
__snake_case = True
__snake_case = True
__snake_case = FalconForCausalLM(config=a_ )
model.to(a_ )
model.eval()
# first forward pass
__snake_case = model(
a_ , attention_mask=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , use_cache=a_ , )
__snake_case = outputs.past_key_values
# create hypothetical multiple next token and extent to next_input_ids
__snake_case = ids_tensor((self.batch_size, 3) , config.vocab_size )
__snake_case = ids_tensor((self.batch_size, 3) , vocab_size=2 )
# append to next input_ids and
__snake_case = torch.cat([input_ids, next_tokens] , dim=-1 )
__snake_case = torch.cat([input_mask, next_mask] , dim=-1 )
__snake_case = model(
a_ , attention_mask=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , output_hidden_states=a_ , )["hidden_states"][0]
__snake_case = model(
a_ , attention_mask=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , past_key_values=a_ , output_hidden_states=a_ , )["hidden_states"][0]
# select random slice
__snake_case = ids_tensor((1,) , output_from_past.shape[-1] ).item()
__snake_case = output_from_no_past[:, -3:, random_slice_idx].detach()
__snake_case = output_from_past[:, :, random_slice_idx].detach()
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] )
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = self.prepare_config_and_inputs()
(
(
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) ,
) = config_and_inputs
__snake_case = {"input_ids": input_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = (
(
FalconModel,
FalconForCausalLM,
FalconForSequenceClassification,
FalconForTokenClassification,
FalconForQuestionAnswering,
)
if is_torch_available()
else ()
)
__SCREAMING_SNAKE_CASE = (FalconForCausalLM,) if is_torch_available() else ()
__SCREAMING_SNAKE_CASE = (
{
"""feature-extraction""": FalconModel,
"""text-classification""": FalconForSequenceClassification,
"""text-generation""": FalconForCausalLM,
"""question-answering""": FalconForQuestionAnswering,
"""token-classification""": FalconForTokenClassification,
"""zero-shot""": FalconForSequenceClassification,
}
if is_torch_available()
else {}
)
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = False
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = FalconModelTester(self )
__snake_case = ConfigTester(self , config_class=a_ , hidden_size=37 )
def A ( self : Optional[Any] ):
"""simple docstring"""
self.config_tester.run_common_tests()
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*a_ )
def A ( self : List[str] ):
"""simple docstring"""
__snake_case , *__snake_case = self.model_tester.prepare_config_and_inputs()
for alibi in [True, False]:
__snake_case = alibi
self.model_tester.create_and_check_model(a_ , *a_ )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = 3
__snake_case = input_dict["input_ids"]
__snake_case = input_ids.ne(1 ).to(a_ )
__snake_case = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size )
__snake_case = FalconForSequenceClassification(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) )
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = 3
__snake_case = "single_label_classification"
__snake_case = input_dict["input_ids"]
__snake_case = input_ids.ne(1 ).to(a_ )
__snake_case = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size )
__snake_case = FalconForSequenceClassification(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = input_dict["input_ids"]
__snake_case = FalconForCausalLM(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , use_cache=a_ )
__snake_case = input_ids.shape[0]
__snake_case = model._convert_to_rw_cache(result.past_key_values )
__snake_case = model._convert_cache_to_standard_format(a_ , a_ )
for layer in range(len(a_ ) ):
for tensor_idx in range(2 ):
self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3 )
self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4 )
self.assertTrue(
torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx] ) )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = 3
__snake_case = "multi_label_classification"
__snake_case = input_dict["input_ids"]
__snake_case = input_ids.ne(1 ).to(a_ )
__snake_case = ids_tensor(
[self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float )
__snake_case = FalconForSequenceClassification(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) )
def A ( self : Dict ):
"""simple docstring"""
for model_class in self.all_generative_model_classes:
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
# If it doesn't support cache, pass the test
if not hasattr(a_ , "use_cache" ):
return
__snake_case = model_class(a_ ).to(a_ )
if "use_cache" not in inputs:
__snake_case = True
__snake_case = model(**a_ )
# If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format)
if "past_key_values" not in outputs:
return
__snake_case = (
getattr(a_ , "decoder_layers" , a_ )
or getattr(a_ , "num_decoder_layers" , a_ )
or config.num_hidden_layers
)
__snake_case = getattr(a_ , "num_kv_heads" , config.num_attention_heads )
__snake_case = getattr(a_ , "d_model" , config.hidden_size )
__snake_case = embed_dim // num_attention_heads
__snake_case = outputs["past_key_values"]
self.assertEqual(len(a_ ) , a_ )
__snake_case , __snake_case = inputs["input_ids"].shape
for i in range(a_ ):
if config.new_decoder_architecture:
__snake_case = config.num_attention_heads
elif config.multi_query:
__snake_case = 1
self.assertEqual(len(past_kv[0] ) , 2 ) # K V for the decoder = 2
self.assertEqual(
past_kv[i][0].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) )
self.assertEqual(
past_kv[i][1].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) )
@require_torch
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
@slow
def A ( self : Any ):
"""simple docstring"""
__snake_case = AutoTokenizer.from_pretrained("Rocketknight1/falcon-rw-1b" )
__snake_case = FalconForCausalLM.from_pretrained("Rocketknight1/falcon-rw-1b" )
model.eval()
model.to(a_ )
__snake_case = tokenizer("My favorite food is" , return_tensors="pt" ).to(a_ )
__snake_case = (
"My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday."
)
__snake_case = model.generate(**a_ , do_sample=a_ , max_new_tokens=19 )
__snake_case = tokenizer.batch_decode(a_ )[0]
self.assertEqual(a_ , a_ )
@slow
def A ( self : Optional[int] ):
"""simple docstring"""
for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]:
__snake_case = AutoTokenizer.from_pretrained(a_ )
__snake_case = FalconForCausalLM.from_pretrained(a_ )
model.eval()
model.to(a_ )
__snake_case = tokenizer("My favorite food is" , return_tensors="pt" ).to(a_ )
# We just test that these run without errors - the models are randomly initialized
# and so the actual text outputs will be garbage
model.generate(**a_ , do_sample=a_ , max_new_tokens=4 )
model.generate(**a_ , do_sample=a_ , max_new_tokens=4 )
model.generate(**a_ , num_beams=2 , max_new_tokens=4 )
@slow
def A ( self : Any ):
"""simple docstring"""
with torch.no_grad():
for repo in [
"Rocketknight1/falcon-rw-1b",
"Rocketknight1/tiny-random-falcon-7b",
"Rocketknight1/tiny-random-falcon-40b",
]:
__snake_case = AutoTokenizer.from_pretrained(a_ )
__snake_case = FalconForCausalLM.from_pretrained(a_ )
model.eval()
model.to(device=a_ )
__snake_case = tokenizer("My favorite food is" , return_tensors="pt" ).to(a_ )
# Test results are the same with and without cache
__snake_case = model.generate(**a_ , do_sample=a_ , max_new_tokens=20 , use_cache=a_ )
__snake_case = model.generate(**a_ , do_sample=a_ , max_new_tokens=20 , use_cache=a_ )
self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0 )
| 69 | 1 |
'''simple docstring'''
from itertools import permutations
def __UpperCAmelCase ( _UpperCAmelCase : tuple ) -> bool:
if num[3] % 2 != 0:
return False
if (num[2] + num[3] + num[4]) % 3 != 0:
return False
if num[5] % 5 != 0:
return False
__snake_case = [7, 11, 13, 17]
for i, test in enumerate(_UpperCAmelCase ):
if (num[i + 4] * 1_00 + num[i + 5] * 10 + num[i + 6]) % test != 0:
return False
return True
def __UpperCAmelCase ( _UpperCAmelCase : int = 10 ) -> int:
return sum(
int("".join(map(_UpperCAmelCase , _UpperCAmelCase ) ) )
for num in permutations(range(_UpperCAmelCase ) )
if is_substring_divisible(_UpperCAmelCase ) )
if __name__ == "__main__":
print(F'''{solution() = }''')
| 69 |
'''simple docstring'''
import mpmath # for roots of unity
import numpy as np
class SCREAMING_SNAKE_CASE__ :
def __init__( self : Tuple , a_ : Optional[int]=None , a_ : int=None ):
"""simple docstring"""
__snake_case = list(poly_a or [0] )[:]
__snake_case = list(poly_b or [0] )[:]
# Remove leading zero coefficients
while self.polyA[-1] == 0:
self.polyA.pop()
__snake_case = len(self.polyA )
while self.polyB[-1] == 0:
self.polyB.pop()
__snake_case = len(self.polyB )
# Add 0 to make lengths equal a power of 2
__snake_case = int(
2 ** np.ceil(np.loga(len(self.polyA ) + len(self.polyB ) - 1 ) ) )
while len(self.polyA ) < self.c_max_length:
self.polyA.append(0 )
while len(self.polyB ) < self.c_max_length:
self.polyB.append(0 )
# A complex root used for the fourier transform
__snake_case = complex(mpmath.root(x=1 , n=self.c_max_length , k=1 ) )
# The product
__snake_case = self.__multiply()
def A ( self : Any , a_ : Optional[Any] ):
"""simple docstring"""
__snake_case = [[x] for x in self.polyA] if which == "A" else [[x] for x in self.polyB]
# Corner case
if len(a_ ) <= 1:
return dft[0]
#
__snake_case = self.c_max_length // 2
while next_ncol > 0:
__snake_case = [[] for i in range(a_ )]
__snake_case = self.root**next_ncol
# First half of next step
__snake_case = 1
for j in range(self.c_max_length // (next_ncol * 2) ):
for i in range(a_ ):
new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j] )
current_root *= root
# Second half of next step
__snake_case = 1
for j in range(self.c_max_length // (next_ncol * 2) ):
for i in range(a_ ):
new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j] )
current_root *= root
# Update
__snake_case = new_dft
__snake_case = next_ncol // 2
return dft[0]
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = self.__dft("A" )
__snake_case = self.__dft("B" )
__snake_case = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length )]]
del dft_a
del dft_b
# Corner Case
if len(inverce_c[0] ) <= 1:
return inverce_c[0]
# Inverse DFT
__snake_case = 2
while next_ncol <= self.c_max_length:
__snake_case = [[] for i in range(a_ )]
__snake_case = self.root ** (next_ncol // 2)
__snake_case = 1
# First half of next step
for j in range(self.c_max_length // next_ncol ):
for i in range(next_ncol // 2 ):
# Even positions
new_inverse_c[i].append(
(
inverce_c[i][j]
+ inverce_c[i][j + self.c_max_length // next_ncol]
)
/ 2 )
# Odd positions
new_inverse_c[i + next_ncol // 2].append(
(
inverce_c[i][j]
- inverce_c[i][j + self.c_max_length // next_ncol]
)
/ (2 * current_root) )
current_root *= root
# Update
__snake_case = new_inverse_c
next_ncol *= 2
# Unpack
__snake_case = [round(x[0].real , 8 ) + round(x[0].imag , 8 ) * 1j for x in inverce_c]
# Remove leading 0's
while inverce_c[-1] == 0:
inverce_c.pop()
return inverce_c
def __str__( self : Optional[int] ):
"""simple docstring"""
__snake_case = "A = " + " + ".join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.polyA[: self.len_A] ) )
__snake_case = "B = " + " + ".join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.polyB[: self.len_B] ) )
__snake_case = "A*B = " + " + ".join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.product ) )
return f'''{a}\n{b}\n{c}'''
# Unit tests
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 | 1 |
'''simple docstring'''
import mpmath # for roots of unity
import numpy as np
class SCREAMING_SNAKE_CASE__ :
def __init__( self : Tuple , a_ : Optional[int]=None , a_ : int=None ):
"""simple docstring"""
__snake_case = list(poly_a or [0] )[:]
__snake_case = list(poly_b or [0] )[:]
# Remove leading zero coefficients
while self.polyA[-1] == 0:
self.polyA.pop()
__snake_case = len(self.polyA )
while self.polyB[-1] == 0:
self.polyB.pop()
__snake_case = len(self.polyB )
# Add 0 to make lengths equal a power of 2
__snake_case = int(
2 ** np.ceil(np.loga(len(self.polyA ) + len(self.polyB ) - 1 ) ) )
while len(self.polyA ) < self.c_max_length:
self.polyA.append(0 )
while len(self.polyB ) < self.c_max_length:
self.polyB.append(0 )
# A complex root used for the fourier transform
__snake_case = complex(mpmath.root(x=1 , n=self.c_max_length , k=1 ) )
# The product
__snake_case = self.__multiply()
def A ( self : Any , a_ : Optional[Any] ):
"""simple docstring"""
__snake_case = [[x] for x in self.polyA] if which == "A" else [[x] for x in self.polyB]
# Corner case
if len(a_ ) <= 1:
return dft[0]
#
__snake_case = self.c_max_length // 2
while next_ncol > 0:
__snake_case = [[] for i in range(a_ )]
__snake_case = self.root**next_ncol
# First half of next step
__snake_case = 1
for j in range(self.c_max_length // (next_ncol * 2) ):
for i in range(a_ ):
new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j] )
current_root *= root
# Second half of next step
__snake_case = 1
for j in range(self.c_max_length // (next_ncol * 2) ):
for i in range(a_ ):
new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j] )
current_root *= root
# Update
__snake_case = new_dft
__snake_case = next_ncol // 2
return dft[0]
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = self.__dft("A" )
__snake_case = self.__dft("B" )
__snake_case = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length )]]
del dft_a
del dft_b
# Corner Case
if len(inverce_c[0] ) <= 1:
return inverce_c[0]
# Inverse DFT
__snake_case = 2
while next_ncol <= self.c_max_length:
__snake_case = [[] for i in range(a_ )]
__snake_case = self.root ** (next_ncol // 2)
__snake_case = 1
# First half of next step
for j in range(self.c_max_length // next_ncol ):
for i in range(next_ncol // 2 ):
# Even positions
new_inverse_c[i].append(
(
inverce_c[i][j]
+ inverce_c[i][j + self.c_max_length // next_ncol]
)
/ 2 )
# Odd positions
new_inverse_c[i + next_ncol // 2].append(
(
inverce_c[i][j]
- inverce_c[i][j + self.c_max_length // next_ncol]
)
/ (2 * current_root) )
current_root *= root
# Update
__snake_case = new_inverse_c
next_ncol *= 2
# Unpack
__snake_case = [round(x[0].real , 8 ) + round(x[0].imag , 8 ) * 1j for x in inverce_c]
# Remove leading 0's
while inverce_c[-1] == 0:
inverce_c.pop()
return inverce_c
def __str__( self : Optional[int] ):
"""simple docstring"""
__snake_case = "A = " + " + ".join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.polyA[: self.len_A] ) )
__snake_case = "B = " + " + ".join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.polyB[: self.len_B] ) )
__snake_case = "A*B = " + " + ".join(
f'''{coef}*x^{i}''' for coef, i in enumerate(self.product ) )
return f'''{a}\n{b}\n{c}'''
# Unit tests
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
a : List[Any] = {
'''configuration_table_transformer''': [
'''TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''TableTransformerConfig''',
'''TableTransformerOnnxConfig''',
]
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : Tuple = [
'''TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TableTransformerForObjectDetection''',
'''TableTransformerModel''',
'''TableTransformerPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_table_transformer import (
TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
TableTransformerConfig,
TableTransformerOnnxConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_table_transformer import (
TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TableTransformerForObjectDetection,
TableTransformerModel,
TableTransformerPreTrainedModel,
)
else:
import sys
a : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 69 | 1 |
'''simple docstring'''
from __future__ import annotations
import unittest
from transformers import DebertaVaConfig, 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 (
TFDebertaVaForMaskedLM,
TFDebertaVaForQuestionAnswering,
TFDebertaVaForSequenceClassification,
TFDebertaVaForTokenClassification,
TFDebertaVaModel,
)
class SCREAMING_SNAKE_CASE__ :
def __init__( self : str , a_ : int , a_ : Tuple=13 , a_ : str=7 , a_ : Tuple=True , a_ : Optional[Any]=True , a_ : Union[str, Any]=True , a_ : List[str]=True , a_ : List[Any]=99 , a_ : Optional[int]=32 , a_ : int=2 , a_ : int=4 , a_ : str=37 , a_ : Dict="gelu" , a_ : List[str]=0.1 , a_ : Any=0.1 , a_ : Any=512 , a_ : Any=16 , a_ : List[Any]=2 , a_ : List[str]=0.02 , a_ : Optional[Any]=False , a_ : List[Any]=True , a_ : Optional[Any]="None" , a_ : int=3 , a_ : int=4 , a_ : List[Any]=None , ):
"""simple docstring"""
__snake_case = parent
__snake_case = batch_size
__snake_case = seq_length
__snake_case = is_training
__snake_case = use_input_mask
__snake_case = use_token_type_ids
__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_act
__snake_case = hidden_dropout_prob
__snake_case = attention_probs_dropout_prob
__snake_case = max_position_embeddings
__snake_case = type_vocab_size
__snake_case = type_sequence_label_size
__snake_case = initializer_range
__snake_case = num_labels
__snake_case = num_choices
__snake_case = relative_attention
__snake_case = position_biased_input
__snake_case = pos_att_type
__snake_case = scope
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__snake_case = None
if self.use_input_mask:
__snake_case = random_attention_mask([self.batch_size, self.seq_length] )
__snake_case = None
if self.use_token_type_ids:
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
__snake_case = None
__snake_case = None
__snake_case = None
if self.use_labels:
__snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__snake_case = DebertaVaConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , initializer_range=self.initializer_range , return_dict=a_ , )
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def A ( self : Any , a_ : Optional[Any] , a_ : str , a_ : List[str] , a_ : str , a_ : Union[str, Any] , a_ : Tuple , a_ : Dict ):
"""simple docstring"""
__snake_case = TFDebertaVaModel(config=a_ )
__snake_case = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
__snake_case = [input_ids, input_mask]
__snake_case = model(a_ )
__snake_case = model(a_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def A ( self : Dict , a_ : Any , a_ : Any , a_ : Union[str, Any] , a_ : str , a_ : Optional[Any] , a_ : Union[str, Any] , a_ : Dict ):
"""simple docstring"""
__snake_case = TFDebertaVaForMaskedLM(config=a_ )
__snake_case = {
"input_ids": input_ids,
"attention_mask": input_mask,
"token_type_ids": token_type_ids,
}
__snake_case = model(a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def A ( self : Dict , a_ : List[str] , a_ : List[str] , a_ : List[str] , a_ : List[str] , a_ : Union[str, Any] , a_ : Optional[int] , a_ : List[str] ):
"""simple docstring"""
__snake_case = self.num_labels
__snake_case = TFDebertaVaForSequenceClassification(config=a_ )
__snake_case = {
"input_ids": input_ids,
"attention_mask": input_mask,
"token_type_ids": token_type_ids,
}
__snake_case = model(a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def A ( self : Union[str, Any] , a_ : Tuple , a_ : int , a_ : Tuple , a_ : Union[str, Any] , a_ : List[str] , a_ : Union[str, Any] , a_ : List[Any] ):
"""simple docstring"""
__snake_case = self.num_labels
__snake_case = TFDebertaVaForTokenClassification(config=a_ )
__snake_case = {
"input_ids": input_ids,
"attention_mask": input_mask,
"token_type_ids": token_type_ids,
}
__snake_case = model(a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def A ( self : Any , a_ : Optional[int] , a_ : Optional[Any] , a_ : Any , a_ : Any , a_ : Dict , a_ : int , a_ : Optional[int] ):
"""simple docstring"""
__snake_case = TFDebertaVaForQuestionAnswering(config=a_ )
__snake_case = {
"input_ids": input_ids,
"attention_mask": input_mask,
"token_type_ids": token_type_ids,
}
__snake_case = model(a_ )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = self.prepare_config_and_inputs()
(
(
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) ,
) = config_and_inputs
__snake_case = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_tf
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = (
(
TFDebertaVaModel,
TFDebertaVaForMaskedLM,
TFDebertaVaForQuestionAnswering,
TFDebertaVaForSequenceClassification,
TFDebertaVaForTokenClassification,
)
if is_tf_available()
else ()
)
__SCREAMING_SNAKE_CASE = (
{
"""feature-extraction""": TFDebertaVaModel,
"""fill-mask""": TFDebertaVaForMaskedLM,
"""question-answering""": TFDebertaVaForQuestionAnswering,
"""text-classification""": TFDebertaVaForSequenceClassification,
"""token-classification""": TFDebertaVaForTokenClassification,
"""zero-shot""": TFDebertaVaForSequenceClassification,
}
if is_tf_available()
else {}
)
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = False
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = TFDebertaVaModelTester(self )
__snake_case = ConfigTester(self , config_class=a_ , hidden_size=37 )
def A ( self : Dict ):
"""simple docstring"""
self.config_tester.run_common_tests()
def A ( self : List[str] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*a_ )
def A ( self : Any ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*a_ )
def A ( self : str ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*a_ )
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*a_ )
def A ( self : int ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*a_ )
@slow
def A ( self : List[str] ):
"""simple docstring"""
__snake_case = TFDebertaVaModel.from_pretrained("kamalkraj/deberta-v2-xlarge" )
self.assertIsNotNone(a_ )
@require_tf
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
@unittest.skip(reason="Model not available yet" )
def A ( self : Optional[int] ):
"""simple docstring"""
pass
@slow
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = TFDebertaVaModel.from_pretrained("kamalkraj/deberta-v2-xlarge" )
__snake_case = tf.constant([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] )
__snake_case = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
__snake_case = model(a_ , attention_mask=a_ )[0]
__snake_case = tf.constant(
[[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] )
tf.debugging.assert_near(output[:, 1:4, 1:4] , a_ , atol=1e-4 )
| 69 |
'''simple docstring'''
import json
import os
import torch
from diffusers import UNetaDModel
os.makedirs('''hub/hopper-medium-v2/unet/hor32''', exist_ok=True)
os.makedirs('''hub/hopper-medium-v2/unet/hor128''', exist_ok=True)
os.makedirs('''hub/hopper-medium-v2/value_function''', exist_ok=True)
def __UpperCAmelCase ( _UpperCAmelCase : List[str] ) -> str:
if hor == 1_28:
__snake_case = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D")
__snake_case = (32, 1_28, 2_56)
__snake_case = ("UpResnetBlock1D", "UpResnetBlock1D")
elif hor == 32:
__snake_case = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D")
__snake_case = (32, 64, 1_28, 2_56)
__snake_case = ("UpResnetBlock1D", "UpResnetBlock1D", "UpResnetBlock1D")
__snake_case = torch.load(F'''/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch''' )
__snake_case = model.state_dict()
__snake_case = {
"down_block_types": down_block_types,
"block_out_channels": block_out_channels,
"up_block_types": up_block_types,
"layers_per_block": 1,
"use_timestep_embedding": True,
"out_block_type": "OutConv1DBlock",
"norm_num_groups": 8,
"downsample_each_block": False,
"in_channels": 14,
"out_channels": 14,
"extra_in_channels": 0,
"time_embedding_type": "positional",
"flip_sin_to_cos": False,
"freq_shift": 1,
"sample_size": 6_55_36,
"mid_block_type": "MidResTemporalBlock1D",
"act_fn": "mish",
}
__snake_case = UNetaDModel(**_UpperCAmelCase )
print(F'''length of state dict: {len(state_dict.keys() )}''' )
print(F'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' )
__snake_case = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) )
for k, v in mapping.items():
__snake_case = state_dict.pop(_UpperCAmelCase )
hf_value_function.load_state_dict(_UpperCAmelCase )
torch.save(hf_value_function.state_dict() , F'''hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin''' )
with open(F'''hub/hopper-medium-v2/unet/hor{hor}/config.json''' , "w" ) as f:
json.dump(_UpperCAmelCase , _UpperCAmelCase )
def __UpperCAmelCase ( ) -> List[Any]:
__snake_case = {
"in_channels": 14,
"down_block_types": ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D"),
"up_block_types": (),
"out_block_type": "ValueFunction",
"mid_block_type": "ValueFunctionMidBlock1D",
"block_out_channels": (32, 64, 1_28, 2_56),
"layers_per_block": 1,
"downsample_each_block": True,
"sample_size": 6_55_36,
"out_channels": 14,
"extra_in_channels": 0,
"time_embedding_type": "positional",
"use_timestep_embedding": True,
"flip_sin_to_cos": False,
"freq_shift": 1,
"norm_num_groups": 8,
"act_fn": "mish",
}
__snake_case = torch.load("/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch" )
__snake_case = model
__snake_case = UNetaDModel(**_UpperCAmelCase )
print(F'''length of state dict: {len(state_dict.keys() )}''' )
print(F'''length of value function dict: {len(hf_value_function.state_dict().keys() )}''' )
__snake_case = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) )
for k, v in mapping.items():
__snake_case = state_dict.pop(_UpperCAmelCase )
hf_value_function.load_state_dict(_UpperCAmelCase )
torch.save(hf_value_function.state_dict() , "hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin" )
with open("hub/hopper-medium-v2/value_function/config.json" , "w" ) as f:
json.dump(_UpperCAmelCase , _UpperCAmelCase )
if __name__ == "__main__":
unet(32)
# unet(128)
value_function()
| 69 | 1 |
'''simple docstring'''
import requests
from bsa import BeautifulSoup
def __UpperCAmelCase ( _UpperCAmelCase : str = "https://www.worldometers.info/coronavirus" ) -> dict:
__snake_case = BeautifulSoup(requests.get(_UpperCAmelCase ).text , "html.parser" )
__snake_case = soup.findAll("h1" )
__snake_case = 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''')
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int = 1_00_00_00 ) -> int:
__snake_case = 1
__snake_case = 1
__snake_case = {1: 1}
for inputa in range(2 , _UpperCAmelCase ):
__snake_case = 0
__snake_case = inputa
while True:
if number in counters:
counter += counters[number]
break
if number % 2 == 0:
number //= 2
counter += 1
else:
__snake_case = (3 * number) + 1
counter += 1
if inputa not in counters:
__snake_case = counter
if counter > pre_counter:
__snake_case = inputa
__snake_case = counter
return largest_number
if __name__ == "__main__":
print(solution(int(input().strip())))
| 69 | 1 |
'''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 __UpperCAmelCase ( _UpperCAmelCase : List[str] ) -> List[str]:
__snake_case = [2, 2, 6, 2] if "tiny" in model_name else [2, 2, 18, 2]
__snake_case = True if "large" in model_name or "huge" in model_name else False
__snake_case = True if "large" in model_name or "huge" in model_name else False
__snake_case = 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:
__snake_case = [3, 3, 3, 3]
__snake_case = [5, 5, 5, 5]
elif "fl4" in model_name:
__snake_case = [4, 4, 4, 4]
__snake_case = [3, 3, 3, 3]
if "tiny" in model_name or "small" in model_name or "base" in model_name:
__snake_case = [3, 3, 3, 3]
if "lrf" in model_name:
__snake_case = [3, 3, 3, 3]
else:
__snake_case = [2, 2, 2, 2]
if "tiny" in model_name:
__snake_case = 96
elif "small" in model_name:
__snake_case = 96
elif "base" in model_name:
__snake_case = 1_28
elif "large" in model_name:
__snake_case = 1_92
elif "xlarge" in model_name:
__snake_case = 2_56
elif "huge" in model_name:
__snake_case = 3_52
# set label information
__snake_case = "huggingface/label-files"
if "large" in model_name or "huge" in model_name:
__snake_case = "imagenet-22k-id2label.json"
else:
__snake_case = "imagenet-1k-id2label.json"
__snake_case = json.load(open(hf_hub_download(_UpperCAmelCase , _UpperCAmelCase , repo_type="dataset" ) , "r" ) )
__snake_case = {int(_UpperCAmelCase ): v for k, v in idalabel.items()}
__snake_case = {v: k for k, v in idalabel.items()}
__snake_case = FocalNetConfig(
embed_dim=_UpperCAmelCase , depths=_UpperCAmelCase , focal_levels=_UpperCAmelCase , focal_windows=_UpperCAmelCase , use_conv_embed=_UpperCAmelCase , idalabel=_UpperCAmelCase , labelaid=_UpperCAmelCase , use_post_layernorm=_UpperCAmelCase , use_layerscale=_UpperCAmelCase , )
return config
def __UpperCAmelCase ( _UpperCAmelCase : Tuple ) -> Optional[Any]:
if "patch_embed.proj" in name:
__snake_case = name.replace("patch_embed.proj" , "embeddings.patch_embeddings.projection" )
if "patch_embed.norm" in name:
__snake_case = name.replace("patch_embed.norm" , "embeddings.norm" )
if "layers" in name:
__snake_case = "encoder." + name
if "encoder.layers" in name:
__snake_case = name.replace("encoder.layers" , "encoder.stages" )
if "downsample.proj" in name:
__snake_case = name.replace("downsample.proj" , "downsample.projection" )
if "blocks" in name:
__snake_case = name.replace("blocks" , "layers" )
if "modulation.f.weight" in name or "modulation.f.bias" in name:
__snake_case = name.replace("modulation.f" , "modulation.projection_in" )
if "modulation.h.weight" in name or "modulation.h.bias" in name:
__snake_case = name.replace("modulation.h" , "modulation.projection_context" )
if "modulation.proj.weight" in name or "modulation.proj.bias" in name:
__snake_case = name.replace("modulation.proj" , "modulation.projection_out" )
if name == "norm.weight":
__snake_case = "layernorm.weight"
if name == "norm.bias":
__snake_case = "layernorm.bias"
if "head" in name:
__snake_case = name.replace("head" , "classifier" )
else:
__snake_case = "focalnet." + name
return name
def __UpperCAmelCase ( _UpperCAmelCase : List[str] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : List[str]=False ) -> Dict:
# fmt: off
__snake_case = {
"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
__snake_case = model_name_to_url[model_name]
print("Checkpoint URL: " , _UpperCAmelCase )
__snake_case = torch.hub.load_state_dict_from_url(_UpperCAmelCase , map_location="cpu" )["model"]
# rename keys
for key in state_dict.copy().keys():
__snake_case = state_dict.pop(_UpperCAmelCase )
__snake_case = val
__snake_case = get_focalnet_config(_UpperCAmelCase )
__snake_case = FocalNetForImageClassification(_UpperCAmelCase )
model.eval()
# load state dict
model.load_state_dict(_UpperCAmelCase )
# verify conversion
__snake_case = "http://images.cocodataset.org/val2017/000000039769.jpg"
__snake_case = BitImageProcessor(
do_resize=_UpperCAmelCase , size={"shortest_edge": 2_56} , resample=PILImageResampling.BILINEAR , do_center_crop=_UpperCAmelCase , crop_size=2_24 , do_normalize=_UpperCAmelCase , image_mean=_UpperCAmelCase , image_std=_UpperCAmelCase , )
__snake_case = Image.open(requests.get(_UpperCAmelCase , stream=_UpperCAmelCase ).raw )
__snake_case = processor(images=_UpperCAmelCase , return_tensors="pt" )
__snake_case = transforms.Compose(
[
transforms.Resize(2_56 ),
transforms.CenterCrop(2_24 ),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ),
] )
__snake_case = image_transforms(_UpperCAmelCase ).unsqueeze(0 )
# verify pixel_values
assert torch.allclose(inputs.pixel_values , _UpperCAmelCase , atol=1E-4 )
__snake_case = model(**_UpperCAmelCase )
__snake_case = 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":
__snake_case = torch.tensor([0.2166, -0.4368, 0.2191] )
elif model_name == "focalnet-tiny-lrf":
__snake_case = torch.tensor([1.1669, 0.0125, -0.1695] )
elif model_name == "focalnet-small":
__snake_case = torch.tensor([0.4917, -0.0430, 0.1341] )
elif model_name == "focalnet-small-lrf":
__snake_case = torch.tensor([-0.2588, -0.5342, -0.2331] )
elif model_name == "focalnet-base":
__snake_case = torch.tensor([-0.1655, -0.4090, -0.1730] )
elif model_name == "focalnet-base-lrf":
__snake_case = torch.tensor([0.5306, -0.0483, -0.3928] )
assert torch.allclose(outputs.logits[0, :3] , _UpperCAmelCase , 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(_UpperCAmelCase )
processor.save_pretrained(_UpperCAmelCase )
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__":
a : int = 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.''',
)
a : List[Any] = parser.parse_args()
convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 69 |
'''simple docstring'''
from ...processing_utils import ProcessorMixin
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = """SpeechT5FeatureExtractor"""
__SCREAMING_SNAKE_CASE = """SpeechT5Tokenizer"""
def __init__( self : List[Any] , a_ : str , a_ : str ):
"""simple docstring"""
super().__init__(a_ , a_ )
def __call__( self : Dict , *a_ : Tuple , **a_ : List[str] ):
"""simple docstring"""
__snake_case = kwargs.pop("audio" , a_ )
__snake_case = kwargs.pop("text" , a_ )
__snake_case = kwargs.pop("text_target" , a_ )
__snake_case = kwargs.pop("audio_target" , a_ )
__snake_case = kwargs.pop("sampling_rate" , a_ )
if audio is not None and text is not None:
raise ValueError(
"Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?" )
if audio_target is not None and text_target is not None:
raise ValueError(
"Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?" )
if audio is None and audio_target is None and text is None and text_target is None:
raise ValueError(
"You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process." )
if audio is not None:
__snake_case = self.feature_extractor(a_ , *a_ , sampling_rate=a_ , **a_ )
elif text is not None:
__snake_case = self.tokenizer(a_ , **a_ )
else:
__snake_case = None
if audio_target is not None:
__snake_case = self.feature_extractor(audio_target=a_ , *a_ , sampling_rate=a_ , **a_ )
__snake_case = targets["input_values"]
elif text_target is not None:
__snake_case = self.tokenizer(a_ , **a_ )
__snake_case = targets["input_ids"]
else:
__snake_case = None
if inputs is None:
return targets
if targets is not None:
__snake_case = labels
__snake_case = targets.get("attention_mask" )
if decoder_attention_mask is not None:
__snake_case = decoder_attention_mask
return inputs
def A ( self : List[str] , *a_ : str , **a_ : Dict ):
"""simple docstring"""
__snake_case = kwargs.pop("input_values" , a_ )
__snake_case = kwargs.pop("input_ids" , a_ )
__snake_case = kwargs.pop("labels" , a_ )
if input_values is not None and input_ids is not None:
raise ValueError("Cannot process both `input_values` and `input_ids` inputs." )
if input_values is None and input_ids is None and labels is None:
raise ValueError(
"You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded." )
if input_values is not None:
__snake_case = self.feature_extractor.pad(a_ , *a_ , **a_ )
elif input_ids is not None:
__snake_case = self.tokenizer.pad(a_ , **a_ )
else:
__snake_case = None
if labels is not None:
if "input_ids" in labels or (isinstance(a_ , a_ ) and "input_ids" in labels[0]):
__snake_case = self.tokenizer.pad(a_ , **a_ )
__snake_case = targets["input_ids"]
else:
__snake_case = self.feature_extractor.feature_size
__snake_case = self.feature_extractor.num_mel_bins
__snake_case = self.feature_extractor.pad(a_ , *a_ , **a_ )
__snake_case = feature_size_hack
__snake_case = targets["input_values"]
else:
__snake_case = None
if inputs is None:
return targets
if targets is not None:
__snake_case = labels
__snake_case = targets.get("attention_mask" )
if decoder_attention_mask is not None:
__snake_case = decoder_attention_mask
return inputs
def A ( self : List[str] , *a_ : Any , **a_ : List[str] ):
"""simple docstring"""
return self.tokenizer.batch_decode(*a_ , **a_ )
def A ( self : Optional[int] , *a_ : Union[str, Any] , **a_ : str ):
"""simple docstring"""
return self.tokenizer.decode(*a_ , **a_ )
| 69 | 1 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : int ) -> str:
if a < 0 or b < 0:
raise ValueError("the value of both inputs must be positive" )
__snake_case = str(bin(_UpperCAmelCase ) )[2:] # remove the leading "0b"
__snake_case = str(bin(_UpperCAmelCase ) )[2:] # remove the leading "0b"
__snake_case = max(len(_UpperCAmelCase ) , len(_UpperCAmelCase ) )
return "0b" + "".join(
str(int(char_a != char_b ) )
for char_a, char_b in zip(a_binary.zfill(_UpperCAmelCase ) , b_binary.zfill(_UpperCAmelCase ) ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 |
'''simple docstring'''
import re
from pathlib import Path
from unittest import TestCase
import pytest
@pytest.mark.integration
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def A ( self : Optional[Any] , a_ : str ):
"""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 A ( self : Any , a_ : str ):
"""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 A ( self : Optional[int] ):
"""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 A ( self : Optional[Any] ):
"""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.''' )
| 69 | 1 |
'''simple docstring'''
from itertools import product
def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : int ) -> list[int]:
__snake_case = sides_number
__snake_case = max_face_number * dice_number
__snake_case = [0] * (max_total + 1)
__snake_case = 1
__snake_case = range(_UpperCAmelCase , max_face_number + 1 )
for dice_numbers in product(_UpperCAmelCase , repeat=_UpperCAmelCase ):
__snake_case = sum(_UpperCAmelCase )
totals_frequencies[total] += 1
return totals_frequencies
def __UpperCAmelCase ( ) -> float:
__snake_case = total_frequency_distribution(
sides_number=4 , dice_number=9 )
__snake_case = total_frequency_distribution(
sides_number=6 , dice_number=6 )
__snake_case = 0
__snake_case = 9
__snake_case = 4 * 9
__snake_case = 6
for peter_total in range(_UpperCAmelCase , max_peter_total + 1 ):
peter_wins_count += peter_totals_frequencies[peter_total] * sum(
colin_totals_frequencies[min_colin_total:peter_total] )
__snake_case = (4**9) * (6**6)
__snake_case = peter_wins_count / total_games_number
__snake_case = round(_UpperCAmelCase , ndigits=7 )
return rounded_peter_win_probability
if __name__ == "__main__":
print(F'''{solution() = }''')
| 69 |
'''simple docstring'''
import os
from shutil import copyfile
from typing import List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
a : Optional[Any] = logging.get_logger(__name__)
a : Dict = {'''vocab_file''': '''sentencepiece.model'''}
a : Tuple = {
'''vocab_file''': {
'''google/rembert''': '''https://huggingface.co/google/rembert/resolve/main/sentencepiece.model''',
},
}
a : str = {
'''google/rembert''': 256,
}
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES
__SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP
__SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__( self : Optional[Any] , a_ : int , a_ : Any=False , a_ : List[Any]=True , a_ : List[Any]=True , a_ : List[Any]="[CLS]" , a_ : List[Any]="[SEP]" , a_ : List[Any]="[UNK]" , a_ : str="[SEP]" , a_ : List[str]="[PAD]" , a_ : Optional[int]="[CLS]" , a_ : List[str]="[MASK]" , **a_ : str , ):
"""simple docstring"""
super().__init__(
do_lower_case=a_ , remove_space=a_ , keep_accents=a_ , bos_token=a_ , eos_token=a_ , unk_token=a_ , sep_token=a_ , pad_token=a_ , cls_token=a_ , mask_token=a_ , **a_ , )
__snake_case = do_lower_case
__snake_case = remove_space
__snake_case = keep_accents
__snake_case = vocab_file
__snake_case = spm.SentencePieceProcessor()
self.sp_model.Load(a_ )
@property
def A ( self : Optional[Any] ):
"""simple docstring"""
return len(self.sp_model )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = {self.convert_ids_to_tokens(a_ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self : Dict ):
"""simple docstring"""
__snake_case = self.__dict__.copy()
__snake_case = None
return state
def __setstate__( self : str , a_ : Optional[int] ):
"""simple docstring"""
__snake_case = d
__snake_case = spm.SentencePieceProcessor()
self.sp_model.Load(self.vocab_file )
def A ( self : Tuple , a_ : Optional[int] , a_ : int=False ):
"""simple docstring"""
__snake_case = self.sp_model.EncodeAsPieces(a_ )
return pieces
def A ( self : Any , a_ : Optional[Any] ):
"""simple docstring"""
return self.sp_model.PieceToId(a_ )
def A ( self : Optional[Any] , a_ : List[str] ):
"""simple docstring"""
return self.sp_model.IdToPiece(a_ )
def A ( self : Optional[Any] , a_ : int ):
"""simple docstring"""
__snake_case = self.sp_model.decode_pieces(a_ )
return out_string
def A ( self : Union[str, Any] , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
__snake_case = [self.sep_token_id]
__snake_case = [self.cls_token_id]
if token_ids_a is None:
return cls + token_ids_a + sep
return cls + token_ids_a + sep + token_ids_a + sep
def A ( self : List[str] , a_ : List[int] , a_ : Optional[List[int]] = None , a_ : bool = False ):
"""simple docstring"""
if already_has_special_tokens:
if token_ids_a is not None:
raise ValueError(
"You should not supply a second sequence if the provided sequence of "
"ids is already formatted with special tokens for the model." )
return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]
if token_ids_a is not None:
return [1] + ([0] * len(a_ )) + [1] + ([0] * len(a_ )) + [1]
return [1] + ([0] * len(a_ )) + [1]
def A ( self : Tuple , a_ : List[int] , a_ : Optional[List[int]] = None ):
"""simple docstring"""
__snake_case = [self.sep_token_id]
__snake_case = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def A ( self : List[Any] , a_ : str , a_ : Optional[str] = None ):
"""simple docstring"""
if not os.path.isdir(a_ ):
logger.error("Vocabulary path ({}) should be a directory".format(a_ ) )
return
__snake_case = 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_ ):
copyfile(self.vocab_file , a_ )
return (out_vocab_file,)
| 69 | 1 |
'''simple docstring'''
import math
import numpy as np
import qiskit
from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute
def __UpperCAmelCase ( _UpperCAmelCase : int = 3 ) -> qiskit.result.counts.Counts:
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)." )
__snake_case = QuantumRegister(_UpperCAmelCase , "qr" )
__snake_case = ClassicalRegister(_UpperCAmelCase , "cr" )
__snake_case = QuantumCircuit(_UpperCAmelCase , _UpperCAmelCase )
__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
__snake_case = Aer.get_backend("qasm_simulator" )
__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)}'''
)
| 69 |
'''simple docstring'''
import os
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from huggingface_hub import HfFolder, delete_repo
from huggingface_hub.file_download import http_get
from requests.exceptions import HTTPError
from transformers import (
AlbertTokenizer,
AutoTokenizer,
BertTokenizer,
BertTokenizerFast,
GPTaTokenizerFast,
is_tokenizers_available,
)
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers
from transformers.tokenization_utils import Trie
sys.path.append(str(Path(__file__).parent.parent / '''utils'''))
from test_module.custom_tokenization import CustomTokenizer # noqa E402
if is_tokenizers_available():
from test_module.custom_tokenization_fast import CustomTokenizerFast
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = mock.Mock()
__snake_case = 500
__snake_case = {}
__snake_case = HTTPError
__snake_case = {}
# Download this model to make sure it's in the cache.
__snake_case = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" )
# Under the mock environment we get a 500 error when trying to reach the tokenizer.
with mock.patch("requests.Session.request" , return_value=a_ ) as mock_head:
__snake_case = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" )
# This check we did call the fake head request
mock_head.assert_called()
@require_tokenizers
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = mock.Mock()
__snake_case = 500
__snake_case = {}
__snake_case = HTTPError
__snake_case = {}
# Download this model to make sure it's in the cache.
__snake_case = GPTaTokenizerFast.from_pretrained("gpt2" )
# Under the mock environment we get a 500 error when trying to reach the tokenizer.
with mock.patch("requests.Session.request" , return_value=a_ ) as mock_head:
__snake_case = GPTaTokenizerFast.from_pretrained("gpt2" )
# This check we did call the fake head request
mock_head.assert_called()
def A ( self : Optional[Any] ):
"""simple docstring"""
try:
__snake_case = tempfile.mktemp()
with open(a_ , "wb" ) as f:
http_get("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" , a_ )
__snake_case = AlbertTokenizer.from_pretrained(a_ )
finally:
os.remove(a_ )
# Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in
# the current folder and have the right name.
if os.path.isfile("tokenizer.json" ):
# We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it.
return
try:
with open("tokenizer.json" , "wb" ) as f:
http_get("https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json" , a_ )
__snake_case = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" )
# The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000
self.assertEqual(tokenizer.vocab_size , 1_000 )
# Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file.
finally:
os.remove("tokenizer.json" )
def A ( self : str ):
"""simple docstring"""
__snake_case = AlbertTokenizer.from_pretrained("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" )
@is_staging_test
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
__SCREAMING_SNAKE_CASE = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""]
@classmethod
def A ( cls : List[Any] ):
"""simple docstring"""
__snake_case = TOKEN
HfFolder.save_token(a_ )
@classmethod
def A ( cls : List[Any] ):
"""simple docstring"""
try:
delete_repo(token=cls._token , repo_id="test-tokenizer" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="valid_org/test-tokenizer-org" )
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="test-dynamic-tokenizer" )
except HTTPError:
pass
def A ( self : int ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = BertTokenizer(a_ )
tokenizer.push_to_hub("test-tokenizer" , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
# Reset repo
delete_repo(token=self._token , repo_id="test-tokenizer" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(a_ , repo_id="test-tokenizer" , push_to_hub=a_ , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
def A ( self : int ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = BertTokenizer(a_ )
tokenizer.push_to_hub("valid_org/test-tokenizer-org" , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
# Reset repo
delete_repo(token=self._token , repo_id="valid_org/test-tokenizer-org" )
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(
a_ , repo_id="valid_org/test-tokenizer-org" , push_to_hub=a_ , use_auth_token=self._token )
__snake_case = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" )
self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab )
@require_tokenizers
def A ( self : List[str] ):
"""simple docstring"""
CustomTokenizer.register_for_auto_class()
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = CustomTokenizer(a_ )
# No fast custom tokenizer
tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token )
__snake_case = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=a_ )
# Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module
self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizer" )
# Fast and slow custom tokenizer
CustomTokenizerFast.register_for_auto_class()
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = os.path.join(a_ , "vocab.txt" )
with open(a_ , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) )
__snake_case = BertTokenizerFast.from_pretrained(a_ )
bert_tokenizer.save_pretrained(a_ )
__snake_case = CustomTokenizerFast.from_pretrained(a_ )
tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token )
__snake_case = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=a_ )
# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizerFast" )
__snake_case = AutoTokenizer.from_pretrained(
f'''{USER}/test-dynamic-tokenizer''' , use_fast=a_ , trust_remote_code=a_ )
# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizer" )
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def A ( self : Optional[int] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("Hello 友達" )
self.assertEqual(trie.data , {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}} )
trie.add("Hello" )
trie.data
self.assertEqual(trie.data , {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}} )
def A ( self : str ):
"""simple docstring"""
__snake_case = Trie()
self.assertEqual(trie.split("[CLS] This is a extra_id_100" ) , ["[CLS] This is a extra_id_100"] )
trie.add("[CLS]" )
trie.add("extra_id_1" )
trie.add("extra_id_100" )
self.assertEqual(trie.split("[CLS] This is a extra_id_100" ) , ["[CLS]", " This is a ", "extra_id_100"] )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("A" )
self.assertEqual(trie.split("ABC" ) , ["A", "BC"] )
self.assertEqual(trie.split("BCA" ) , ["BC", "A"] )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("TOKEN]" )
trie.add("[SPECIAL_TOKEN]" )
self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] )
def A ( self : str ):
"""simple docstring"""
__snake_case = Trie()
trie.add("A" )
trie.add("P" )
trie.add("[SPECIAL_TOKEN]" )
self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] )
def A ( self : Optional[int] ):
"""simple docstring"""
__snake_case = Trie()
trie.add("AB" )
trie.add("B" )
trie.add("C" )
self.assertEqual(trie.split("ABC" ) , ["AB", "C"] )
def A ( self : Tuple ):
"""simple docstring"""
__snake_case = Trie()
trie.add("ABC" )
trie.add("B" )
trie.add("CD" )
self.assertEqual(trie.split("ABCD" ) , ["ABC", "D"] )
def A ( self : Any ):
"""simple docstring"""
__snake_case = Trie()
__snake_case = trie.cut_text("ABC" , [0, 0, 2, 1, 2, 3] )
self.assertEqual(a_ , ["AB", "C"] )
| 69 | 1 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> bool:
return number & 1 == 0
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : int ) -> int:
assert (
isinstance(_UpperCAmelCase , _UpperCAmelCase ) and number_of_steps > 0
), F'''number_of_steps needs to be positive integer, your input {number_of_steps}'''
if number_of_steps == 1:
return 1
__snake_case , __snake_case = 1, 1
for _ in range(number_of_steps - 1 ):
__snake_case , __snake_case = current + previous, current
return current
if __name__ == "__main__":
import doctest
doctest.testmod()
| 69 | 1 |
'''simple docstring'''
import argparse
from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta
from transformers.utils import logging
logging.set_verbosity_info()
def __UpperCAmelCase ( _UpperCAmelCase : Tuple , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Any ) -> Any:
# Initialise PyTorch model
__snake_case = TaConfig.from_json_file(_UpperCAmelCase )
print(F'''Building PyTorch model from configuration: {config}''' )
__snake_case = TaForConditionalGeneration(_UpperCAmelCase )
# Load weights from tf checkpoint
load_tf_weights_in_ta(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
# Save pytorch-model
print(F'''Save PyTorch model to {pytorch_dump_path}''' )
model.save_pretrained(_UpperCAmelCase )
if __name__ == "__main__":
a : List[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(
'''--config_file''',
default=None,
type=str,
required=True,
help=(
'''The config json file corresponding to the pre-trained T5 model. \nThis specifies the model architecture.'''
),
)
parser.add_argument(
'''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
)
a : Any = parser.parse_args()
convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
| 69 |
'''simple docstring'''
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> str:
return " ".join(
"".join(word[::-1] ) if len(_UpperCAmelCase ) > 4 else word for word in sentence.split() )
if __name__ == "__main__":
import doctest
doctest.testmod()
print(reverse_long_words('''Hey wollef sroirraw'''))
| 69 | 1 |
'''simple docstring'''
import copy
from typing import Any, Dict, List, Optional, Union
import numpy as np
import torch
from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging
a : str = logging.get_logger(__name__)
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
__SCREAMING_SNAKE_CASE = ["""input_features""", """is_longer"""]
def __init__( self : Tuple , a_ : Union[str, Any]=64 , a_ : Dict=48_000 , a_ : List[str]=480 , a_ : Dict=10 , a_ : List[str]=1_024 , a_ : int=0.0 , a_ : str=False , a_ : float = 0 , a_ : float = 14_000 , a_ : int = None , a_ : str = "fusion" , a_ : str = "repeatpad" , **a_ : str , ):
"""simple docstring"""
super().__init__(
feature_size=a_ , sampling_rate=a_ , padding_value=a_ , return_attention_mask=a_ , **a_ , )
__snake_case = top_db
__snake_case = truncation
__snake_case = padding
__snake_case = fft_window_size
__snake_case = (fft_window_size >> 1) + 1
__snake_case = hop_length
__snake_case = max_length_s
__snake_case = max_length_s * sampling_rate
__snake_case = sampling_rate
__snake_case = frequency_min
__snake_case = frequency_max
__snake_case = mel_filter_bank(
num_frequency_bins=self.nb_frequency_bins , num_mel_filters=a_ , min_frequency=a_ , max_frequency=a_ , sampling_rate=a_ , norm=a_ , mel_scale="htk" , )
__snake_case = mel_filter_bank(
num_frequency_bins=self.nb_frequency_bins , num_mel_filters=a_ , min_frequency=a_ , max_frequency=a_ , sampling_rate=a_ , norm="slaney" , mel_scale="slaney" , )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = copy.deepcopy(self.__dict__ )
__snake_case = self.__class__.__name__
if "mel_filters" in output:
del output["mel_filters"]
if "mel_filters_slaney" in output:
del output["mel_filters_slaney"]
return output
def A ( self : str , a_ : np.array , a_ : Optional[np.array] = None ):
"""simple docstring"""
__snake_case = spectrogram(
a_ , window_function(self.fft_window_size , "hann" ) , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=a_ , log_mel="dB" , )
return log_mel_spectrogram.T
def A ( self : Tuple , a_ : int , a_ : Tuple , a_ : List[Any] ):
"""simple docstring"""
__snake_case = np.array_split(list(range(0 , total_frames - chunk_frames + 1 ) ) , 3 )
if len(ranges[1] ) == 0:
# if the audio is too short, we just use the first chunk
__snake_case = [0]
if len(ranges[2] ) == 0:
# if the audio is too short, we just use the first chunk
__snake_case = [0]
# randomly choose index for each part
__snake_case = np.random.choice(ranges[0] )
__snake_case = np.random.choice(ranges[1] )
__snake_case = np.random.choice(ranges[2] )
__snake_case = mel[idx_front : idx_front + chunk_frames, :]
__snake_case = mel[idx_middle : idx_middle + chunk_frames, :]
__snake_case = mel[idx_back : idx_back + chunk_frames, :]
__snake_case = torch.tensor(mel[None, None, :] )
__snake_case = torch.nn.functional.interpolate(
a_ , size=[chunk_frames, 64] , mode="bilinear" , align_corners=a_ )
__snake_case = mel_shrink[0][0].numpy()
__snake_case = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 )
return mel_fusion
def A ( self : List[Any] , a_ : np.array , a_ : Tuple , a_ : List[Any] , a_ : str ):
"""simple docstring"""
if waveform.shape[0] > max_length:
if truncation == "rand_trunc":
__snake_case = True
# random crop to max_length (for compatibility) -> this should be handled by self.pad
__snake_case = len(a_ ) - max_length
__snake_case = np.random.randint(0 , overflow + 1 )
__snake_case = waveform[idx : idx + max_length]
__snake_case = self._np_extract_fbank_features(a_ , self.mel_filters_slaney )[None, :]
elif truncation == "fusion":
__snake_case = self._np_extract_fbank_features(a_ , self.mel_filters )
__snake_case = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed
__snake_case = mel.shape[0]
if chunk_frames == total_frames:
# there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length.
# In this case, we just use the whole audio.
__snake_case = np.stack([mel, mel, mel, mel] , axis=0 )
__snake_case = False
else:
__snake_case = self._random_mel_fusion(a_ , a_ , a_ )
__snake_case = True
else:
raise NotImplementedError(f'''data_truncating {truncation} not implemented''' )
else:
__snake_case = False
# only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding
if waveform.shape[0] < max_length:
if padding == "repeat":
__snake_case = int(max_length / len(a_ ) )
__snake_case = np.stack(np.tile(a_ , n_repeat + 1 ) )[:max_length]
if padding == "repeatpad":
__snake_case = int(max_length / len(a_ ) )
__snake_case = np.stack(np.tile(a_ , a_ ) )
__snake_case = np.pad(a_ , (0, max_length - waveform.shape[0]) , mode="constant" , constant_values=0 )
if truncation == "fusion":
__snake_case = self._np_extract_fbank_features(a_ , self.mel_filters )
__snake_case = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 )
else:
__snake_case = self._np_extract_fbank_features(a_ , self.mel_filters_slaney )[None, :]
return input_mel, longer
def __call__( self : Any , a_ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , a_ : str = None , a_ : Optional[str] = None , a_ : Optional[int] = None , a_ : Optional[int] = None , a_ : Optional[Union[str, TensorType]] = None , **a_ : Union[str, Any] , ):
"""simple docstring"""
__snake_case = truncation if truncation is not None else self.truncation
__snake_case = padding if padding else self.padding
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
f'''The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a'''
f''' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input'''
f''' was sampled with {self.sampling_rate} and not {sampling_rate}.''' )
else:
logger.warning(
"It is strongly recommended to pass the `sampling_rate` argument to this function. "
"Failing to do so can result in silent errors that might be hard to debug." )
__snake_case = isinstance(a_ , 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}''' )
__snake_case = is_batched_numpy or (
isinstance(a_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) ))
)
if is_batched:
__snake_case = [np.asarray(a_ , dtype=np.floataa ) for speech in raw_speech]
elif not is_batched and not isinstance(a_ , np.ndarray ):
__snake_case = np.asarray(a_ , dtype=np.floataa )
elif isinstance(a_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ):
__snake_case = raw_speech.astype(np.floataa )
# always return batch
if not is_batched:
__snake_case = [np.asarray(a_ )]
# convert to mel spectrogram, truncate and pad if needed.
__snake_case = [
self._get_input_mel(a_ , max_length if max_length else self.nb_max_samples , a_ , a_ )
for waveform in raw_speech
]
__snake_case = []
__snake_case = []
for mel, longer in padded_inputs:
input_mel.append(a_ )
is_longer.append(a_ )
if truncation == "fusion" and sum(a_ ) == 0:
# if no audio is longer than 10s, then randomly select one audio to be longer
__snake_case = np.random.randint(0 , len(a_ ) )
__snake_case = True
if isinstance(input_mel[0] , a_ ):
__snake_case = [np.asarray(a_ , dtype=np.floataa ) for feature in input_mel]
# is_longer is a list of bool
__snake_case = [[longer] for longer in is_longer]
__snake_case = {"input_features": input_mel, "is_longer": is_longer}
__snake_case = BatchFeature(a_ )
if return_tensors is not None:
__snake_case = input_features.convert_to_tensors(a_ )
return input_features
| 69 |
'''simple docstring'''
import unittest
from transformers import MPNetConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
MPNetForMaskedLM,
MPNetForMultipleChoice,
MPNetForQuestionAnswering,
MPNetForSequenceClassification,
MPNetForTokenClassification,
MPNetModel,
)
class SCREAMING_SNAKE_CASE__ :
def __init__( self : str , a_ : Any , a_ : Union[str, Any]=13 , a_ : Any=7 , a_ : Any=True , a_ : Dict=True , a_ : Union[str, Any]=False , a_ : Tuple=True , a_ : str=99 , a_ : Tuple=64 , a_ : Tuple=5 , a_ : Union[str, Any]=4 , a_ : Dict=64 , a_ : Union[str, Any]="gelu" , a_ : Dict=0.1 , a_ : List[str]=0.1 , a_ : Dict=512 , a_ : Tuple=16 , a_ : str=2 , a_ : Any=0.02 , a_ : List[Any]=3 , a_ : Tuple=4 , a_ : Optional[int]=None , ):
"""simple docstring"""
__snake_case = parent
__snake_case = batch_size
__snake_case = seq_length
__snake_case = is_training
__snake_case = use_input_mask
__snake_case = use_token_type_ids
__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_act
__snake_case = hidden_dropout_prob
__snake_case = attention_probs_dropout_prob
__snake_case = max_position_embeddings
__snake_case = type_vocab_size
__snake_case = type_sequence_label_size
__snake_case = initializer_range
__snake_case = num_labels
__snake_case = num_choices
__snake_case = scope
def A ( self : int ):
"""simple docstring"""
return MPNetConfig.from_pretrained("microsoft/mpnet-base" )
def A ( self : str ):
"""simple docstring"""
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__snake_case = None
if self.use_input_mask:
__snake_case = random_attention_mask([self.batch_size, self.seq_length] )
__snake_case = None
__snake_case = None
__snake_case = None
if self.use_labels:
__snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__snake_case = ids_tensor([self.batch_size] , self.num_choices )
__snake_case = self.get_config()
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
def A ( self : List[str] ):
"""simple docstring"""
return MPNetConfig(
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 , initializer_range=self.initializer_range , )
def A ( self : Tuple , a_ : int , a_ : str , a_ : Optional[int] , a_ : List[Any] , a_ : str , a_ : Optional[Any] ):
"""simple docstring"""
__snake_case = MPNetModel(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , a_ )
__snake_case = model(a_ )
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 A ( self : Any , a_ : int , a_ : Tuple , a_ : str , a_ : int , a_ : str , a_ : List[Any] ):
"""simple docstring"""
__snake_case = MPNetForQuestionAnswering(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(
a_ , attention_mask=a_ , start_positions=a_ , end_positions=a_ , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def A ( self : Any , a_ : Any , a_ : int , a_ : Union[str, Any] , a_ : Dict , a_ : Optional[Any] , a_ : Any ):
"""simple docstring"""
__snake_case = self.num_labels
__snake_case = MPNetForSequenceClassification(a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def A ( self : Optional[Any] , a_ : Any , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : List[Any] , a_ : List[Any] ):
"""simple docstring"""
__snake_case = self.num_choices
__snake_case = MPNetForMultipleChoice(config=a_ )
model.to(a_ )
model.eval()
__snake_case = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__snake_case = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__snake_case = model(
a_ , attention_mask=a_ , labels=a_ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def A ( self : Dict , a_ : List[str] , a_ : str , a_ : Union[str, Any] , a_ : str , a_ : Optional[int] , a_ : Optional[Any] ):
"""simple docstring"""
__snake_case = self.num_labels
__snake_case = MPNetForTokenClassification(config=a_ )
model.to(a_ )
model.eval()
__snake_case = model(a_ , attention_mask=a_ , labels=a_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.prepare_config_and_inputs()
((__snake_case) , (__snake_case) , (__snake_case) , (__snake_case) , (__snake_case) , (__snake_case)) = config_and_inputs
__snake_case = {"input_ids": input_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE = (
(
MPNetForMaskedLM,
MPNetForMultipleChoice,
MPNetForQuestionAnswering,
MPNetForSequenceClassification,
MPNetForTokenClassification,
MPNetModel,
)
if is_torch_available()
else ()
)
__SCREAMING_SNAKE_CASE = (
{
"""feature-extraction""": MPNetModel,
"""fill-mask""": MPNetForMaskedLM,
"""question-answering""": MPNetForQuestionAnswering,
"""text-classification""": MPNetForSequenceClassification,
"""token-classification""": MPNetForTokenClassification,
"""zero-shot""": MPNetForSequenceClassification,
}
if is_torch_available()
else {}
)
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = True
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = MPNetModelTester(self )
__snake_case = ConfigTester(self , config_class=a_ , hidden_size=37 )
def A ( self : List[Any] ):
"""simple docstring"""
self.config_tester.run_common_tests()
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_model(*a_ )
def A ( self : Dict ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_sequence_classification(*a_ )
def A ( self : List[Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_multiple_choice(*a_ )
def A ( self : int ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_token_classification(*a_ )
def A ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_question_answering(*a_ )
@require_torch
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
@slow
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = MPNetModel.from_pretrained("microsoft/mpnet-base" )
__snake_case = torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] )
__snake_case = model(a_ )[0]
__snake_case = torch.Size((1, 11, 768) )
self.assertEqual(output.shape , a_ )
__snake_case = torch.tensor(
[[[-0.0550, 0.1943, -0.0740], [-0.0562, 0.2211, -0.0579], [-0.0437, 0.3337, -0.0641]]] )
# compare the actual values for a slice.
self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) )
| 69 | 1 |
'''simple docstring'''
from typing import Dict
from .base import GenericTensor, Pipeline
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def A ( self : Dict , a_ : str=None , a_ : Any=None , a_ : Optional[Any]=None , **a_ : str ):
"""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 A ( self : str , a_ : Optional[int] , **a_ : Tuple ):
"""simple docstring"""
__snake_case = self.framework
__snake_case = self.tokenizer(a_ , return_tensors=a_ , **a_ )
return model_inputs
def A ( self : int , a_ : Any ):
"""simple docstring"""
__snake_case = self.model(**a_ )
return model_outputs
def A ( self : Dict , a_ : Optional[Any] , a_ : Tuple=False ):
"""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 : Union[str, Any] , *a_ : Union[str, Any] , **a_ : List[Any] ):
"""simple docstring"""
return super().__call__(*a_ , **a_ )
| 69 |
'''simple docstring'''
# Logistic Regression from scratch
# In[62]:
# In[63]:
# importing all the required libraries
import numpy as np
from matplotlib import pyplot as plt
from sklearn import datasets
def __UpperCAmelCase ( _UpperCAmelCase : str ) -> Optional[int]:
return 1 / (1 + np.exp(-z ))
def __UpperCAmelCase ( _UpperCAmelCase : Tuple , _UpperCAmelCase : Dict ) -> List[str]:
return (-y * np.log(_UpperCAmelCase ) - (1 - y) * np.log(1 - h )).mean()
def __UpperCAmelCase ( _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : List[Any] ) -> Optional[Any]:
__snake_case = np.dot(_UpperCAmelCase , _UpperCAmelCase )
return np.sum(y * scores - np.log(1 + np.exp(_UpperCAmelCase ) ) )
def __UpperCAmelCase ( _UpperCAmelCase : List[Any] , _UpperCAmelCase : str , _UpperCAmelCase : Dict , _UpperCAmelCase : List[str]=7_00_00 ) -> Union[str, Any]:
__snake_case = np.zeros(x.shape[1] )
for iterations in range(_UpperCAmelCase ):
__snake_case = np.dot(_UpperCAmelCase , _UpperCAmelCase )
__snake_case = sigmoid_function(_UpperCAmelCase )
__snake_case = np.dot(x.T , h - y ) / y.size
__snake_case = theta - alpha * gradient # updating the weights
__snake_case = np.dot(_UpperCAmelCase , _UpperCAmelCase )
__snake_case = sigmoid_function(_UpperCAmelCase )
__snake_case = cost_function(_UpperCAmelCase , _UpperCAmelCase )
if iterations % 1_00 == 0:
print(F'''loss: {j} \t''' ) # printing the loss after every 100 iterations
return theta
# In[68]:
if __name__ == "__main__":
a : int = datasets.load_iris()
a : int = iris.data[:, :2]
a : Optional[Any] = (iris.target != 0) * 1
a : Tuple = 0.1
a : List[str] = logistic_reg(alpha, x, y, max_iterations=70_000)
print('''theta: ''', theta) # printing the theta i.e our weights vector
def __UpperCAmelCase ( _UpperCAmelCase : Optional[int] ) -> Union[str, Any]:
return sigmoid_function(
np.dot(_UpperCAmelCase , _UpperCAmelCase ) ) # predicting the value of probability from the logistic regression algorithm
plt.figure(figsize=(10, 6))
plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color='''b''', label='''0''')
plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color='''r''', label='''1''')
((a) , (a)) : Any = (x[:, 0].min(), x[:, 0].max())
((a) , (a)) : Any = (x[:, 1].min(), x[:, 1].max())
((a) , (a)) : Any = np.meshgrid(np.linspace(xa_min, xa_max), np.linspace(xa_min, xa_max))
a : Optional[Any] = np.c_[xxa.ravel(), xxa.ravel()]
a : List[Any] = predict_prob(grid).reshape(xxa.shape)
plt.contour(xxa, xxa, probs, [0.5], linewidths=1, colors='''black''')
plt.legend()
plt.show()
| 69 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.