code
stringlengths 82
53.2k
| code_codestyle
int64 0
721
| style_context
stringlengths 91
41.9k
| style_context_codestyle
int64 0
699
| label
int64 0
1
|
---|---|---|---|---|
import argparse
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to properly calculate the metrics on the
# validation dataset when in a distributed system, and builds off the
# `nlp_example.py` script.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
# - single CPU or single GPU
# - multi GPUS (using PyTorch distributed mode)
# - (multi) TPUs
# - fp16 (mixed-precision) or fp32 (normal precision)
#
# To help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################
__SCREAMING_SNAKE_CASE : Any = 16
__SCREAMING_SNAKE_CASE : Dict = 32
def UpperCAmelCase__ ( __magic_name__ : Accelerator , __magic_name__ : int = 16 ):
'''simple docstring'''
lowerCAmelCase : Dict = AutoTokenizer.from_pretrained('''bert-base-cased''' )
lowerCAmelCase : int = load_dataset('''glue''' , '''mrpc''' )
def tokenize_function(__magic_name__ : List[str] ):
# max_length=None => use the model max length (it's actually the default)
lowerCAmelCase : Optional[Any] = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=__magic_name__ , max_length=__magic_name__ )
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
lowerCAmelCase : Dict = datasets.map(
__magic_name__ , batched=__magic_name__ , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
lowerCAmelCase : Optional[Any] = tokenized_datasets.rename_column('''label''' , '''labels''' )
def collate_fn(__magic_name__ : Dict ):
# On TPU it's best to pad everything to the same length or training will be very slow.
lowerCAmelCase : List[str] = 1_28 if accelerator.distributed_type == DistributedType.TPU else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
lowerCAmelCase : Tuple = 16
elif accelerator.mixed_precision != "no":
lowerCAmelCase : Union[str, Any] = 8
else:
lowerCAmelCase : List[Any] = None
return tokenizer.pad(
__magic_name__ , padding='''longest''' , max_length=__magic_name__ , pad_to_multiple_of=__magic_name__ , return_tensors='''pt''' , )
# Instantiate dataloaders.
lowerCAmelCase : str = DataLoader(
tokenized_datasets['''train'''] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ )
lowerCAmelCase : str = DataLoader(
tokenized_datasets['''validation'''] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ )
return train_dataloader, eval_dataloader
# For testing only
if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1":
from accelerate.test_utils.training import mocked_dataloaders
__SCREAMING_SNAKE_CASE : Tuple = mocked_dataloaders # noqa: F811
def UpperCAmelCase__ ( __magic_name__ : Dict , __magic_name__ : Dict ):
'''simple docstring'''
if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , __magic_name__ ) == "1":
lowerCAmelCase : Optional[int] = 2
# Initialize accelerator
lowerCAmelCase : Optional[int] = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
lowerCAmelCase : List[str] = config['''lr''']
lowerCAmelCase : Any = int(config['''num_epochs'''] )
lowerCAmelCase : int = int(config['''seed'''] )
lowerCAmelCase : str = int(config['''batch_size'''] )
lowerCAmelCase : Optional[int] = evaluate.load('''glue''' , '''mrpc''' )
# If the batch size is too big we use gradient accumulation
lowerCAmelCase : Tuple = 1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
lowerCAmelCase : Any = batch_size // MAX_GPU_BATCH_SIZE
lowerCAmelCase : Tuple = MAX_GPU_BATCH_SIZE
set_seed(__magic_name__ )
lowerCAmelCase , lowerCAmelCase : Dict = get_dataloaders(__magic_name__ , __magic_name__ )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
lowerCAmelCase : Union[str, Any] = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=__magic_name__ )
# 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).
lowerCAmelCase : List[Any] = model.to(accelerator.device )
# Instantiate optimizer
lowerCAmelCase : str = AdamW(params=model.parameters() , lr=__magic_name__ )
# Instantiate scheduler
lowerCAmelCase : Optional[Any] = get_linear_schedule_with_warmup(
optimizer=__magic_name__ , num_warmup_steps=1_00 , num_training_steps=(len(__magic_name__ ) * num_epochs) // gradient_accumulation_steps , )
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase : Any = accelerator.prepare(
__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ )
# Now we train the model
for epoch in range(__magic_name__ ):
model.train()
for step, batch in enumerate(__magic_name__ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
lowerCAmelCase : Any = model(**__magic_name__ )
lowerCAmelCase : Union[str, Any] = outputs.loss
lowerCAmelCase : Dict = loss / gradient_accumulation_steps
accelerator.backward(__magic_name__ )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
lowerCAmelCase : str = 0
for step, batch in enumerate(__magic_name__ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
lowerCAmelCase : List[str] = model(**__magic_name__ )
lowerCAmelCase : List[Any] = outputs.logits.argmax(dim=-1 )
lowerCAmelCase , lowerCAmelCase : List[str] = accelerator.gather((predictions, batch['''labels''']) )
# New Code #
# First we check if it's a distributed system
if accelerator.use_distributed:
# Then see if we're on the last batch of our eval dataloader
if step == len(__magic_name__ ) - 1:
# Last batch needs to be truncated on distributed systems as it contains additional samples
lowerCAmelCase : Optional[int] = predictions[: len(eval_dataloader.dataset ) - samples_seen]
lowerCAmelCase : str = references[: len(eval_dataloader.dataset ) - samples_seen]
else:
# Otherwise we add the number of samples seen
samples_seen += references.shape[0]
# All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`:
# accelerator.gather_for_metrics((predictions, batch["labels"]))
metric.add_batch(
predictions=__magic_name__ , references=__magic_name__ , )
lowerCAmelCase : Union[str, Any] = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f'''epoch {epoch}:''' , __magic_name__ )
def UpperCAmelCase__ ( ):
'''simple docstring'''
lowerCAmelCase : Dict = argparse.ArgumentParser(description='''Simple example of training script.''' )
parser.add_argument(
'''--mixed_precision''' , type=__magic_name__ , default=__magic_name__ , 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.''' )
lowerCAmelCase : List[Any] = parser.parse_args()
lowerCAmelCase : List[str] = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16}
training_function(__magic_name__ , __magic_name__ )
if __name__ == "__main__":
main()
| 348 |
from math import factorial, pi
def UpperCAmelCase__ ( __magic_name__ : float , __magic_name__ : int = 30 ):
'''simple docstring'''
if not isinstance(__magic_name__ , (int, float) ):
raise ValueError('''maclaurin_sin() requires either an int or float for theta''' )
if not isinstance(__magic_name__ , __magic_name__ ) or accuracy <= 0:
raise ValueError('''maclaurin_sin() requires a positive int for accuracy''' )
lowerCAmelCase : Optional[int] = float(__magic_name__ )
lowerCAmelCase : Any = theta // (2 * pi)
theta -= 2 * div * pi
return sum(
(-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(__magic_name__ ) )
def UpperCAmelCase__ ( __magic_name__ : float , __magic_name__ : int = 30 ):
'''simple docstring'''
if not isinstance(__magic_name__ , (int, float) ):
raise ValueError('''maclaurin_cos() requires either an int or float for theta''' )
if not isinstance(__magic_name__ , __magic_name__ ) or accuracy <= 0:
raise ValueError('''maclaurin_cos() requires a positive int for accuracy''' )
lowerCAmelCase : Dict = float(__magic_name__ )
lowerCAmelCase : Union[str, Any] = theta // (2 * pi)
theta -= 2 * div * pi
return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(__magic_name__ ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
print(maclaurin_sin(10))
print(maclaurin_sin(-10))
print(maclaurin_sin(10, 15))
print(maclaurin_sin(-10, 15))
print(maclaurin_cos(5))
print(maclaurin_cos(-5))
print(maclaurin_cos(10, 15))
print(maclaurin_cos(-10, 15))
| 348 | 1 |
def A ( SCREAMING_SNAKE_CASE = 600851475143 ):
"""simple docstring"""
try:
UpperCAmelCase__ :int = int(SCREAMING_SNAKE_CASE )
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.' )
UpperCAmelCase__ :Dict = 1
UpperCAmelCase__ :Any = 2
while i * i <= n:
while n % i == 0:
UpperCAmelCase__ :List[Any] = i
n //= i
i += 1
if n > 1:
UpperCAmelCase__ :str = n
return int(SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
print(f"""{solution() = }""")
| 433 |
import argparse
import math
import os
from copy import deepcopy
import torch
from audio_diffusion.models import DiffusionAttnUnetaD
from diffusion import sampling
from torch import nn
from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel
__snake_case : Dict = {
'gwf-440k': {
'url': 'https://model-server.zqevans2.workers.dev/gwf-440k.ckpt',
'sample_rate': 48_000,
'sample_size': 65_536,
},
'jmann-small-190k': {
'url': 'https://model-server.zqevans2.workers.dev/jmann-small-190k.ckpt',
'sample_rate': 48_000,
'sample_size': 65_536,
},
'jmann-large-580k': {
'url': 'https://model-server.zqevans2.workers.dev/jmann-large-580k.ckpt',
'sample_rate': 48_000,
'sample_size': 131_072,
},
'maestro-uncond-150k': {
'url': 'https://model-server.zqevans2.workers.dev/maestro-uncond-150k.ckpt',
'sample_rate': 16_000,
'sample_size': 65_536,
},
'unlocked-uncond-250k': {
'url': 'https://model-server.zqevans2.workers.dev/unlocked-uncond-250k.ckpt',
'sample_rate': 16_000,
'sample_size': 65_536,
},
'honk-140k': {
'url': 'https://model-server.zqevans2.workers.dev/honk-140k.ckpt',
'sample_rate': 16_000,
'sample_size': 65_536,
},
}
def A ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
"""simple docstring"""
return torch.atana(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) / math.pi * 2
def A ( SCREAMING_SNAKE_CASE ):
"""simple docstring"""
UpperCAmelCase__ :List[str] = torch.sin(t * math.pi / 2 ) ** 2
UpperCAmelCase__ :int = (1 - sigma**2) ** 0.5
return alpha_sigma_to_t(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
class UpperCamelCase__ ( UpperCAmelCase__):
'''simple docstring'''
pass
class UpperCamelCase__ ( nn.Module):
'''simple docstring'''
def __init__( self , A ) ->Union[str, Any]:
super().__init__()
UpperCAmelCase__ :Dict = DiffusionAttnUnetaD(A , n_attn_layers=4 )
UpperCAmelCase__ :Optional[Any] = deepcopy(self.diffusion )
UpperCAmelCase__ :str = torch.quasirandom.SobolEngine(1 , scramble=A )
def A ( SCREAMING_SNAKE_CASE ):
"""simple docstring"""
UpperCAmelCase__ :Dict = MODELS_MAP[model_name]['url']
os.system(f"""wget {url} ./""" )
return f"""./{model_name}.ckpt"""
__snake_case : Union[str, Any] = {
'1': 'resnets.0',
'2': 'attentions.0',
'3': 'resnets.1',
'4': 'attentions.1',
'5': 'resnets.2',
'6': 'attentions.2',
}
__snake_case : Tuple = {
'8': 'resnets.0',
'9': 'attentions.0',
'10': 'resnets.1',
'11': 'attentions.1',
'12': 'resnets.2',
'13': 'attentions.2',
}
__snake_case : Optional[int] = {
'1': 'resnets.0',
'2': 'attentions.0',
'3': 'resnets.1',
'4': 'attentions.1',
'5': 'resnets.2',
'6': 'attentions.2',
'8': 'resnets.3',
'9': 'attentions.3',
'10': 'resnets.4',
'11': 'attentions.4',
'12': 'resnets.5',
'13': 'attentions.5',
}
__snake_case : str = {
'0': 'resnets.0',
'1': 'resnets.1',
'2': 'resnets.2',
'4': 'resnets.0',
'5': 'resnets.1',
'6': 'resnets.2',
}
__snake_case : Optional[int] = {
'skip': 'conv_skip',
'main.0': 'conv_1',
'main.1': 'group_norm_1',
'main.3': 'conv_2',
'main.4': 'group_norm_2',
}
__snake_case : Union[str, Any] = {
'norm': 'group_norm',
'qkv_proj': ['query', 'key', 'value'],
'out_proj': ['proj_attn'],
}
def A ( SCREAMING_SNAKE_CASE ):
"""simple docstring"""
if name.startswith('skip' ):
return name.replace('skip' , RES_CONV_MAP['skip'] )
# name has to be of format main.{digit}
if not name.startswith('main.' ):
raise ValueError(f"""ResConvBlock error with {name}""" )
return name.replace(name[:6] , RES_CONV_MAP[name[:6]] )
def A ( SCREAMING_SNAKE_CASE ):
"""simple docstring"""
for key, value in ATTN_MAP.items():
if name.startswith(SCREAMING_SNAKE_CASE ) and not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
return name.replace(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
elif name.startswith(SCREAMING_SNAKE_CASE ):
return [name.replace(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for v in value]
raise ValueError(f"""Attn error with {name}""" )
def A ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 ):
"""simple docstring"""
UpperCAmelCase__ :Any = input_string
if string.split('.' )[0] == "timestep_embed":
return string.replace('timestep_embed' , 'time_proj' )
UpperCAmelCase__ :List[Any] = 0
if string.startswith('net.3.' ):
depth += 1
UpperCAmelCase__ :int = string[6:]
elif string.startswith('net.' ):
UpperCAmelCase__ :Union[str, Any] = string[4:]
while string.startswith('main.7.' ):
depth += 1
UpperCAmelCase__ :List[str] = string[7:]
if string.startswith('main.' ):
UpperCAmelCase__ :Tuple = string[5:]
# mid block
if string[:2].isdigit():
UpperCAmelCase__ :int = string[:2]
UpperCAmelCase__ :List[Any] = string[2:]
else:
UpperCAmelCase__ :Dict = string[0]
UpperCAmelCase__ :Union[str, Any] = string[1:]
if depth == max_depth:
UpperCAmelCase__ :Dict = MID_NUM_TO_LAYER[layer_num]
UpperCAmelCase__ :int = 'mid_block'
elif depth > 0 and int(SCREAMING_SNAKE_CASE ) < 7:
UpperCAmelCase__ :List[Any] = DOWN_NUM_TO_LAYER[layer_num]
UpperCAmelCase__ :Any = f"""down_blocks.{depth}"""
elif depth > 0 and int(SCREAMING_SNAKE_CASE ) > 7:
UpperCAmelCase__ :Union[str, Any] = UP_NUM_TO_LAYER[layer_num]
UpperCAmelCase__ :Union[str, Any] = f"""up_blocks.{max_depth - depth - 1}"""
elif depth == 0:
UpperCAmelCase__ :List[str] = DEPTH_0_TO_LAYER[layer_num]
UpperCAmelCase__ :List[str] = f"""up_blocks.{max_depth - 1}""" if int(SCREAMING_SNAKE_CASE ) > 3 else 'down_blocks.0'
if not string_left.startswith('.' ):
raise ValueError(f"""Naming error with {input_string} and string_left: {string_left}.""" )
UpperCAmelCase__ :int = string_left[1:]
if "resnets" in new_layer:
UpperCAmelCase__ :Optional[Any] = convert_resconv_naming(SCREAMING_SNAKE_CASE )
elif "attentions" in new_layer:
UpperCAmelCase__ :Any = convert_attn_naming(SCREAMING_SNAKE_CASE )
UpperCAmelCase__ :Any = new_string_left
if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
UpperCAmelCase__ :Tuple = prefix + '.' + new_layer + '.' + string_left
else:
UpperCAmelCase__ :int = [prefix + '.' + new_layer + '.' + s for s in string_left]
return new_string
def A ( SCREAMING_SNAKE_CASE ):
"""simple docstring"""
UpperCAmelCase__ :str = {}
for k, v in state_dict.items():
if k.endswith('kernel' ):
# up- and downsample layers, don't have trainable weights
continue
UpperCAmelCase__ :Tuple = rename(SCREAMING_SNAKE_CASE )
# check if we need to transform from Conv => Linear for attention
if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
UpperCAmelCase__ :Tuple = transform_conv_attns(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
else:
UpperCAmelCase__ :Union[str, Any] = v
return new_state_dict
def A ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
"""simple docstring"""
if len(SCREAMING_SNAKE_CASE ) == 1:
if len(v.shape ) == 3:
# weight
UpperCAmelCase__ :List[str] = v[:, :, 0]
else:
# bias
UpperCAmelCase__ :Union[str, Any] = v
else:
# qkv matrices
UpperCAmelCase__ :Optional[int] = v.shape[0]
UpperCAmelCase__ :str = trippled_shape // 3
for i in range(3 ):
if len(v.shape ) == 3:
UpperCAmelCase__ :Optional[int] = v[i * single_shape : (i + 1) * single_shape, :, 0]
else:
UpperCAmelCase__ :Optional[Any] = v[i * single_shape : (i + 1) * single_shape]
return new_state_dict
def A ( SCREAMING_SNAKE_CASE ):
"""simple docstring"""
UpperCAmelCase__ :Union[str, Any] = torch.device('cuda' if torch.cuda.is_available() else 'cpu' )
UpperCAmelCase__ :List[Any] = args.model_path.split('/' )[-1].split('.' )[0]
if not os.path.isfile(args.model_path ):
assert (
model_name == args.model_path
), f"""Make sure to provide one of the official model names {MODELS_MAP.keys()}"""
UpperCAmelCase__ :List[str] = download(SCREAMING_SNAKE_CASE )
UpperCAmelCase__ :Optional[int] = MODELS_MAP[model_name]['sample_rate']
UpperCAmelCase__ :Tuple = MODELS_MAP[model_name]['sample_size']
UpperCAmelCase__ :Optional[Any] = Object()
UpperCAmelCase__ :int = sample_size
UpperCAmelCase__ :Any = sample_rate
UpperCAmelCase__ :List[str] = 0
UpperCAmelCase__ :Union[str, Any] = UNetaDModel(sample_size=SCREAMING_SNAKE_CASE , sample_rate=SCREAMING_SNAKE_CASE )
UpperCAmelCase__ :Dict = diffusers_model.state_dict()
UpperCAmelCase__ :Dict = DiffusionUncond(SCREAMING_SNAKE_CASE )
orig_model.load_state_dict(torch.load(args.model_path , map_location=SCREAMING_SNAKE_CASE )['state_dict'] )
UpperCAmelCase__ :Dict = orig_model.diffusion_ema.eval()
UpperCAmelCase__ :Optional[Any] = orig_model.state_dict()
UpperCAmelCase__ :Tuple = rename_orig_weights(SCREAMING_SNAKE_CASE )
UpperCAmelCase__ :Dict = set(renamed_state_dict.keys() ) - set(diffusers_state_dict.keys() )
UpperCAmelCase__ :Dict = set(diffusers_state_dict.keys() ) - set(renamed_state_dict.keys() )
assert len(SCREAMING_SNAKE_CASE ) == 0, f"""Problem with {renamed_minus_diffusers}"""
assert all(k.endswith('kernel' ) for k in list(SCREAMING_SNAKE_CASE ) ), f"""Problem with {diffusers_minus_renamed}"""
for key, value in renamed_state_dict.items():
assert (
diffusers_state_dict[key].squeeze().shape == value.squeeze().shape
), f"""Shape for {key} doesn't match. Diffusers: {diffusers_state_dict[key].shape} vs. {value.shape}"""
if key == "time_proj.weight":
UpperCAmelCase__ :List[Any] = value.squeeze()
UpperCAmelCase__ :List[Any] = value
diffusers_model.load_state_dict(SCREAMING_SNAKE_CASE )
UpperCAmelCase__ :Optional[int] = 100
UpperCAmelCase__ :Any = 33
UpperCAmelCase__ :int = IPNDMScheduler(num_train_timesteps=SCREAMING_SNAKE_CASE )
UpperCAmelCase__ :List[str] = torch.manual_seed(SCREAMING_SNAKE_CASE )
UpperCAmelCase__ :int = torch.randn([1, 2, config.sample_size] , generator=SCREAMING_SNAKE_CASE ).to(SCREAMING_SNAKE_CASE )
UpperCAmelCase__ :Optional[int] = torch.linspace(1 , 0 , steps + 1 , device=SCREAMING_SNAKE_CASE )[:-1]
UpperCAmelCase__ :List[Any] = get_crash_schedule(SCREAMING_SNAKE_CASE )
UpperCAmelCase__ :Tuple = DanceDiffusionPipeline(unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE )
UpperCAmelCase__ :Optional[Any] = torch.manual_seed(33 )
UpperCAmelCase__ :List[str] = pipe(num_inference_steps=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE ).audios
UpperCAmelCase__ :Any = sampling.iplms_sample(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , {} )
UpperCAmelCase__ :List[Any] = generated.clamp(-1 , 1 )
UpperCAmelCase__ :int = (generated - audio).abs().sum()
UpperCAmelCase__ :Optional[Any] = (generated - audio).abs().max()
if args.save:
pipe.save_pretrained(args.checkpoint_path )
print('Diff sum' , SCREAMING_SNAKE_CASE )
print('Diff max' , SCREAMING_SNAKE_CASE )
assert diff_max < 1E-3, f"""Diff max: {diff_max} is too much :-/"""
print(f"""Conversion for {model_name} successful!""" )
if __name__ == "__main__":
__snake_case : Any = argparse.ArgumentParser()
parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.')
parser.add_argument(
'--save', default=True, type=bool, required=False, help='Whether to save the converted model or not.'
)
parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.')
__snake_case : Union[str, Any] = parser.parse_args()
main(args)
| 433 | 1 |
"""simple docstring"""
import argparse
import os
import re
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_dummies.py
__UpperCamelCase = '''src/diffusers'''
# Matches is_xxx_available()
__UpperCamelCase = re.compile(R'''is\_([a-z_]*)_available\(\)''')
# Matches from xxx import bla
__UpperCamelCase = re.compile(R'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''')
__UpperCamelCase = '''
{0} = None
'''
__UpperCamelCase = '''
class {0}(metaclass=DummyObject):
_backends = {1}
def __init__(self, *args, **kwargs):
requires_backends(self, {1})
@classmethod
def from_config(cls, *args, **kwargs):
requires_backends(cls, {1})
@classmethod
def from_pretrained(cls, *args, **kwargs):
requires_backends(cls, {1})
'''
__UpperCamelCase = '''
def {0}(*args, **kwargs):
requires_backends({0}, {1})
'''
def lowercase (SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Union[str, Any]:
SCREAMING_SNAKE_CASE = _re_backend.findall(SCREAMING_SNAKE_CASE_ )
if len(SCREAMING_SNAKE_CASE_ ) == 0:
return None
return "_and_".join(SCREAMING_SNAKE_CASE_ )
def lowercase () -> Tuple:
with open(os.path.join(SCREAMING_SNAKE_CASE_ , '__init__.py' ) , 'r' , encoding='utf-8' , newline='\n' ) as f:
SCREAMING_SNAKE_CASE = f.readlines()
# Get to the point we do the actual imports for type checking
SCREAMING_SNAKE_CASE = 0
SCREAMING_SNAKE_CASE = {}
# Go through the end of the file
while line_index < len(SCREAMING_SNAKE_CASE_ ):
# If the line contains is_backend_available, we grab all objects associated with the `else` block
SCREAMING_SNAKE_CASE = find_backend(lines[line_index] )
if backend is not None:
while not lines[line_index].startswith('else:' ):
line_index += 1
line_index += 1
SCREAMING_SNAKE_CASE = []
# Until we unindent, add backend objects to the list
while line_index < len(SCREAMING_SNAKE_CASE_ ) and len(lines[line_index] ) > 1:
SCREAMING_SNAKE_CASE = lines[line_index]
SCREAMING_SNAKE_CASE = _re_single_line_import.search(SCREAMING_SNAKE_CASE_ )
if single_line_import_search is not None:
objects.extend(single_line_import_search.groups()[0].split(', ' ) )
elif line.startswith(' ' * 8 ):
objects.append(line[8:-2] )
line_index += 1
if len(SCREAMING_SNAKE_CASE_ ) > 0:
SCREAMING_SNAKE_CASE = objects
else:
line_index += 1
return backend_specific_objects
def lowercase (SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> int:
if name.isupper():
return DUMMY_CONSTANT.format(SCREAMING_SNAKE_CASE_ )
elif name.islower():
return DUMMY_FUNCTION.format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
else:
return DUMMY_CLASS.format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
def lowercase (SCREAMING_SNAKE_CASE_ : Union[str, Any]=None ) -> Tuple:
if backend_specific_objects is None:
SCREAMING_SNAKE_CASE = read_init()
# For special correspondence backend to module name as used in the function requires_modulename
SCREAMING_SNAKE_CASE = {}
for backend, objects in backend_specific_objects.items():
SCREAMING_SNAKE_CASE = '[' + ', '.join(F'"{b}"' for b in backend.split('_and_' ) ) + ']'
SCREAMING_SNAKE_CASE = '# This file is autogenerated by the command `make fix-copies`, do not edit.\n'
dummy_file += "from ..utils import DummyObject, requires_backends\n\n"
dummy_file += "\n".join([create_dummy_object(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for o in objects] )
SCREAMING_SNAKE_CASE = dummy_file
return dummy_files
def lowercase (SCREAMING_SNAKE_CASE_ : Any=False ) -> List[Any]:
SCREAMING_SNAKE_CASE = create_dummy_files()
# For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py
SCREAMING_SNAKE_CASE = {'torch': 'pt'}
# Locate actual dummy modules and read their content.
SCREAMING_SNAKE_CASE = os.path.join(SCREAMING_SNAKE_CASE_ , 'utils' )
SCREAMING_SNAKE_CASE = {
backend: os.path.join(SCREAMING_SNAKE_CASE_ , F'dummy_{short_names.get(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )}_objects.py' )
for backend in dummy_files.keys()
}
SCREAMING_SNAKE_CASE = {}
for backend, file_path in dummy_file_paths.items():
if os.path.isfile(SCREAMING_SNAKE_CASE_ ):
with open(SCREAMING_SNAKE_CASE_ , 'r' , encoding='utf-8' , newline='\n' ) as f:
SCREAMING_SNAKE_CASE = f.read()
else:
SCREAMING_SNAKE_CASE = ''
for backend in dummy_files.keys():
if dummy_files[backend] != actual_dummies[backend]:
if overwrite:
print(
F'Updating diffusers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )}_objects.py as the main '
'__init__ has new objects.' )
with open(dummy_file_paths[backend] , 'w' , encoding='utf-8' , newline='\n' ) as f:
f.write(dummy_files[backend] )
else:
raise ValueError(
'The main __init__ has objects that are not present in '
F'diffusers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )}_objects.py. Run `make fix-copies` '
'to fix this.' )
if __name__ == "__main__":
__UpperCamelCase = argparse.ArgumentParser()
parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''')
__UpperCamelCase = parser.parse_args()
check_dummies(args.fix_and_overwrite)
| 247 |
"""simple docstring"""
import itertools
import json
import os
import unittest
from transformers import AddedToken, LongformerTokenizer, LongformerTokenizerFast
from transformers.models.longformer.tokenization_longformer import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class lowerCAmelCase ( lowerCamelCase_ , unittest.TestCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ : Optional[Any] = LongformerTokenizer
SCREAMING_SNAKE_CASE_ : List[str] = True
SCREAMING_SNAKE_CASE_ : List[str] = LongformerTokenizerFast
SCREAMING_SNAKE_CASE_ : Optional[int] = True
def __A ( self ) -> Optional[Any]:
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
SCREAMING_SNAKE_CASE = [
'l',
'o',
'w',
'e',
'r',
's',
't',
'i',
'd',
'n',
'\u0120',
'\u0120l',
'\u0120n',
'\u0120lo',
'\u0120low',
'er',
'\u0120lowest',
'\u0120newer',
'\u0120wider',
'<unk>',
]
SCREAMING_SNAKE_CASE = dict(zip(lowerCAmelCase__ , range(len(lowerCAmelCase__ ) ) ) )
SCREAMING_SNAKE_CASE = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', '']
SCREAMING_SNAKE_CASE = {'unk_token': '<unk>'}
SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] )
SCREAMING_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(lowerCAmelCase__ ) + '\n' )
with open(self.merges_file , 'w' , encoding='utf-8' ) as fp:
fp.write('\n'.join(lowerCAmelCase__ ) )
def __A ( self , **lowerCAmelCase__ ) -> str:
kwargs.update(self.special_tokens_map )
return self.tokenizer_class.from_pretrained(self.tmpdirname , **lowerCAmelCase__ )
def __A ( self , **lowerCAmelCase__ ) -> List[Any]:
kwargs.update(self.special_tokens_map )
return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **lowerCAmelCase__ )
def __A ( self , lowerCAmelCase__ ) -> Dict:
SCREAMING_SNAKE_CASE = 'lower newer'
SCREAMING_SNAKE_CASE = 'lower newer'
return input_text, output_text
def __A ( self ) -> str:
SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map )
SCREAMING_SNAKE_CASE = 'lower newer'
SCREAMING_SNAKE_CASE = ['l', 'o', 'w', 'er', '\u0120', 'n', 'e', 'w', 'er']
SCREAMING_SNAKE_CASE = tokenizer.tokenize(lowerCAmelCase__ ) # , add_prefix_space=True)
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokens + [tokenizer.unk_token]
SCREAMING_SNAKE_CASE = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase__ ) , lowerCAmelCase__ )
def __A ( self ) -> Tuple:
SCREAMING_SNAKE_CASE = self.get_tokenizer()
self.assertListEqual(tokenizer.encode('Hello world!' , add_special_tokens=lowerCAmelCase__ ) , [0, 31_414, 232, 328, 2] )
self.assertListEqual(
tokenizer.encode('Hello world! cécé herlolip 418' , add_special_tokens=lowerCAmelCase__ ) , [0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2] , )
@slow
def __A ( self ) -> List[Any]:
SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained('allenai/longformer-base-4096' )
SCREAMING_SNAKE_CASE = tokenizer.encode('sequence builders' , add_special_tokens=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokenizer.encode('multi-sequence build' , add_special_tokens=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokenizer.encode(
'sequence builders' , add_special_tokens=lowerCAmelCase__ , add_prefix_space=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokenizer.encode(
'sequence builders' , 'multi-sequence build' , add_special_tokens=lowerCAmelCase__ , add_prefix_space=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__ , lowerCAmelCase__ )
assert encoded_sentence == encoded_text_from_decode
assert encoded_pair == encoded_pair_from_decode
def __A ( self ) -> List[Any]:
SCREAMING_SNAKE_CASE = self.get_tokenizer()
SCREAMING_SNAKE_CASE = 'Encode this sequence.'
SCREAMING_SNAKE_CASE = tokenizer.byte_encoder[' '.encode('utf-8' )[0]]
# Testing encoder arguments
SCREAMING_SNAKE_CASE = tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , add_prefix_space=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(encoded[0] )[0]
self.assertNotEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , add_prefix_space=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(encoded[0] )[0]
self.assertEqual(lowerCAmelCase__ , lowerCAmelCase__ )
tokenizer.add_special_tokens({'bos_token': '<s>'} )
SCREAMING_SNAKE_CASE = tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(encoded[1] )[0]
self.assertNotEqual(lowerCAmelCase__ , lowerCAmelCase__ )
# Testing spaces after special tokens
SCREAMING_SNAKE_CASE = '<mask>'
tokenizer.add_special_tokens(
{'mask_token': AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ )} ) # mask token has a left space
SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = 'Encode <mask> sequence'
SCREAMING_SNAKE_CASE = 'Encode <mask>sequence'
SCREAMING_SNAKE_CASE = tokenizer.encode(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = encoded.index(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0]
self.assertEqual(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokenizer.encode(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = encoded.index(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0]
self.assertNotEqual(lowerCAmelCase__ , lowerCAmelCase__ )
def __A ( self ) -> Dict:
pass
def __A ( self ) -> Union[str, Any]:
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ):
SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(lowerCAmelCase__ , **lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(lowerCAmelCase__ , **lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = 'A, <mask> AllenNLP sentence.'
SCREAMING_SNAKE_CASE = tokenizer_r.encode_plus(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , return_token_type_ids=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokenizer_p.encode_plus(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , return_token_type_ids=lowerCAmelCase__ )
# token_type_ids should put 0 everywhere
self.assertEqual(sum(tokens_r['token_type_ids'] ) , sum(tokens_p['token_type_ids'] ) )
# attention_mask should put 1 everywhere, so sum over length should be 1
self.assertEqual(
sum(tokens_r['attention_mask'] ) / len(tokens_r['attention_mask'] ) , sum(tokens_p['attention_mask'] ) / len(tokens_p['attention_mask'] ) , )
SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(tokens_r['input_ids'] )
SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(tokens_p['input_ids'] )
# Rust correctly handles the space before the mask while python doesnt
self.assertSequenceEqual(tokens_p['input_ids'] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2] )
self.assertSequenceEqual(tokens_r['input_ids'] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2] )
self.assertSequenceEqual(
lowerCAmelCase__ , ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] )
self.assertSequenceEqual(
lowerCAmelCase__ , ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] )
def __A ( self ) -> Union[str, Any]:
for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ):
SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(
self.tmpdirname , use_fast=lowerCAmelCase__ , add_prefix_space=lowerCAmelCase__ , trim_offsets=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() )
SCREAMING_SNAKE_CASE = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() )
self.assertEqual(pre_tokenizer_state['add_prefix_space'] , lowerCAmelCase__ )
self.assertEqual(post_processor_state['add_prefix_space'] , lowerCAmelCase__ )
self.assertEqual(post_processor_state['trim_offsets'] , lowerCAmelCase__ )
def __A ( self ) -> Dict:
# Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and
# `trim_offsets`
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ):
SCREAMING_SNAKE_CASE = 'hello' # `hello` is a token in the vocabulary of `pretrained_name`
SCREAMING_SNAKE_CASE = F'{text_of_1_token} {text_of_1_token}'
SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(
lowerCAmelCase__ , use_fast=lowerCAmelCase__ , add_prefix_space=lowerCAmelCase__ , trim_offsets=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokenizer_r(lowerCAmelCase__ , return_offsets_mapping=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ )
self.assertEqual(encoding.offset_mapping[0] , (0, len(lowerCAmelCase__ )) )
self.assertEqual(
encoding.offset_mapping[1] , (len(lowerCAmelCase__ ) + 1, len(lowerCAmelCase__ ) + 1 + len(lowerCAmelCase__ )) , )
SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(
lowerCAmelCase__ , use_fast=lowerCAmelCase__ , add_prefix_space=lowerCAmelCase__ , trim_offsets=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokenizer_r(lowerCAmelCase__ , return_offsets_mapping=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ )
self.assertEqual(encoding.offset_mapping[0] , (0, len(lowerCAmelCase__ )) )
self.assertEqual(
encoding.offset_mapping[1] , (len(lowerCAmelCase__ ) + 1, len(lowerCAmelCase__ ) + 1 + len(lowerCAmelCase__ )) , )
SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(
lowerCAmelCase__ , use_fast=lowerCAmelCase__ , add_prefix_space=lowerCAmelCase__ , trim_offsets=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokenizer_r(lowerCAmelCase__ , return_offsets_mapping=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ )
self.assertEqual(encoding.offset_mapping[0] , (0, len(lowerCAmelCase__ )) )
self.assertEqual(
encoding.offset_mapping[1] , (len(lowerCAmelCase__ ), len(lowerCAmelCase__ ) + 1 + len(lowerCAmelCase__ )) , )
SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(
lowerCAmelCase__ , use_fast=lowerCAmelCase__ , add_prefix_space=lowerCAmelCase__ , trim_offsets=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokenizer_r(lowerCAmelCase__ , return_offsets_mapping=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ )
self.assertEqual(encoding.offset_mapping[0] , (0, len(lowerCAmelCase__ )) )
self.assertEqual(
encoding.offset_mapping[1] , (len(lowerCAmelCase__ ), len(lowerCAmelCase__ ) + 1 + len(lowerCAmelCase__ )) , )
SCREAMING_SNAKE_CASE = F' {text}'
# tokenizer_r = self.rust_tokenizer_class.from_pretrained(
# pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True
# )
# encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False)
# self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token)))
# self.assertEqual(
# encoding.offset_mapping[1],
# (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)),
# )
SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(
lowerCAmelCase__ , use_fast=lowerCAmelCase__ , add_prefix_space=lowerCAmelCase__ , trim_offsets=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokenizer_r(lowerCAmelCase__ , return_offsets_mapping=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ )
self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(lowerCAmelCase__ )) )
self.assertEqual(
encoding.offset_mapping[1] , (1 + len(lowerCAmelCase__ ) + 1, 1 + len(lowerCAmelCase__ ) + 1 + len(lowerCAmelCase__ )) , )
SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(
lowerCAmelCase__ , use_fast=lowerCAmelCase__ , add_prefix_space=lowerCAmelCase__ , trim_offsets=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokenizer_r(lowerCAmelCase__ , return_offsets_mapping=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ )
self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(lowerCAmelCase__ )) )
self.assertEqual(
encoding.offset_mapping[1] , (1 + len(lowerCAmelCase__ ), 1 + len(lowerCAmelCase__ ) + 1 + len(lowerCAmelCase__ )) , )
SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(
lowerCAmelCase__ , use_fast=lowerCAmelCase__ , add_prefix_space=lowerCAmelCase__ , trim_offsets=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE = tokenizer_r(lowerCAmelCase__ , return_offsets_mapping=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ )
self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(lowerCAmelCase__ )) )
self.assertEqual(
encoding.offset_mapping[1] , (1 + len(lowerCAmelCase__ ), 1 + len(lowerCAmelCase__ ) + 1 + len(lowerCAmelCase__ )) , )
| 247 | 1 |
import unittest
import numpy as np
from transformers.testing_utils import is_flaky, 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 DonutImageProcessor
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
'''simple docstring'''
def __init__( self, lowerCamelCase__, lowerCamelCase__=7, lowerCamelCase__=3, lowerCamelCase__=18, lowerCamelCase__=30, lowerCamelCase__=400, lowerCamelCase__=True, lowerCamelCase__=None, lowerCamelCase__=True, lowerCamelCase__=False, lowerCamelCase__=True, lowerCamelCase__=True, lowerCamelCase__=[0.5, 0.5, 0.5], lowerCamelCase__=[0.5, 0.5, 0.5], ):
A : Dict = parent
A : Tuple = batch_size
A : List[str] = num_channels
A : Dict = image_size
A : str = min_resolution
A : Optional[int] = max_resolution
A : Optional[int] = do_resize
A : Optional[int] = size if size is not None else {"""height""": 18, """width""": 20}
A : Union[str, Any] = do_thumbnail
A : Dict = do_align_axis
A : List[str] = do_pad
A : Optional[Any] = do_normalize
A : List[str] = image_mean
A : Union[str, Any] = image_std
def _lowerCAmelCase ( self ):
return {
"do_resize": self.do_resize,
"size": self.size,
"do_thumbnail": self.do_thumbnail,
"do_align_long_axis": self.do_align_axis,
"do_pad": self.do_pad,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
}
@require_torch
@require_vision
class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ):
'''simple docstring'''
__lowerCamelCase : Dict = DonutImageProcessor if is_vision_available() else None
def _lowerCAmelCase ( self ):
A : Dict = DonutImageProcessingTester(self )
@property
def _lowerCAmelCase ( self ):
return self.image_processor_tester.prepare_image_processor_dict()
def _lowerCAmelCase ( self ):
A : int = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(UpperCamelCase__, """do_resize""" ) )
self.assertTrue(hasattr(UpperCamelCase__, """size""" ) )
self.assertTrue(hasattr(UpperCamelCase__, """do_thumbnail""" ) )
self.assertTrue(hasattr(UpperCamelCase__, """do_align_long_axis""" ) )
self.assertTrue(hasattr(UpperCamelCase__, """do_pad""" ) )
self.assertTrue(hasattr(UpperCamelCase__, """do_normalize""" ) )
self.assertTrue(hasattr(UpperCamelCase__, """image_mean""" ) )
self.assertTrue(hasattr(UpperCamelCase__, """image_std""" ) )
def _lowerCAmelCase ( self ):
A : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size, {"""height""": 18, """width""": 20} )
A : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict, size=42 )
self.assertEqual(image_processor.size, {"""height""": 42, """width""": 42} )
# Previous config had dimensions in (width, height) order
A : int = self.image_processing_class.from_dict(self.image_processor_dict, size=(42, 84) )
self.assertEqual(image_processor.size, {"""height""": 84, """width""": 42} )
def _lowerCAmelCase ( self ):
pass
@is_flaky()
def _lowerCAmelCase ( self ):
A : Optional[Any] = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
A : Dict = prepare_image_inputs(self.image_processor_tester, equal_resolution=UpperCamelCase__ )
for image in image_inputs:
self.assertIsInstance(UpperCamelCase__, Image.Image )
# Test not batched input
A : List[str] = image_processing(image_inputs[0], return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape, (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["""height"""],
self.image_processor_tester.size["""width"""],
), )
# Test batched
A : Optional[Any] = image_processing(UpperCamelCase__, return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape, (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["""height"""],
self.image_processor_tester.size["""width"""],
), )
@is_flaky()
def _lowerCAmelCase ( self ):
A : Any = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
A : Dict = prepare_image_inputs(self.image_processor_tester, equal_resolution=UpperCamelCase__, numpify=UpperCamelCase__ )
for image in image_inputs:
self.assertIsInstance(UpperCamelCase__, np.ndarray )
# Test not batched input
A : Optional[int] = image_processing(image_inputs[0], return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape, (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["""height"""],
self.image_processor_tester.size["""width"""],
), )
# Test batched
A : List[Any] = image_processing(UpperCamelCase__, return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape, (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["""height"""],
self.image_processor_tester.size["""width"""],
), )
@is_flaky()
def _lowerCAmelCase ( self ):
A : Optional[int] = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
A : Union[str, Any] = prepare_image_inputs(self.image_processor_tester, equal_resolution=UpperCamelCase__, torchify=UpperCamelCase__ )
for image in image_inputs:
self.assertIsInstance(UpperCamelCase__, torch.Tensor )
# Test not batched input
A : List[Any] = image_processing(image_inputs[0], return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape, (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["""height"""],
self.image_processor_tester.size["""width"""],
), )
# Test batched
A : Optional[int] = image_processing(UpperCamelCase__, return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape, (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["""height"""],
self.image_processor_tester.size["""width"""],
), )
| 700 |
def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase ) -> Optional[Any]:
"""simple docstring"""
A : Dict = [0 for i in range(r + 1 )]
# nc0 = 1
A : Dict = 1
for i in range(1 , n + 1 ):
# to compute current row from previous row.
A : Any = min(_lowerCAmelCase , _lowerCAmelCase )
while j > 0:
c[j] += c[j - 1]
j -= 1
return c[r]
print(binomial_coefficient(n=10, r=5))
| 520 | 0 |
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
lowerCAmelCase : Any = logging.get_logger(__name__)
@add_end_docstrings(__magic_name__)
class _A ( __magic_name__):
def __init__( self , **_SCREAMING_SNAKE_CASE ):
"""simple docstring"""
super().__init__(**_SCREAMING_SNAKE_CASE )
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 , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ):
"""simple docstring"""
return super().__call__(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
def UpperCAmelCase ( self , **_SCREAMING_SNAKE_CASE ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : str = {}
if "candidate_labels" in kwargs:
SCREAMING_SNAKE_CASE_ : int = kwargs['candidate_labels']
if "hypothesis_template" in kwargs:
SCREAMING_SNAKE_CASE_ : Any = kwargs['hypothesis_template']
return preprocess_params, {}, {}
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE="This is a photo of {}." ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Dict = load_image(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ : Tuple = self.image_processor(images=[image] , return_tensors=self.framework )
SCREAMING_SNAKE_CASE_ : Optional[int] = candidate_labels
SCREAMING_SNAKE_CASE_ : List[Any] = [hypothesis_template.format(_SCREAMING_SNAKE_CASE ) for x in candidate_labels]
SCREAMING_SNAKE_CASE_ : Optional[int] = self.tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=self.framework , padding=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ : Optional[int] = [text_inputs]
return inputs
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Any = model_inputs.pop('candidate_labels' )
SCREAMING_SNAKE_CASE_ : Optional[Any] = model_inputs.pop('text_inputs' )
if isinstance(text_inputs[0] , _SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ : int = text_inputs[0]
else:
# Batching case.
SCREAMING_SNAKE_CASE_ : str = text_inputs[0][0]
SCREAMING_SNAKE_CASE_ : List[str] = self.model(**_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ : str = {
'candidate_labels': candidate_labels,
'logits': outputs.logits_per_image,
}
return model_outputs
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : str = model_outputs.pop('candidate_labels' )
SCREAMING_SNAKE_CASE_ : int = model_outputs['logits'][0]
if self.framework == "pt":
SCREAMING_SNAKE_CASE_ : Dict = logits.softmax(dim=-1 ).squeeze(-1 )
SCREAMING_SNAKE_CASE_ : Union[str, Any] = probs.tolist()
if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ : Tuple = [scores]
elif self.framework == "tf":
SCREAMING_SNAKE_CASE_ : List[str] = stable_softmax(_SCREAMING_SNAKE_CASE , axis=-1 )
SCREAMING_SNAKE_CASE_ : Any = probs.numpy().tolist()
else:
raise ValueError(f"Unsupported framework: {self.framework}" )
SCREAMING_SNAKE_CASE_ : int = [
{'score': score, 'label': candidate_label}
for score, candidate_label in sorted(zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , key=lambda _SCREAMING_SNAKE_CASE : -x[0] )
]
return result
| 511 |
from __future__ import annotations
import os
from typing import Any
import requests
lowerCAmelCase : str = 'https://api.github.com'
# https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user
lowerCAmelCase : Optional[Any] = BASE_URL + '/user'
# https://github.com/settings/tokens
lowerCAmelCase : Optional[int] = os.environ.get('USER_TOKEN', '')
def A_ ( a ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : List[str] = {
'Authorization': f"token {auth_token}",
'Accept': 'application/vnd.github.v3+json',
}
return requests.get(a , headers=a ).json()
if __name__ == "__main__": # pragma: no cover
if USER_TOKEN:
for key, value in fetch_github_info(USER_TOKEN).items():
print(F'{key}: {value}')
else:
raise ValueError('\'USER_TOKEN\' field cannot be empty.')
| 511 | 1 |
def _SCREAMING_SNAKE_CASE ( a ) -> int:
__A : List[str] = []
__A : Tuple = []
__A : Union[str, Any] = {
'^': 3,
'*': 2,
'/': 2,
'%': 2,
'+': 1,
'-': 1,
} # Priority of each operator
__A : List[str] = len(a ) if (len(a ) > 7) else 7
# Print table header for output
print(
'Symbol'.center(8 ) , 'Stack'.center(a ) , 'Postfix'.center(a ) , sep=' | ' , )
print('-' * (print_width * 3 + 7) )
for x in infix:
if x.isalpha() or x.isdigit():
post_fix.append(a ) # if x is Alphabet / Digit, add it to Postfix
elif x == "(":
stack.append(a ) # if x is "(" push to Stack
elif x == ")": # if x is ")" pop stack until "(" is encountered
while stack[-1] != "(":
post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix
stack.pop()
else:
if len(a ) == 0:
stack.append(a ) # If stack is empty, push x to stack
else: # while priority of x is not > priority of element in the stack
while len(a ) > 0 and priority[x] <= priority[stack[-1]]:
post_fix.append(stack.pop() ) # pop stack & add to Postfix
stack.append(a ) # push x to stack
print(
x.center(8 ) , (''.join(a )).ljust(a ) , (''.join(a )).ljust(a ) , sep=' | ' , ) # Output in tabular format
while len(a ) > 0: # while stack is not empty
post_fix.append(stack.pop() ) # pop stack & add to Postfix
print(
' '.center(8 ) , (''.join(a )).ljust(a ) , (''.join(a )).ljust(a ) , sep=' | ' , ) # Output in tabular format
return "".join(a ) # return Postfix as str
def _SCREAMING_SNAKE_CASE ( a ) -> List[str]:
__A : List[Any] = list(infix[::-1] ) # reverse the infix equation
for i in range(len(a ) ):
if infix[i] == "(":
__A : List[str] = ')' # change "(" to ")"
elif infix[i] == ")":
__A : Any = '(' # change ")" to "("
return (infix_2_postfix(''.join(a ) ))[
::-1
] # call infix_2_postfix on Infix, return reverse of Postfix
if __name__ == "__main__":
UpperCAmelCase : List[str] = input('''\nEnter an Infix Equation = ''') # Input an Infix equation
UpperCAmelCase : Union[str, Any] = ''''''.join(Infix.split()) # Remove spaces from the input
print('''\n\t''', Infix, '''(Infix) -> ''', infix_2_prefix(Infix), '''(Prefix)''')
| 77 |
import glob
import os
import random
from string import ascii_lowercase, digits
import cva
UpperCAmelCase : Dict = ''''''
UpperCAmelCase : Union[str, Any] = ''''''
UpperCAmelCase : Optional[int] = ''''''
UpperCAmelCase : Union[str, Any] = 1 # (0 is vertical, 1 is horizontal)
def _SCREAMING_SNAKE_CASE ( ) -> None:
__A , __A : List[Any] = get_dataset(a , a )
print('Processing...' )
__A , __A , __A : Optional[Any] = update_image_and_anno(a , a , a )
for index, image in enumerate(a ):
# Get random string code: '7b7ad245cdff75241935e4dd860f3bad'
__A : Optional[int] = random_chars(32 )
__A : Dict = paths[index].split(os.sep )[-1].rsplit('.' , 1 )[0]
__A : Dict = F"""{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}"""
cva.imwrite(F"""/{file_root}.jpg""" , a , [cva.IMWRITE_JPEG_QUALITY, 85] )
print(F"""Success {index+1}/{len(a )} with {file_name}""" )
__A : int = []
for anno in new_annos[index]:
__A : Any = F"""{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}"""
annos_list.append(a )
with open(F"""/{file_root}.txt""" , 'w' ) as outfile:
outfile.write('\n'.join(line for line in annos_list ) )
def _SCREAMING_SNAKE_CASE ( a , a ) -> tuple[list, list]:
__A : int = []
__A : List[Any] = []
for label_file in glob.glob(os.path.join(a , '*.txt' ) ):
__A : List[str] = label_file.split(os.sep )[-1].rsplit('.' , 1 )[0]
with open(a ) as in_file:
__A : Tuple = in_file.readlines()
__A : Dict = os.path.join(a , F"""{label_name}.jpg""" )
__A : Dict = []
for obj_list in obj_lists:
__A : int = obj_list.rstrip('\n' ).split(' ' )
boxes.append(
[
int(obj[0] ),
float(obj[1] ),
float(obj[2] ),
float(obj[3] ),
float(obj[4] ),
] )
if not boxes:
continue
img_paths.append(a )
labels.append(a )
return img_paths, labels
def _SCREAMING_SNAKE_CASE ( a , a , a = 1 ) -> tuple[list, list, list]:
__A : int = []
__A : Optional[Any] = []
__A : Dict = []
for idx in range(len(a ) ):
__A : Dict = []
__A : Optional[Any] = img_list[idx]
path_list.append(a )
__A : Union[str, Any] = anno_list[idx]
__A : Optional[Any] = cva.imread(a )
if flip_type == 1:
__A : Any = cva.flip(a , a )
for bbox in img_annos:
__A : Dict = 1 - bbox[1]
new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] )
elif flip_type == 0:
__A : Union[str, Any] = cva.flip(a , a )
for bbox in img_annos:
__A : Optional[Any] = 1 - bbox[2]
new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] )
new_annos_lists.append(a )
new_imgs_list.append(a )
return new_imgs_list, new_annos_lists, path_list
def _SCREAMING_SNAKE_CASE ( a = 32 ) -> str:
assert number_char > 1, "The number of character should greater than 1"
__A : List[Any] = ascii_lowercase + digits
return "".join(random.choice(a ) for _ in range(a ) )
if __name__ == "__main__":
main()
print('''DONE ✅''')
| 77 | 1 |
import random
from typing import Any
def __lowercase ( a__ ) -> Dict:
for _ in range(len(SCREAMING_SNAKE_CASE_ ) ):
__SCREAMING_SNAKE_CASE = random.randint(0 , len(SCREAMING_SNAKE_CASE_ ) - 1 )
__SCREAMING_SNAKE_CASE = random.randint(0 , len(SCREAMING_SNAKE_CASE_ ) - 1 )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = data[b], data[a]
return data
if __name__ == "__main__":
lowerCAmelCase__ : Tuple =[0, 1, 2, 3, 4, 5, 6, 7]
lowerCAmelCase__ : Optional[int] =['''python''', '''says''', '''hello''', '''!''']
print('''Fisher-Yates Shuffle:''')
print('''List''', integers, strings)
print('''FY Shuffle''', fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
| 148 |
'''simple docstring'''
import unittest
from queue import Empty
from threading import Thread
from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available
from transformers.testing_utils import CaptureStdout, require_torch, torch_device
from ..test_modeling_common import ids_tensor
if is_torch_available():
import torch
from transformers import AutoModelForCausalLM
@require_torch
class lowerCAmelCase_ ( unittest.TestCase ):
def _snake_case ( self ) -> Union[str, Any]:
_lowerCAmelCase = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" )
_lowerCAmelCase = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(_lowerCAmelCase )
_lowerCAmelCase = -1
_lowerCAmelCase = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(_lowerCAmelCase )
_lowerCAmelCase = model.generate(_lowerCAmelCase , max_new_tokens=10 , do_sample=_lowerCAmelCase )
_lowerCAmelCase = tokenizer.decode(greedy_ids[0] )
with CaptureStdout() as cs:
_lowerCAmelCase = TextStreamer(_lowerCAmelCase )
model.generate(_lowerCAmelCase , max_new_tokens=10 , do_sample=_lowerCAmelCase , streamer=_lowerCAmelCase )
# The greedy text should be printed to stdout, except for the final "\n" in the streamer
_lowerCAmelCase = cs.out[:-1]
self.assertEqual(_lowerCAmelCase , _lowerCAmelCase )
def _snake_case ( self ) -> Union[str, Any]:
_lowerCAmelCase = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" )
_lowerCAmelCase = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(_lowerCAmelCase )
_lowerCAmelCase = -1
_lowerCAmelCase = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(_lowerCAmelCase )
_lowerCAmelCase = model.generate(_lowerCAmelCase , max_new_tokens=10 , do_sample=_lowerCAmelCase )
_lowerCAmelCase = tokenizer.decode(greedy_ids[0] )
_lowerCAmelCase = TextIteratorStreamer(_lowerCAmelCase )
_lowerCAmelCase = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer}
_lowerCAmelCase = Thread(target=model.generate , kwargs=_lowerCAmelCase )
thread.start()
_lowerCAmelCase = ""
for new_text in streamer:
streamer_text += new_text
self.assertEqual(_lowerCAmelCase , _lowerCAmelCase )
def _snake_case ( self ) -> List[str]:
_lowerCAmelCase = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" )
_lowerCAmelCase = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(_lowerCAmelCase )
_lowerCAmelCase = -1
_lowerCAmelCase = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(_lowerCAmelCase )
_lowerCAmelCase = model.generate(_lowerCAmelCase , max_new_tokens=10 , do_sample=_lowerCAmelCase )
_lowerCAmelCase = greedy_ids[:, input_ids.shape[1] :]
_lowerCAmelCase = tokenizer.decode(new_greedy_ids[0] )
with CaptureStdout() as cs:
_lowerCAmelCase = TextStreamer(_lowerCAmelCase , skip_prompt=_lowerCAmelCase )
model.generate(_lowerCAmelCase , max_new_tokens=10 , do_sample=_lowerCAmelCase , streamer=_lowerCAmelCase )
# The greedy text should be printed to stdout, except for the final "\n" in the streamer
_lowerCAmelCase = cs.out[:-1]
self.assertEqual(_lowerCAmelCase , _lowerCAmelCase )
def _snake_case ( self ) -> Dict:
# Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested
# with actual models -- the dummy models' tokenizers are not aligned with their models, and
# `skip_special_tokens=True` has no effect on them
_lowerCAmelCase = AutoTokenizer.from_pretrained("distilgpt2" )
_lowerCAmelCase = AutoModelForCausalLM.from_pretrained("distilgpt2" ).to(_lowerCAmelCase )
_lowerCAmelCase = -1
_lowerCAmelCase = torch.ones((1, 5) , device=_lowerCAmelCase ).long() * model.config.bos_token_id
with CaptureStdout() as cs:
_lowerCAmelCase = TextStreamer(_lowerCAmelCase , skip_special_tokens=_lowerCAmelCase )
model.generate(_lowerCAmelCase , max_new_tokens=1 , do_sample=_lowerCAmelCase , streamer=_lowerCAmelCase )
# The prompt contains a special token, so the streamer should not print it. As such, the output text, when
# re-tokenized, must only contain one token
_lowerCAmelCase = cs.out[:-1] # Remove the final "\n"
_lowerCAmelCase = tokenizer(_lowerCAmelCase , return_tensors="pt" )
self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1) )
def _snake_case ( self ) -> Union[str, Any]:
_lowerCAmelCase = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" )
_lowerCAmelCase = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(_lowerCAmelCase )
_lowerCAmelCase = -1
_lowerCAmelCase = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(_lowerCAmelCase )
_lowerCAmelCase = TextIteratorStreamer(_lowerCAmelCase , timeout=0.001 )
_lowerCAmelCase = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer}
_lowerCAmelCase = Thread(target=model.generate , kwargs=_lowerCAmelCase )
thread.start()
# The streamer will timeout after 0.001 seconds, so an exception will be raised
with self.assertRaises(_lowerCAmelCase ):
_lowerCAmelCase = ""
for new_text in streamer:
streamer_text += new_text
| 18 | 0 |
"""simple docstring"""
def lowercase__(A = 1_000 ) ->int:
"""simple docstring"""
lowercase__ : Union[str, Any]= 2**power
lowercase__ : Dict= str(A )
lowercase__ : List[str]= list(A )
lowercase__ : Union[str, Any]= 0
for i in list_num:
sum_of_num += int(A )
return sum_of_num
if __name__ == "__main__":
a : Any = int(input("""Enter the power of 2: """).strip())
print("""2 ^ """, power, """ = """, 2**power)
a : Union[str, Any] = solution(power)
print("""Sum of the digits is: """, result)
| 85 |
"""simple docstring"""
from typing import List, Optional, Tuple, Union
import torch
from ...models import UNetaDModel
from ...schedulers import ScoreSdeVeScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ):
"""simple docstring"""
__lowerCamelCase = 42
__lowerCamelCase = 42
def __init__( self , snake_case__ , snake_case__ ):
'''simple docstring'''
super().__init__()
self.register_modules(unet=snake_case__ , scheduler=snake_case__ )
@torch.no_grad()
def __call__( self , snake_case__ = 1 , snake_case__ = 2000 , snake_case__ = None , snake_case__ = "pil" , snake_case__ = True , **snake_case__ , ):
'''simple docstring'''
lowercase__ : Optional[Any]= self.unet.config.sample_size
lowercase__ : Dict= (batch_size, 3, img_size, img_size)
lowercase__ : List[Any]= self.unet
lowercase__ : Tuple= randn_tensor(snake_case__ , generator=snake_case__ ) * self.scheduler.init_noise_sigma
lowercase__ : Tuple= sample.to(self.device )
self.scheduler.set_timesteps(snake_case__ )
self.scheduler.set_sigmas(snake_case__ )
for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ):
lowercase__ : Optional[Any]= self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device )
# correction step
for _ in range(self.scheduler.config.correct_steps ):
lowercase__ : List[Any]= self.unet(snake_case__ , snake_case__ ).sample
lowercase__ : List[Any]= self.scheduler.step_correct(snake_case__ , snake_case__ , generator=snake_case__ ).prev_sample
# prediction step
lowercase__ : List[str]= model(snake_case__ , snake_case__ ).sample
lowercase__ : Tuple= self.scheduler.step_pred(snake_case__ , snake_case__ , snake_case__ , generator=snake_case__ )
lowercase__, lowercase__ : Tuple= output.prev_sample, output.prev_sample_mean
lowercase__ : List[str]= sample_mean.clamp(0 , 1 )
lowercase__ : Union[str, Any]= sample.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
lowercase__ : str= self.numpy_to_pil(snake_case__ )
if not return_dict:
return (sample,)
return ImagePipelineOutput(images=snake_case__ )
| 85 | 1 |
import hashlib
import unittest
from typing import Dict
import numpy as np
from transformers import (
MODEL_FOR_MASK_GENERATION_MAPPING,
TF_MODEL_FOR_MASK_GENERATION_MAPPING,
is_vision_available,
pipeline,
)
from transformers.pipelines import MaskGenerationPipeline
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_tf,
require_torch,
require_vision,
slow,
)
if is_vision_available():
from PIL import Image
else:
class SCREAMING_SNAKE_CASE :
@staticmethod
def UpperCamelCase_ ( *__lowercase : str , **__lowercase : List[Any] ):
'''simple docstring'''
pass
def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Image ):
"""simple docstring"""
__a = hashlib.mda(image.tobytes() )
return m.hexdigest()[:10]
def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Image ):
"""simple docstring"""
__a = np.array(_SCREAMING_SNAKE_CASE )
__a = npimg.shape
return {"hash": hashimage(_SCREAMING_SNAKE_CASE ), "shape": shape}
@is_pipeline_test
@require_vision
@require_torch
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
__lowerCamelCase : List[str] =dict(
(list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) )
__lowerCamelCase : Any =dict(
(list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) )
def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : int , __lowercase : int , __lowercase : Union[str, Any] ):
'''simple docstring'''
__a = MaskGenerationPipeline(model=__lowercase , image_processor=__lowercase )
return image_segmenter, [
"./tests/fixtures/tests_samples/COCO/000000039769.png",
"./tests/fixtures/tests_samples/COCO/000000039769.png",
]
def UpperCamelCase_ ( self : int , __lowercase : Dict , __lowercase : Any ):
'''simple docstring'''
pass
@require_tf
@unittest.skip("""Image segmentation not implemented in TF""" )
def UpperCamelCase_ ( self : Tuple ):
'''simple docstring'''
pass
@slow
@require_torch
def UpperCamelCase_ ( self : Union[str, Any] ):
'''simple docstring'''
__a = pipeline("""mask-generation""" , model="""facebook/sam-vit-huge""" )
__a = image_segmenter("""http://images.cocodataset.org/val2017/000000039769.jpg""" , points_per_batch=256 )
# Shortening by hashing
__a = []
for i, o in enumerate(outputs["""masks"""] ):
new_outupt += [{"mask": mask_to_test_readable(__lowercase ), "scores": outputs["scores"][i]}]
# fmt: off
self.assertEqual(
nested_simplify(__lowercase , decimals=4 ) , [
{"""mask""": {"""hash""": """115ad19f5f""", """shape""": (480, 640)}, """scores""": 1.0444},
{"""mask""": {"""hash""": """6affa964c6""", """shape""": (480, 640)}, """scores""": 1.021},
{"""mask""": {"""hash""": """dfe28a0388""", """shape""": (480, 640)}, """scores""": 1.0167},
{"""mask""": {"""hash""": """c0a5f4a318""", """shape""": (480, 640)}, """scores""": 1.0132},
{"""mask""": {"""hash""": """fe8065c197""", """shape""": (480, 640)}, """scores""": 1.0053},
{"""mask""": {"""hash""": """e2d0b7a0b7""", """shape""": (480, 640)}, """scores""": 0.9967},
{"""mask""": {"""hash""": """453c7844bd""", """shape""": (480, 640)}, """scores""": 0.993},
{"""mask""": {"""hash""": """3d44f2926d""", """shape""": (480, 640)}, """scores""": 0.9909},
{"""mask""": {"""hash""": """64033ddc3f""", """shape""": (480, 640)}, """scores""": 0.9879},
{"""mask""": {"""hash""": """801064ff79""", """shape""": (480, 640)}, """scores""": 0.9834},
{"""mask""": {"""hash""": """6172f276ef""", """shape""": (480, 640)}, """scores""": 0.9716},
{"""mask""": {"""hash""": """b49e60e084""", """shape""": (480, 640)}, """scores""": 0.9612},
{"""mask""": {"""hash""": """a811e775fd""", """shape""": (480, 640)}, """scores""": 0.9599},
{"""mask""": {"""hash""": """a6a8ebcf4b""", """shape""": (480, 640)}, """scores""": 0.9552},
{"""mask""": {"""hash""": """9d8257e080""", """shape""": (480, 640)}, """scores""": 0.9532},
{"""mask""": {"""hash""": """32de6454a8""", """shape""": (480, 640)}, """scores""": 0.9516},
{"""mask""": {"""hash""": """af3d4af2c8""", """shape""": (480, 640)}, """scores""": 0.9499},
{"""mask""": {"""hash""": """3c6db475fb""", """shape""": (480, 640)}, """scores""": 0.9483},
{"""mask""": {"""hash""": """c290813fb9""", """shape""": (480, 640)}, """scores""": 0.9464},
{"""mask""": {"""hash""": """b6f0b8f606""", """shape""": (480, 640)}, """scores""": 0.943},
{"""mask""": {"""hash""": """92ce16bfdf""", """shape""": (480, 640)}, """scores""": 0.943},
{"""mask""": {"""hash""": """c749b25868""", """shape""": (480, 640)}, """scores""": 0.9408},
{"""mask""": {"""hash""": """efb6cab859""", """shape""": (480, 640)}, """scores""": 0.9335},
{"""mask""": {"""hash""": """1ff2eafb30""", """shape""": (480, 640)}, """scores""": 0.9326},
{"""mask""": {"""hash""": """788b798e24""", """shape""": (480, 640)}, """scores""": 0.9262},
{"""mask""": {"""hash""": """abea804f0e""", """shape""": (480, 640)}, """scores""": 0.8999},
{"""mask""": {"""hash""": """7b9e8ddb73""", """shape""": (480, 640)}, """scores""": 0.8986},
{"""mask""": {"""hash""": """cd24047c8a""", """shape""": (480, 640)}, """scores""": 0.8984},
{"""mask""": {"""hash""": """6943e6bcbd""", """shape""": (480, 640)}, """scores""": 0.8873},
{"""mask""": {"""hash""": """b5f47c9191""", """shape""": (480, 640)}, """scores""": 0.8871}
] , )
# fmt: on
@require_torch
@slow
def UpperCamelCase_ ( self : Dict ):
'''simple docstring'''
__a = """facebook/sam-vit-huge"""
__a = pipeline("""mask-generation""" , model=__lowercase )
__a = image_segmenter(
"""http://images.cocodataset.org/val2017/000000039769.jpg""" , pred_iou_thresh=1 , points_per_batch=256 )
# Shortening by hashing
__a = []
for i, o in enumerate(outputs["""masks"""] ):
new_outupt += [{"mask": mask_to_test_readable(__lowercase ), "scores": outputs["scores"][i]}]
self.assertEqual(
nested_simplify(__lowercase , decimals=4 ) , [
{"""mask""": {"""hash""": """115ad19f5f""", """shape""": (480, 640)}, """scores""": 1.0444},
{"""mask""": {"""hash""": """6affa964c6""", """shape""": (480, 640)}, """scores""": 1.0210},
{"""mask""": {"""hash""": """dfe28a0388""", """shape""": (480, 640)}, """scores""": 1.0167},
{"""mask""": {"""hash""": """c0a5f4a318""", """shape""": (480, 640)}, """scores""": 1.0132},
{"""mask""": {"""hash""": """fe8065c197""", """shape""": (480, 640)}, """scores""": 1.0053},
] , )
| 225 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
lowerCamelCase__ = {
"""configuration_mvp""": ["""MVP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MvpConfig""", """MvpOnnxConfig"""],
"""tokenization_mvp""": ["""MvpTokenizer"""],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCamelCase__ = ["""MvpTokenizerFast"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCamelCase__ = [
"""MVP_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""MvpForCausalLM""",
"""MvpForConditionalGeneration""",
"""MvpForQuestionAnswering""",
"""MvpForSequenceClassification""",
"""MvpModel""",
"""MvpPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig
from .tokenization_mvp import MvpTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_mvp_fast import MvpTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mvp import (
MVP_PRETRAINED_MODEL_ARCHIVE_LIST,
MvpForCausalLM,
MvpForConditionalGeneration,
MvpForQuestionAnswering,
MvpForSequenceClassification,
MvpModel,
MvpPreTrainedModel,
)
else:
import sys
lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 225 | 1 |
import fire
from torch.utils.data import DataLoader
from tqdm import tqdm
from transformers import AutoTokenizer
from utils import SeqaSeqDataset, pickle_save
def A(__a: Any , __a: str , __a: List[Any]=1024 , __a: Optional[int]=1024 , __a: List[str]=False , **__a: Optional[Any] ):
lowerCAmelCase_ = AutoTokenizer.from_pretrained(__a )
lowerCAmelCase_ = SeqaSeqDataset(__a , __a , __a , __a , type_path="train" , **__a )
lowerCAmelCase_ = tok.pad_token_id
def get_lens(__a: List[str] ):
lowerCAmelCase_ = tqdm(
DataLoader(__a , batch_size=512 , num_workers=8 , shuffle=__a , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , )
lowerCAmelCase_ = []
for batch in dl:
lowerCAmelCase_ = batch["input_ids"].ne(__a ).sum(1 ).tolist()
lowerCAmelCase_ = batch["labels"].ne(__a ).sum(1 ).tolist()
if consider_target:
for src, tgt in zip(__a , __a ):
max_lens.append(max(__a , __a ) )
else:
max_lens.extend(__a )
return max_lens
lowerCAmelCase_ = get_lens(__a )
lowerCAmelCase_ = SeqaSeqDataset(__a , __a , __a , __a , type_path="val" , **__a )
lowerCAmelCase_ = get_lens(__a )
pickle_save(__a , train_ds.len_file )
pickle_save(__a , val_ds.len_file )
if __name__ == "__main__":
fire.Fire(save_len_file)
| 226 |
def A(__a: int ):
lowerCAmelCase_ = abs(__a )
lowerCAmelCase_ = 0
while n > 0:
res += n % 10
n //= 10
return res
def A(__a: int ):
lowerCAmelCase_ = abs(__a )
return n if n < 10 else n % 10 + sum_of_digits(n // 10 )
def A(__a: int ):
return sum(int(__a ) for c in str(abs(__a ) ) )
def A():
from collections.abc import Callable
from timeit import timeit
def benchmark_a_function(__a: Callable , __a: int ) -> None:
lowerCAmelCase_ = F"{func.__name__}({value})"
lowerCAmelCase_ = timeit(F"__main__.{call}" , setup="import __main__" )
print(F"{call:56} = {func(__a )} -- {timing:.4f} seconds" )
for value in (26_2144, 1125_8999_0684_2624, 126_7650_6002_2822_9401_4967_0320_5376):
for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact):
benchmark_a_function(__a , __a )
print()
if __name__ == "__main__":
import doctest
doctest.testmod()
benchmark()
| 226 | 1 |
from abc import ABC, abstractmethod
from typing import Optional, Union
from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit
from ..utils.typing import NestedDataStructureLike, PathLike
class A_ ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__(self , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = None , lowercase__ = False , lowercase__ = False , lowercase__ = None , **lowercase__ , ) -> Optional[int]:
__UpperCAmelCase = path_or_paths
__UpperCAmelCase = split if split or isinstance(_snake_case , _snake_case ) else "train"
__UpperCAmelCase = features
__UpperCAmelCase = cache_dir
__UpperCAmelCase = keep_in_memory
__UpperCAmelCase = streaming
__UpperCAmelCase = num_proc
__UpperCAmelCase = kwargs
@abstractmethod
def lowerCAmelCase_ (self ) -> Optional[Any]:
pass
class A_ ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__(self , lowercase__ = None , lowercase__ = None , lowercase__ = False , lowercase__ = False , lowercase__ = None , **lowercase__ , ) -> List[str]:
__UpperCAmelCase = features
__UpperCAmelCase = cache_dir
__UpperCAmelCase = keep_in_memory
__UpperCAmelCase = streaming
__UpperCAmelCase = num_proc
__UpperCAmelCase = kwargs
@abstractmethod
def lowerCAmelCase_ (self ) -> int:
pass
| 303 |
'''simple docstring'''
import gc
import unittest
import numpy as np
import torch
import torch.nn.functional as F
from transformers import (
ClapTextConfig,
ClapTextModelWithProjection,
RobertaTokenizer,
SpeechTaHifiGan,
SpeechTaHifiGanConfig,
)
from diffusers import (
AudioLDMPipeline,
AutoencoderKL,
DDIMScheduler,
LMSDiscreteScheduler,
PNDMScheduler,
UNetaDConditionModel,
)
from diffusers.utils import is_xformers_available, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism
from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
class _snake_case (__SCREAMING_SNAKE_CASE , unittest.TestCase):
__A : Any =AudioLDMPipeline
__A : Dict =TEXT_TO_AUDIO_PARAMS
__A : Any =TEXT_TO_AUDIO_BATCH_PARAMS
__A : Tuple =frozenset(
[
"num_inference_steps",
"num_waveforms_per_prompt",
"generator",
"latents",
"output_type",
"return_dict",
"callback",
"callback_steps",
])
def UpperCamelCase__ ( self ):
torch.manual_seed(0 )
UpperCAmelCase_ : Union[str, Any] = UNetaDConditionModel(
block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") ,up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") ,cross_attention_dim=(32, 64) ,class_embed_type="simple_projection" ,projection_class_embeddings_input_dim=32 ,class_embeddings_concat=_snake_case ,)
UpperCAmelCase_ : Optional[Any] = DDIMScheduler(
beta_start=0.00085 ,beta_end=0.012 ,beta_schedule="scaled_linear" ,clip_sample=_snake_case ,set_alpha_to_one=_snake_case ,)
torch.manual_seed(0 )
UpperCAmelCase_ : Union[str, Any] = AutoencoderKL(
block_out_channels=[32, 64] ,in_channels=1 ,out_channels=1 ,down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] ,up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] ,latent_channels=4 ,)
torch.manual_seed(0 )
UpperCAmelCase_ : Optional[int] = ClapTextConfig(
bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=10_00 ,projection_dim=32 ,)
UpperCAmelCase_ : Optional[Any] = ClapTextModelWithProjection(_snake_case )
UpperCAmelCase_ : List[Any] = RobertaTokenizer.from_pretrained("hf-internal-testing/tiny-random-roberta" ,model_max_length=77 )
UpperCAmelCase_ : Optional[int] = SpeechTaHifiGanConfig(
model_in_dim=8 ,sampling_rate=1_60_00 ,upsample_initial_channel=16 ,upsample_rates=[2, 2] ,upsample_kernel_sizes=[4, 4] ,resblock_kernel_sizes=[3, 7] ,resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] ,normalize_before=_snake_case ,)
UpperCAmelCase_ : Union[str, Any] = SpeechTaHifiGan(_snake_case )
UpperCAmelCase_ : Union[str, Any] = {
"unet": unet,
"scheduler": scheduler,
"vae": vae,
"text_encoder": text_encoder,
"tokenizer": tokenizer,
"vocoder": vocoder,
}
return components
def UpperCamelCase__ ( self ,_snake_case ,_snake_case=0 ):
if str(_snake_case ).startswith("mps" ):
UpperCAmelCase_ : Optional[int] = torch.manual_seed(_snake_case )
else:
UpperCAmelCase_ : List[str] = torch.Generator(device=_snake_case ).manual_seed(_snake_case )
UpperCAmelCase_ : Any = {
"prompt": "A hammer hitting a wooden surface",
"generator": generator,
"num_inference_steps": 2,
"guidance_scale": 6.0,
}
return inputs
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : int = "cpu" # ensure determinism for the device-dependent torch.Generator
UpperCAmelCase_ : str = self.get_dummy_components()
UpperCAmelCase_ : Optional[Any] = AudioLDMPipeline(**_snake_case )
UpperCAmelCase_ : List[Any] = audioldm_pipe.to(_snake_case )
audioldm_pipe.set_progress_bar_config(disable=_snake_case )
UpperCAmelCase_ : List[str] = self.get_dummy_inputs(_snake_case )
UpperCAmelCase_ : Any = audioldm_pipe(**_snake_case )
UpperCAmelCase_ : Dict = output.audios[0]
assert audio.ndim == 1
assert len(_snake_case ) == 2_56
UpperCAmelCase_ : Any = audio[:10]
UpperCAmelCase_ : Any = np.array(
[-0.0050, 0.0050, -0.0060, 0.0033, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0033] )
assert np.abs(audio_slice - expected_slice ).max() < 1E-2
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : Optional[int] = self.get_dummy_components()
UpperCAmelCase_ : int = AudioLDMPipeline(**_snake_case )
UpperCAmelCase_ : Dict = audioldm_pipe.to(_snake_case )
UpperCAmelCase_ : Tuple = audioldm_pipe.to(_snake_case )
audioldm_pipe.set_progress_bar_config(disable=_snake_case )
UpperCAmelCase_ : Union[str, Any] = self.get_dummy_inputs(_snake_case )
UpperCAmelCase_ : Tuple = 3 * [inputs["prompt"]]
# forward
UpperCAmelCase_ : Any = audioldm_pipe(**_snake_case )
UpperCAmelCase_ : List[str] = output.audios[0]
UpperCAmelCase_ : Optional[Any] = self.get_dummy_inputs(_snake_case )
UpperCAmelCase_ : str = 3 * [inputs.pop("prompt" )]
UpperCAmelCase_ : str = audioldm_pipe.tokenizer(
_snake_case ,padding="max_length" ,max_length=audioldm_pipe.tokenizer.model_max_length ,truncation=_snake_case ,return_tensors="pt" ,)
UpperCAmelCase_ : Dict = text_inputs["input_ids"].to(_snake_case )
UpperCAmelCase_ : str = audioldm_pipe.text_encoder(
_snake_case ,)
UpperCAmelCase_ : Optional[Any] = prompt_embeds.text_embeds
# additional L_2 normalization over each hidden-state
UpperCAmelCase_ : Tuple = F.normalize(_snake_case ,dim=-1 )
UpperCAmelCase_ : int = prompt_embeds
# forward
UpperCAmelCase_ : int = audioldm_pipe(**_snake_case )
UpperCAmelCase_ : List[Any] = output.audios[0]
assert np.abs(audio_a - audio_a ).max() < 1E-2
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : List[Any] = self.get_dummy_components()
UpperCAmelCase_ : Tuple = AudioLDMPipeline(**_snake_case )
UpperCAmelCase_ : List[Any] = audioldm_pipe.to(_snake_case )
UpperCAmelCase_ : List[Any] = audioldm_pipe.to(_snake_case )
audioldm_pipe.set_progress_bar_config(disable=_snake_case )
UpperCAmelCase_ : Union[str, Any] = self.get_dummy_inputs(_snake_case )
UpperCAmelCase_ : Optional[int] = 3 * ["this is a negative prompt"]
UpperCAmelCase_ : Any = negative_prompt
UpperCAmelCase_ : Union[str, Any] = 3 * [inputs["prompt"]]
# forward
UpperCAmelCase_ : Dict = audioldm_pipe(**_snake_case )
UpperCAmelCase_ : Dict = output.audios[0]
UpperCAmelCase_ : Tuple = self.get_dummy_inputs(_snake_case )
UpperCAmelCase_ : Optional[Any] = 3 * [inputs.pop("prompt" )]
UpperCAmelCase_ : List[Any] = []
for p in [prompt, negative_prompt]:
UpperCAmelCase_ : Any = audioldm_pipe.tokenizer(
_snake_case ,padding="max_length" ,max_length=audioldm_pipe.tokenizer.model_max_length ,truncation=_snake_case ,return_tensors="pt" ,)
UpperCAmelCase_ : List[Any] = text_inputs["input_ids"].to(_snake_case )
UpperCAmelCase_ : str = audioldm_pipe.text_encoder(
_snake_case ,)
UpperCAmelCase_ : List[Any] = text_embeds.text_embeds
# additional L_2 normalization over each hidden-state
UpperCAmelCase_ : Any = F.normalize(_snake_case ,dim=-1 )
embeds.append(_snake_case )
UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = embeds
# forward
UpperCAmelCase_ : Tuple = audioldm_pipe(**_snake_case )
UpperCAmelCase_ : Any = output.audios[0]
assert np.abs(audio_a - audio_a ).max() < 1E-2
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : Optional[int] = "cpu" # ensure determinism for the device-dependent torch.Generator
UpperCAmelCase_ : Optional[Any] = self.get_dummy_components()
UpperCAmelCase_ : Any = PNDMScheduler(skip_prk_steps=_snake_case )
UpperCAmelCase_ : Optional[Any] = AudioLDMPipeline(**_snake_case )
UpperCAmelCase_ : List[Any] = audioldm_pipe.to(_snake_case )
audioldm_pipe.set_progress_bar_config(disable=_snake_case )
UpperCAmelCase_ : Any = self.get_dummy_inputs(_snake_case )
UpperCAmelCase_ : int = "egg cracking"
UpperCAmelCase_ : Optional[Any] = audioldm_pipe(**_snake_case ,negative_prompt=_snake_case )
UpperCAmelCase_ : int = output.audios[0]
assert audio.ndim == 1
assert len(_snake_case ) == 2_56
UpperCAmelCase_ : List[Any] = audio[:10]
UpperCAmelCase_ : Any = np.array(
[-0.0051, 0.0050, -0.0060, 0.0034, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0032] )
assert np.abs(audio_slice - expected_slice ).max() < 1E-2
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : Optional[int] = "cpu" # ensure determinism for the device-dependent torch.Generator
UpperCAmelCase_ : List[str] = self.get_dummy_components()
UpperCAmelCase_ : Dict = PNDMScheduler(skip_prk_steps=_snake_case )
UpperCAmelCase_ : Any = AudioLDMPipeline(**_snake_case )
UpperCAmelCase_ : Any = audioldm_pipe.to(_snake_case )
audioldm_pipe.set_progress_bar_config(disable=_snake_case )
UpperCAmelCase_ : Dict = "A hammer hitting a wooden surface"
# test num_waveforms_per_prompt=1 (default)
UpperCAmelCase_ : Any = audioldm_pipe(_snake_case ,num_inference_steps=2 ).audios
assert audios.shape == (1, 2_56)
# test num_waveforms_per_prompt=1 (default) for batch of prompts
UpperCAmelCase_ : List[str] = 2
UpperCAmelCase_ : Dict = audioldm_pipe([prompt] * batch_size ,num_inference_steps=2 ).audios
assert audios.shape == (batch_size, 2_56)
# test num_waveforms_per_prompt for single prompt
UpperCAmelCase_ : List[str] = 2
UpperCAmelCase_ : List[Any] = audioldm_pipe(_snake_case ,num_inference_steps=2 ,num_waveforms_per_prompt=_snake_case ).audios
assert audios.shape == (num_waveforms_per_prompt, 2_56)
# test num_waveforms_per_prompt for batch of prompts
UpperCAmelCase_ : Union[str, Any] = 2
UpperCAmelCase_ : Optional[int] = audioldm_pipe(
[prompt] * batch_size ,num_inference_steps=2 ,num_waveforms_per_prompt=_snake_case ).audios
assert audios.shape == (batch_size * num_waveforms_per_prompt, 2_56)
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : List[str] = "cpu" # ensure determinism for the device-dependent torch.Generator
UpperCAmelCase_ : Optional[Any] = self.get_dummy_components()
UpperCAmelCase_ : Union[str, Any] = AudioLDMPipeline(**_snake_case )
UpperCAmelCase_ : List[Any] = audioldm_pipe.to(_snake_case )
audioldm_pipe.set_progress_bar_config(disable=_snake_case )
UpperCAmelCase_ : Optional[Any] = audioldm_pipe.vocoder.config.sampling_rate
UpperCAmelCase_ : Any = self.get_dummy_inputs(_snake_case )
UpperCAmelCase_ : Optional[int] = audioldm_pipe(audio_length_in_s=0.016 ,**_snake_case )
UpperCAmelCase_ : str = output.audios[0]
assert audio.ndim == 1
assert len(_snake_case ) / vocoder_sampling_rate == 0.016
UpperCAmelCase_ : List[Any] = audioldm_pipe(audio_length_in_s=0.032 ,**_snake_case )
UpperCAmelCase_ : Any = output.audios[0]
assert audio.ndim == 1
assert len(_snake_case ) / vocoder_sampling_rate == 0.032
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : Optional[int] = self.get_dummy_components()
UpperCAmelCase_ : str = AudioLDMPipeline(**_snake_case )
UpperCAmelCase_ : int = audioldm_pipe.to(_snake_case )
audioldm_pipe.set_progress_bar_config(disable=_snake_case )
UpperCAmelCase_ : int = ["hey"]
UpperCAmelCase_ : Dict = audioldm_pipe(_snake_case ,num_inference_steps=1 )
UpperCAmelCase_ : Any = output.audios.shape
assert audio_shape == (1, 2_56)
UpperCAmelCase_ : Tuple = audioldm_pipe.vocoder.config
config.model_in_dim *= 2
UpperCAmelCase_ : List[Any] = SpeechTaHifiGan(_snake_case ).to(_snake_case )
UpperCAmelCase_ : Tuple = audioldm_pipe(_snake_case ,num_inference_steps=1 )
UpperCAmelCase_ : int = output.audios.shape
# waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram
assert audio_shape == (1, 2_56)
def UpperCamelCase__ ( self ):
self._test_attention_slicing_forward_pass(test_mean_pixel_difference=_snake_case )
def UpperCamelCase__ ( self ):
self._test_inference_batch_single_identical(test_mean_pixel_difference=_snake_case )
@unittest.skipIf(
torch_device != "cuda" or not is_xformers_available() ,reason="XFormers attention is only available with CUDA and `xformers` installed" ,)
def UpperCamelCase__ ( self ):
self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=_snake_case )
@slow
class _snake_case (unittest.TestCase):
def UpperCamelCase__ ( self ):
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCamelCase__ ( self ,_snake_case ,_snake_case="cpu" ,_snake_case=torch.floataa ,_snake_case=0 ):
UpperCAmelCase_ : Union[str, Any] = torch.Generator(device=_snake_case ).manual_seed(_snake_case )
UpperCAmelCase_ : str = np.random.RandomState(_snake_case ).standard_normal((1, 8, 1_28, 16) )
UpperCAmelCase_ : Optional[Any] = torch.from_numpy(_snake_case ).to(device=_snake_case ,dtype=_snake_case )
UpperCAmelCase_ : List[str] = {
"prompt": "A hammer hitting a wooden surface",
"latents": latents,
"generator": generator,
"num_inference_steps": 3,
"guidance_scale": 2.5,
}
return inputs
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : int = AudioLDMPipeline.from_pretrained("cvssp/audioldm" )
UpperCAmelCase_ : Optional[int] = audioldm_pipe.to(_snake_case )
audioldm_pipe.set_progress_bar_config(disable=_snake_case )
UpperCAmelCase_ : List[Any] = self.get_inputs(_snake_case )
UpperCAmelCase_ : List[Any] = 25
UpperCAmelCase_ : Union[str, Any] = audioldm_pipe(**_snake_case ).audios[0]
assert audio.ndim == 1
assert len(_snake_case ) == 8_19_20
UpperCAmelCase_ : Union[str, Any] = audio[7_72_30:7_72_40]
UpperCAmelCase_ : Any = np.array(
[-0.4884, -0.4607, 0.0023, 0.5007, 0.5896, 0.5151, 0.3813, -0.0208, -0.3687, -0.4315] )
UpperCAmelCase_ : Dict = np.abs(expected_slice - audio_slice ).max()
assert max_diff < 1E-2
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : Optional[int] = AudioLDMPipeline.from_pretrained("cvssp/audioldm" )
UpperCAmelCase_ : List[Any] = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config )
UpperCAmelCase_ : int = audioldm_pipe.to(_snake_case )
audioldm_pipe.set_progress_bar_config(disable=_snake_case )
UpperCAmelCase_ : Tuple = self.get_inputs(_snake_case )
UpperCAmelCase_ : Optional[Any] = audioldm_pipe(**_snake_case ).audios[0]
assert audio.ndim == 1
assert len(_snake_case ) == 8_19_20
UpperCAmelCase_ : Any = audio[2_77_80:2_77_90]
UpperCAmelCase_ : List[str] = np.array([-0.2131, -0.0873, -0.0124, -0.0189, 0.0569, 0.1373, 0.1883, 0.2886, 0.3297, 0.2212] )
UpperCAmelCase_ : Union[str, Any] = np.abs(expected_slice - audio_slice ).max()
assert max_diff < 3E-2
| 71 | 0 |
import argparse
import gc
import json
import os
import shutil
import warnings
import torch
from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer
try:
from transformers import LlamaTokenizerFast
except ImportError as e:
warnings.warn(e)
warnings.warn(
'The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion'
)
__lowerCAmelCase : str = None
__lowerCAmelCase : Union[str, Any] = {
'7B': 1_1008,
'13B': 1_3824,
'30B': 1_7920,
'65B': 2_2016,
'70B': 2_8672,
}
__lowerCAmelCase : List[str] = {
'7B': 1,
'7Bf': 1,
'13B': 2,
'13Bf': 2,
'30B': 4,
'65B': 8,
'70B': 8,
'70Bf': 8,
}
def a_ (_lowerCAmelCase : Any , _lowerCAmelCase : List[str]=1 , _lowerCAmelCase : str=256 )-> int:
return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of)
def a_ (_lowerCAmelCase : List[str] )-> List[Any]:
with open(_lowerCAmelCase , """r""" ) as f:
return json.load(_lowerCAmelCase )
def a_ (_lowerCAmelCase : str , _lowerCAmelCase : Optional[Any] )-> str:
with open(_lowerCAmelCase , """w""" ) as f:
json.dump(_lowerCAmelCase , _lowerCAmelCase )
def a_ (_lowerCAmelCase : List[Any] , _lowerCAmelCase : str , _lowerCAmelCase : int , _lowerCAmelCase : List[Any]=True )-> int:
os.makedirs(_lowerCAmelCase , exist_ok=_lowerCAmelCase )
snake_case: Optional[Any] = os.path.join(_lowerCAmelCase , """tmp""" )
os.makedirs(_lowerCAmelCase , exist_ok=_lowerCAmelCase )
snake_case: List[str] = read_json(os.path.join(_lowerCAmelCase , """params.json""" ) )
snake_case: List[Any] = NUM_SHARDS[model_size]
snake_case: List[Any] = params["""n_layers"""]
snake_case: int = params["""n_heads"""]
snake_case: Optional[Any] = n_heads // num_shards
snake_case: Union[str, Any] = params["""dim"""]
snake_case: Union[str, Any] = dim // n_heads
snake_case: Dict = 10000.0
snake_case: Any = 1.0 / (base ** (torch.arange(0 , _lowerCAmelCase , 2 ).float() / dims_per_head))
if "n_kv_heads" in params:
snake_case: int = params["""n_kv_heads"""] # for GQA / MQA
snake_case: Any = n_heads_per_shard // num_key_value_heads
snake_case: Optional[int] = dim // num_key_value_heads
else: # compatibility with other checkpoints
snake_case: int = n_heads
snake_case: int = n_heads_per_shard
snake_case: Optional[int] = dim
# permute for sliced rotary
def permute(_lowerCAmelCase : Tuple , _lowerCAmelCase : Any=n_heads , _lowerCAmelCase : Union[str, Any]=dim , _lowerCAmelCase : List[str]=dim ):
return w.view(_lowerCAmelCase , dima // n_heads // 2 , 2 , _lowerCAmelCase ).transpose(1 , 2 ).reshape(_lowerCAmelCase , _lowerCAmelCase )
print(F"Fetching all parameters from the checkpoint at {input_base_path}." )
# Load weights
if model_size == "7B":
# Not sharded
# (The sharded implementation would also work, but this is simpler.)
snake_case: Tuple = torch.load(os.path.join(_lowerCAmelCase , """consolidated.00.pth""" ) , map_location="""cpu""" )
else:
# Sharded
snake_case: str = [
torch.load(os.path.join(_lowerCAmelCase , F"consolidated.{i:02d}.pth" ) , map_location="""cpu""" )
for i in range(_lowerCAmelCase )
]
snake_case: Optional[int] = 0
snake_case: str = {"""weight_map""": {}}
for layer_i in range(_lowerCAmelCase ):
snake_case: List[Any] = F"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin"
if model_size == "7B":
# Unsharded
snake_case: List[Any] = {
F"model.layers.{layer_i}.self_attn.q_proj.weight": permute(
loaded[F"layers.{layer_i}.attention.wq.weight"] ),
F"model.layers.{layer_i}.self_attn.k_proj.weight": permute(
loaded[F"layers.{layer_i}.attention.wk.weight"] ),
F"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[F"layers.{layer_i}.attention.wv.weight"],
F"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[F"layers.{layer_i}.attention.wo.weight"],
F"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w1.weight"],
F"model.layers.{layer_i}.mlp.down_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w2.weight"],
F"model.layers.{layer_i}.mlp.up_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w3.weight"],
F"model.layers.{layer_i}.input_layernorm.weight": loaded[F"layers.{layer_i}.attention_norm.weight"],
F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[F"layers.{layer_i}.ffn_norm.weight"],
}
else:
# Sharded
# Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share
# the same storage object, saving attention_norm and ffn_norm will save other weights too, which is
# redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned.
snake_case: List[str] = {
F"model.layers.{layer_i}.input_layernorm.weight": loaded[0][
F"layers.{layer_i}.attention_norm.weight"
].clone(),
F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][
F"layers.{layer_i}.ffn_norm.weight"
].clone(),
}
snake_case: Any = permute(
torch.cat(
[
loaded[i][F"layers.{layer_i}.attention.wq.weight"].view(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )
for i in range(_lowerCAmelCase )
] , dim=0 , ).reshape(_lowerCAmelCase , _lowerCAmelCase ) )
snake_case: Dict = permute(
torch.cat(
[
loaded[i][F"layers.{layer_i}.attention.wk.weight"].view(
_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )
for i in range(_lowerCAmelCase )
] , dim=0 , ).reshape(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , )
snake_case: str = torch.cat(
[
loaded[i][F"layers.{layer_i}.attention.wv.weight"].view(
_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )
for i in range(_lowerCAmelCase )
] , dim=0 , ).reshape(_lowerCAmelCase , _lowerCAmelCase )
snake_case: int = torch.cat(
[loaded[i][F"layers.{layer_i}.attention.wo.weight"] for i in range(_lowerCAmelCase )] , dim=1 )
snake_case: List[str] = torch.cat(
[loaded[i][F"layers.{layer_i}.feed_forward.w1.weight"] for i in range(_lowerCAmelCase )] , dim=0 )
snake_case: List[Any] = torch.cat(
[loaded[i][F"layers.{layer_i}.feed_forward.w2.weight"] for i in range(_lowerCAmelCase )] , dim=1 )
snake_case: Optional[int] = torch.cat(
[loaded[i][F"layers.{layer_i}.feed_forward.w3.weight"] for i in range(_lowerCAmelCase )] , dim=0 )
snake_case: List[Any] = inv_freq
for k, v in state_dict.items():
snake_case: List[Any] = filename
param_count += v.numel()
torch.save(_lowerCAmelCase , os.path.join(_lowerCAmelCase , _lowerCAmelCase ) )
snake_case: Tuple = F"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin"
if model_size == "7B":
# Unsharded
snake_case: str = {
"""model.embed_tokens.weight""": loaded["""tok_embeddings.weight"""],
"""model.norm.weight""": loaded["""norm.weight"""],
"""lm_head.weight""": loaded["""output.weight"""],
}
else:
snake_case: List[str] = {
"""model.norm.weight""": loaded[0]["""norm.weight"""],
"""model.embed_tokens.weight""": torch.cat(
[loaded[i]["""tok_embeddings.weight"""] for i in range(_lowerCAmelCase )] , dim=1 ),
"""lm_head.weight""": torch.cat([loaded[i]["""output.weight"""] for i in range(_lowerCAmelCase )] , dim=0 ),
}
for k, v in state_dict.items():
snake_case: List[Any] = filename
param_count += v.numel()
torch.save(_lowerCAmelCase , os.path.join(_lowerCAmelCase , _lowerCAmelCase ) )
# Write configs
snake_case: int = {"""total_size""": param_count * 2}
write_json(_lowerCAmelCase , os.path.join(_lowerCAmelCase , """pytorch_model.bin.index.json""" ) )
snake_case: int = params["""ffn_dim_multiplier"""] if """ffn_dim_multiplier""" in params else 1
snake_case: Dict = params["""multiple_of"""] if """multiple_of""" in params else 256
snake_case: List[Any] = LlamaConfig(
hidden_size=_lowerCAmelCase , intermediate_size=compute_intermediate_size(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) , num_attention_heads=params["""n_heads"""] , num_hidden_layers=params["""n_layers"""] , rms_norm_eps=params["""norm_eps"""] , num_key_value_heads=_lowerCAmelCase , )
config.save_pretrained(_lowerCAmelCase )
# Make space so we can load the model properly now.
del state_dict
del loaded
gc.collect()
print("""Loading the checkpoint in a Llama model.""" )
snake_case: Dict = LlamaForCausalLM.from_pretrained(_lowerCAmelCase , torch_dtype=torch.floataa , low_cpu_mem_usage=_lowerCAmelCase )
# Avoid saving this as part of the config.
del model.config._name_or_path
print("""Saving in the Transformers format.""" )
model.save_pretrained(_lowerCAmelCase , safe_serialization=_lowerCAmelCase )
shutil.rmtree(_lowerCAmelCase )
def a_ (_lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Optional[Any] )-> Tuple:
# Initialize the tokenizer based on the `spm` model
snake_case: Dict = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast
print(F"Saving a {tokenizer_class.__name__} to {tokenizer_path}." )
snake_case: Any = tokenizer_class(_lowerCAmelCase )
tokenizer.save_pretrained(_lowerCAmelCase )
def a_ ()-> int:
snake_case: List[Any] = argparse.ArgumentParser()
parser.add_argument(
"""--input_dir""" , help="""Location of LLaMA weights, which contains tokenizer.model and model folders""" , )
parser.add_argument(
"""--model_size""" , choices=["""7B""", """7Bf""", """13B""", """13Bf""", """30B""", """65B""", """70B""", """70Bf""", """tokenizer_only"""] , )
parser.add_argument(
"""--output_dir""" , help="""Location to write HF model and tokenizer""" , )
parser.add_argument("""--safe_serialization""" , type=_lowerCAmelCase , help="""Whether or not to save using `safetensors`.""" )
snake_case: Tuple = parser.parse_args()
if args.model_size != "tokenizer_only":
write_model(
model_path=args.output_dir , input_base_path=os.path.join(args.input_dir , args.model_size ) , model_size=args.model_size , safe_serialization=args.safe_serialization , )
snake_case: Dict = os.path.join(args.input_dir , """tokenizer.model""" )
write_tokenizer(args.output_dir , _lowerCAmelCase )
if __name__ == "__main__":
main()
| 704 |
import collections
import os
import re
from pathlib import Path
__lowerCAmelCase : Tuple = 'src/transformers'
# Matches is_xxx_available()
__lowerCAmelCase : Union[str, Any] = re.compile(R'is\_([a-z_]*)_available()')
# Catches a one-line _import_struct = {xxx}
__lowerCAmelCase : Dict = re.compile(R'^_import_structure\s+=\s+\{([^\}]+)\}')
# Catches a line with a key-values pattern: "bla": ["foo", "bar"]
__lowerCAmelCase : Union[str, Any] = re.compile(R'\s+"\S*":\s+\[([^\]]*)\]')
# Catches a line if not is_foo_available
__lowerCAmelCase : Optional[Any] = re.compile(R'^\s*if\s+not\s+is\_[a-z_]*\_available\(\)')
# Catches a line _import_struct["bla"].append("foo")
__lowerCAmelCase : str = re.compile(R'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)')
# Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"]
__lowerCAmelCase : List[str] = re.compile(R'^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]')
# Catches a line with an object between quotes and a comma: "MyModel",
__lowerCAmelCase : Optional[int] = re.compile(R'^\s+"([^"]+)",')
# Catches a line with objects between brackets only: ["foo", "bar"],
__lowerCAmelCase : Optional[int] = re.compile(R'^\s+\[([^\]]+)\]')
# Catches a line with from foo import bar, bla, boo
__lowerCAmelCase : Dict = re.compile(R'\s+from\s+\S*\s+import\s+([^\(\s].*)\n')
# Catches a line with try:
__lowerCAmelCase : Optional[int] = re.compile(R'^\s*try:')
# Catches a line with else:
__lowerCAmelCase : Optional[int] = re.compile(R'^\s*else:')
def a_ (_lowerCAmelCase : str )-> Optional[int]:
if _re_test_backend.search(_lowerCAmelCase ) is None:
return None
snake_case: Optional[Any] = [b[0] for b in _re_backend.findall(_lowerCAmelCase )]
backends.sort()
return "_and_".join(_lowerCAmelCase )
def a_ (_lowerCAmelCase : Union[str, Any] )-> Union[str, Any]:
with open(_lowerCAmelCase , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f:
snake_case: Dict = f.readlines()
snake_case: Optional[int] = 0
while line_index < len(_lowerCAmelCase ) and not lines[line_index].startswith("""_import_structure = {""" ):
line_index += 1
# If this is a traditional init, just return.
if line_index >= len(_lowerCAmelCase ):
return None
# First grab the objects without a specific backend in _import_structure
snake_case: Optional[Any] = []
while not lines[line_index].startswith("""if TYPE_CHECKING""" ) and find_backend(lines[line_index] ) is None:
snake_case: Any = lines[line_index]
# If we have everything on a single line, let's deal with it.
if _re_one_line_import_struct.search(_lowerCAmelCase ):
snake_case: int = _re_one_line_import_struct.search(_lowerCAmelCase ).groups()[0]
snake_case: Any = re.findall(R"""\[([^\]]+)\]""" , _lowerCAmelCase )
for imp in imports:
objects.extend([obj[1:-1] for obj in imp.split(""", """ )] )
line_index += 1
continue
snake_case: Union[str, Any] = _re_import_struct_key_value.search(_lowerCAmelCase )
if single_line_import_search is not None:
snake_case: Optional[int] = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(""", """ ) if len(_lowerCAmelCase ) > 0]
objects.extend(_lowerCAmelCase )
elif line.startswith(""" """ * 8 + """\"""" ):
objects.append(line[9:-3] )
line_index += 1
snake_case: int = {"""none""": objects}
# Let's continue with backend-specific objects in _import_structure
while not lines[line_index].startswith("""if TYPE_CHECKING""" ):
# If the line is an if not is_backend_available, we grab all objects associated.
snake_case: Optional[int] = find_backend(lines[line_index] )
# Check if the backend declaration is inside a try block:
if _re_try.search(lines[line_index - 1] ) is None:
snake_case: str = None
if backend is not None:
line_index += 1
# Scroll until we hit the else block of try-except-else
while _re_else.search(lines[line_index] ) is None:
line_index += 1
line_index += 1
snake_case: List[str] = []
# Until we unindent, add backend objects to the list
while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 4 ):
snake_case: Union[str, Any] = lines[line_index]
if _re_import_struct_add_one.search(_lowerCAmelCase ) is not None:
objects.append(_re_import_struct_add_one.search(_lowerCAmelCase ).groups()[0] )
elif _re_import_struct_add_many.search(_lowerCAmelCase ) is not None:
snake_case: Optional[int] = _re_import_struct_add_many.search(_lowerCAmelCase ).groups()[0].split(""", """ )
snake_case: str = [obj[1:-1] for obj in imports if len(_lowerCAmelCase ) > 0]
objects.extend(_lowerCAmelCase )
elif _re_between_brackets.search(_lowerCAmelCase ) is not None:
snake_case: Union[str, Any] = _re_between_brackets.search(_lowerCAmelCase ).groups()[0].split(""", """ )
snake_case: int = [obj[1:-1] for obj in imports if len(_lowerCAmelCase ) > 0]
objects.extend(_lowerCAmelCase )
elif _re_quote_object.search(_lowerCAmelCase ) is not None:
objects.append(_re_quote_object.search(_lowerCAmelCase ).groups()[0] )
elif line.startswith(""" """ * 8 + """\"""" ):
objects.append(line[9:-3] )
elif line.startswith(""" """ * 12 + """\"""" ):
objects.append(line[13:-3] )
line_index += 1
snake_case: List[str] = objects
else:
line_index += 1
# At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend
snake_case: Optional[Any] = []
while (
line_index < len(_lowerCAmelCase )
and find_backend(lines[line_index] ) is None
and not lines[line_index].startswith("""else""" )
):
snake_case: int = lines[line_index]
snake_case: str = _re_import.search(_lowerCAmelCase )
if single_line_import_search is not None:
objects.extend(single_line_import_search.groups()[0].split(""", """ ) )
elif line.startswith(""" """ * 8 ):
objects.append(line[8:-2] )
line_index += 1
snake_case: Union[str, Any] = {"""none""": objects}
# Let's continue with backend-specific objects
while line_index < len(_lowerCAmelCase ):
# If the line is an if is_backend_available, we grab all objects associated.
snake_case: Union[str, Any] = find_backend(lines[line_index] )
# Check if the backend declaration is inside a try block:
if _re_try.search(lines[line_index - 1] ) is None:
snake_case: List[str] = None
if backend is not None:
line_index += 1
# Scroll until we hit the else block of try-except-else
while _re_else.search(lines[line_index] ) is None:
line_index += 1
line_index += 1
snake_case: Tuple = []
# Until we unindent, add backend objects to the list
while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 8 ):
snake_case: List[str] = lines[line_index]
snake_case: str = _re_import.search(_lowerCAmelCase )
if single_line_import_search is not None:
objects.extend(single_line_import_search.groups()[0].split(""", """ ) )
elif line.startswith(""" """ * 12 ):
objects.append(line[12:-2] )
line_index += 1
snake_case: Tuple = objects
else:
line_index += 1
return import_dict_objects, type_hint_objects
def a_ (_lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Union[str, Any] )-> Optional[int]:
def find_duplicates(_lowerCAmelCase : Union[str, Any] ):
return [k for k, v in collections.Counter(_lowerCAmelCase ).items() if v > 1]
if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ):
return ["Both sides of the init do not have the same backends!"]
snake_case: Optional[Any] = []
for key in import_dict_objects.keys():
snake_case: List[str] = find_duplicates(import_dict_objects[key] )
if duplicate_imports:
errors.append(F"Duplicate _import_structure definitions for: {duplicate_imports}" )
snake_case: Optional[int] = find_duplicates(type_hint_objects[key] )
if duplicate_type_hints:
errors.append(F"Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}" )
if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ):
snake_case: Optional[Any] = """base imports""" if key == """none""" else F"{key} backend"
errors.append(F"Differences for {name}:" )
for a in type_hint_objects[key]:
if a not in import_dict_objects[key]:
errors.append(F" {a} in TYPE_HINT but not in _import_structure." )
for a in import_dict_objects[key]:
if a not in type_hint_objects[key]:
errors.append(F" {a} in _import_structure but not in TYPE_HINT." )
return errors
def a_ ()-> int:
snake_case: Optional[int] = []
for root, _, files in os.walk(_lowerCAmelCase ):
if "__init__.py" in files:
snake_case: Optional[int] = os.path.join(_lowerCAmelCase , """__init__.py""" )
snake_case: Any = parse_init(_lowerCAmelCase )
if objects is not None:
snake_case: List[str] = analyze_results(*_lowerCAmelCase )
if len(_lowerCAmelCase ) > 0:
snake_case: Optional[int] = F"Problem in {fname}, both halves do not define the same objects.\n{errors[0]}"
failures.append("""\n""".join(_lowerCAmelCase ) )
if len(_lowerCAmelCase ) > 0:
raise ValueError("""\n\n""".join(_lowerCAmelCase ) )
def a_ ()-> Dict:
snake_case: Any = []
for path, directories, files in os.walk(_lowerCAmelCase ):
for folder in directories:
# Ignore private modules
if folder.startswith("""_""" ):
directories.remove(_lowerCAmelCase )
continue
# Ignore leftovers from branches (empty folders apart from pycache)
if len(list((Path(_lowerCAmelCase ) / folder).glob("""*.py""" ) ) ) == 0:
continue
snake_case: Optional[int] = str((Path(_lowerCAmelCase ) / folder).relative_to(_lowerCAmelCase ) )
snake_case: str = short_path.replace(os.path.sep , """.""" )
submodules.append(_lowerCAmelCase )
for fname in files:
if fname == "__init__.py":
continue
snake_case: Union[str, Any] = str((Path(_lowerCAmelCase ) / fname).relative_to(_lowerCAmelCase ) )
snake_case: List[Any] = short_path.replace(""".py""" , """""" ).replace(os.path.sep , """.""" )
if len(submodule.split(""".""" ) ) == 1:
submodules.append(_lowerCAmelCase )
return submodules
__lowerCAmelCase : Optional[int] = [
'convert_pytorch_checkpoint_to_tf2',
'modeling_flax_pytorch_utils',
'models.esm.openfold_utils',
]
def a_ ()-> Dict:
# This is to make sure the transformers module imported is the one in the repo.
from transformers.utils import direct_transformers_import
snake_case: Union[str, Any] = direct_transformers_import(_lowerCAmelCase )
snake_case: str = set(transformers._import_structure.keys() )
# This contains all the base keys of the _import_structure object defined in the init, but if the user is missing
# some optional dependencies, they may not have all of them. Thus we read the init to read all additions and
# (potentiall re-) add them.
with open(os.path.join(_lowerCAmelCase , """__init__.py""" ) , """r""" ) as f:
snake_case: Optional[int] = f.read()
import_structure_keys.update(set(re.findall(R"""import_structure\[\"([^\"]*)\"\]""" , _lowerCAmelCase ) ) )
snake_case: Any = [
module
for module in get_transformers_submodules()
if module not in IGNORE_SUBMODULES and module not in import_structure_keys
]
if len(_lowerCAmelCase ) > 0:
snake_case: Any = """\n""".join(F"- {module}" for module in module_not_registered )
raise ValueError(
"""The following submodules are not properly registed in the main init of Transformers:\n"""
F"{list_of_modules}\n"
"""Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.""" )
if __name__ == "__main__":
check_all_inits()
check_submodules()
| 164 | 0 |
def _snake_case ( __snake_case , __snake_case ):
return "\n".join(
f"""{number} * {i} = {number * i}""" for i in range(1 , number_of_terms + 1 ) )
if __name__ == "__main__":
print(multiplication_table(number=5, number_of_terms=10))
| 10 |
'''simple docstring'''
import warnings
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
UpperCAmelCase_ = logging.get_logger(__name__)
UpperCAmelCase_ = {
"nvidia/segformer-b0-finetuned-ade-512-512": (
"https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json"
),
# See all SegFormer models at https://huggingface.co/models?filter=segformer
}
class __lowercase ( __magic_name__ ):
_a = """segformer"""
def __init__( self , UpperCamelCase=3 , UpperCamelCase=4 , UpperCamelCase=[2, 2, 2, 2] , UpperCamelCase=[8, 4, 2, 1] , UpperCamelCase=[32, 64, 160, 256] , UpperCamelCase=[7, 3, 3, 3] , UpperCamelCase=[4, 2, 2, 2] , UpperCamelCase=[1, 2, 5, 8] , UpperCamelCase=[4, 4, 4, 4] , UpperCamelCase="gelu" , UpperCamelCase=0.0 , UpperCamelCase=0.0 , UpperCamelCase=0.1 , UpperCamelCase=0.02 , UpperCamelCase=0.1 , UpperCamelCase=1e-6 , UpperCamelCase=256 , UpperCamelCase=255 , **UpperCamelCase , ) -> int:
super().__init__(**UpperCamelCase )
if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False:
warnings.warn(
'Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be'
' removed, as the behaviour will default to that of reshape_last_stage = True.' , UpperCamelCase , )
__a = num_channels
__a = num_encoder_blocks
__a = depths
__a = sr_ratios
__a = hidden_sizes
__a = patch_sizes
__a = strides
__a = mlp_ratios
__a = num_attention_heads
__a = hidden_act
__a = hidden_dropout_prob
__a = attention_probs_dropout_prob
__a = classifier_dropout_prob
__a = initializer_range
__a = drop_path_rate
__a = layer_norm_eps
__a = decoder_hidden_size
__a = kwargs.get('reshape_last_stage' , UpperCamelCase )
__a = semantic_loss_ignore_index
class __lowercase ( __magic_name__ ):
_a = version.parse("""1.11""" )
@property
def UpperCamelCase__ ( self ) -> Mapping[str, Mapping[int, str]]:
return OrderedDict(
[
('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
] )
@property
def UpperCamelCase__ ( self ) -> float:
return 1e-4
@property
def UpperCamelCase__ ( self ) -> int:
return 12
| 539 | 0 |
"""simple docstring"""
from __future__ import annotations
UpperCAmelCase : Dict = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0]
UpperCAmelCase : Optional[Any] = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1]
def __a ( _lowercase ):
"""simple docstring"""
lowerCamelCase__ : Tuple = []
lowerCamelCase__ : Tuple = len(_lowercase )
for i in range(_lowercase ):
lowerCamelCase__ : float = -1
for j in range(i + 1 , _lowercase ):
if arr[i] < arr[j]:
lowerCamelCase__ : int = arr[j]
break
result.append(_lowercase )
return result
def __a ( _lowercase ):
"""simple docstring"""
lowerCamelCase__ : Optional[int] = []
for i, outer in enumerate(_lowercase ):
lowerCamelCase__ : float = -1
for inner in arr[i + 1 :]:
if outer < inner:
lowerCamelCase__ : List[str] = inner
break
result.append(_lowercase )
return result
def __a ( _lowercase ):
"""simple docstring"""
lowerCamelCase__ : Tuple = len(_lowercase )
lowerCamelCase__ : list[float] = []
lowerCamelCase__ : list[float] = [-1] * arr_size
for index in reversed(range(_lowercase ) ):
if stack:
while stack[-1] <= arr[index]:
stack.pop()
if not stack:
break
if stack:
lowerCamelCase__ : List[Any] = stack[-1]
stack.append(arr[index] )
return result
if __name__ == "__main__":
from doctest import testmod
from timeit import timeit
testmod()
print(next_greatest_element_slow(arr))
print(next_greatest_element_fast(arr))
print(next_greatest_element(arr))
UpperCAmelCase : Union[str, Any] = (
"from __main__ import arr, next_greatest_element_slow, "
"next_greatest_element_fast, next_greatest_element"
)
print(
"next_greatest_element_slow():",
timeit("next_greatest_element_slow(arr)", setup=setup),
)
print(
"next_greatest_element_fast():",
timeit("next_greatest_element_fast(arr)", setup=setup),
)
print(
" next_greatest_element():",
timeit("next_greatest_element(arr)", setup=setup),
)
| 706 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
UpperCAmelCase : str = {
"configuration_deberta": ["DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP", "DebertaConfig", "DebertaOnnxConfig"],
"tokenization_deberta": ["DebertaTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase : Optional[Any] = ["DebertaTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase : Union[str, Any] = [
"DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST",
"DebertaForMaskedLM",
"DebertaForQuestionAnswering",
"DebertaForSequenceClassification",
"DebertaForTokenClassification",
"DebertaModel",
"DebertaPreTrainedModel",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase : Dict = [
"TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFDebertaForMaskedLM",
"TFDebertaForQuestionAnswering",
"TFDebertaForSequenceClassification",
"TFDebertaForTokenClassification",
"TFDebertaModel",
"TFDebertaPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig
from .tokenization_deberta import DebertaTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_deberta_fast import DebertaTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_deberta import (
DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
DebertaForMaskedLM,
DebertaForQuestionAnswering,
DebertaForSequenceClassification,
DebertaForTokenClassification,
DebertaModel,
DebertaPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_deberta import (
TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
TFDebertaForMaskedLM,
TFDebertaForQuestionAnswering,
TFDebertaForSequenceClassification,
TFDebertaForTokenClassification,
TFDebertaModel,
TFDebertaPreTrainedModel,
)
else:
import sys
UpperCAmelCase : List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 121 | 0 |
import argparse
import glob
import logging
import os
from argparse import Namespace
from importlib import import_module
import numpy as np
import torch
from lightning_base import BaseTransformer, add_generic_args, generic_train
from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score
from torch.nn import CrossEntropyLoss
from torch.utils.data import DataLoader, TensorDataset
from utils_ner import TokenClassificationTask
a : Tuple = logging.getLogger(__name__)
class _a ( _lowerCAmelCase ):
A = '''token-classification'''
def __init__(self, SCREAMING_SNAKE_CASE_ ) -> List[str]:
if type(SCREAMING_SNAKE_CASE_ ) == dict:
UpperCAmelCase_: Optional[Any] = Namespace(**SCREAMING_SNAKE_CASE_ )
UpperCAmelCase_: Any = import_module("""tasks""" )
try:
UpperCAmelCase_: Any = getattr(SCREAMING_SNAKE_CASE_, hparams.task_type )
UpperCAmelCase_: TokenClassificationTask = token_classification_task_clazz()
except AttributeError:
raise ValueError(
f'Task {hparams.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. '
f'Available tasks classes are: {TokenClassificationTask.__subclasses__()}' )
UpperCAmelCase_: Union[str, Any] = self.token_classification_task.get_labels(hparams.labels )
UpperCAmelCase_: Optional[int] = CrossEntropyLoss().ignore_index
super().__init__(SCREAMING_SNAKE_CASE_, len(self.labels ), self.mode )
def __snake_case (self, **SCREAMING_SNAKE_CASE_ ) -> List[Any]:
return self.model(**SCREAMING_SNAKE_CASE_ )
def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> Optional[Any]:
UpperCAmelCase_: int = {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]}
if self.config.model_type != "distilbert":
UpperCAmelCase_: Optional[Any] = (
batch[2] if self.config.model_type in ["""bert""", """xlnet"""] else None
) # XLM and RoBERTa don"t use token_type_ids
UpperCAmelCase_: int = self(**SCREAMING_SNAKE_CASE_ )
UpperCAmelCase_: Optional[Any] = outputs[0]
# tensorboard_logs = {"loss": loss, "rate": self.lr_scheduler.get_last_lr()[-1]}
return {"loss": loss}
def __snake_case (self ) -> Dict:
UpperCAmelCase_: Optional[int] = self.hparams
for mode in ["train", "dev", "test"]:
UpperCAmelCase_: Tuple = self._feature_file(SCREAMING_SNAKE_CASE_ )
if os.path.exists(SCREAMING_SNAKE_CASE_ ) and not args.overwrite_cache:
logger.info("""Loading features from cached file %s""", SCREAMING_SNAKE_CASE_ )
UpperCAmelCase_: Any = torch.load(SCREAMING_SNAKE_CASE_ )
else:
logger.info("""Creating features from dataset file at %s""", args.data_dir )
UpperCAmelCase_: str = self.token_classification_task.read_examples_from_file(args.data_dir, SCREAMING_SNAKE_CASE_ )
UpperCAmelCase_: Optional[int] = self.token_classification_task.convert_examples_to_features(
SCREAMING_SNAKE_CASE_, self.labels, args.max_seq_length, self.tokenizer, cls_token_at_end=bool(self.config.model_type in ["""xlnet"""] ), cls_token=self.tokenizer.cls_token, cls_token_segment_id=2 if self.config.model_type in ["""xlnet"""] else 0, sep_token=self.tokenizer.sep_token, sep_token_extra=SCREAMING_SNAKE_CASE_, pad_on_left=bool(self.config.model_type in ["""xlnet"""] ), pad_token=self.tokenizer.pad_token_id, pad_token_segment_id=self.tokenizer.pad_token_type_id, pad_token_label_id=self.pad_token_label_id, )
logger.info("""Saving features into cached file %s""", SCREAMING_SNAKE_CASE_ )
torch.save(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ )
def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = False ) -> DataLoader:
UpperCAmelCase_: List[Any] = self._feature_file(SCREAMING_SNAKE_CASE_ )
logger.info("""Loading features from cached file %s""", SCREAMING_SNAKE_CASE_ )
UpperCAmelCase_: Optional[Any] = torch.load(SCREAMING_SNAKE_CASE_ )
UpperCAmelCase_: Optional[Any] = torch.tensor([f.input_ids for f in features], dtype=torch.long )
UpperCAmelCase_: Union[str, Any] = torch.tensor([f.attention_mask for f in features], dtype=torch.long )
if features[0].token_type_ids is not None:
UpperCAmelCase_: List[Any] = torch.tensor([f.token_type_ids for f in features], dtype=torch.long )
else:
UpperCAmelCase_: List[str] = torch.tensor([0 for f in features], dtype=torch.long )
# HACK(we will not use this anymore soon)
UpperCAmelCase_: Union[str, Any] = torch.tensor([f.label_ids for f in features], dtype=torch.long )
return DataLoader(
TensorDataset(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ), batch_size=SCREAMING_SNAKE_CASE_ )
def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> int:
"""Compute validation""" ""
UpperCAmelCase_: Any = {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]}
if self.config.model_type != "distilbert":
UpperCAmelCase_: Tuple = (
batch[2] if self.config.model_type in ["""bert""", """xlnet"""] else None
) # XLM and RoBERTa don"t use token_type_ids
UpperCAmelCase_: int = self(**SCREAMING_SNAKE_CASE_ )
UpperCAmelCase_ , UpperCAmelCase_: List[str] = outputs[:2]
UpperCAmelCase_: Any = logits.detach().cpu().numpy()
UpperCAmelCase_: int = inputs["""labels"""].detach().cpu().numpy()
return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids}
def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]:
UpperCAmelCase_: Any = torch.stack([x["""val_loss"""] for x in outputs] ).mean()
UpperCAmelCase_: Union[str, Any] = np.concatenate([x["""pred"""] for x in outputs], axis=0 )
UpperCAmelCase_: Any = np.argmax(SCREAMING_SNAKE_CASE_, axis=2 )
UpperCAmelCase_: Optional[Any] = np.concatenate([x["""target"""] for x in outputs], axis=0 )
UpperCAmelCase_: Optional[Any] = dict(enumerate(self.labels ) )
UpperCAmelCase_: Union[str, Any] = [[] for _ in range(out_label_ids.shape[0] )]
UpperCAmelCase_: List[Any] = [[] for _ in range(out_label_ids.shape[0] )]
for i in range(out_label_ids.shape[0] ):
for j in range(out_label_ids.shape[1] ):
if out_label_ids[i, j] != self.pad_token_label_id:
out_label_list[i].append(label_map[out_label_ids[i][j]] )
preds_list[i].append(label_map[preds[i][j]] )
UpperCAmelCase_: Optional[int] = {
"""val_loss""": val_loss_mean,
"""accuracy_score""": accuracy_score(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ),
"""precision""": precision_score(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ),
"""recall""": recall_score(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ),
"""f1""": fa_score(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ),
}
UpperCAmelCase_: Optional[int] = dict(results.items() )
UpperCAmelCase_: str = results
return ret, preds_list, out_label_list
def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> Dict:
# when stable
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_: List[str] = self._eval_end(SCREAMING_SNAKE_CASE_ )
UpperCAmelCase_: Optional[int] = ret["""log"""]
return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs}
def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]:
# updating to test_epoch_end instead of deprecated test_end
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_: Optional[Any] = self._eval_end(SCREAMING_SNAKE_CASE_ )
# Converting to the dict required by pl
# https://github.com/PyTorchLightning/pytorch-lightning/blob/master/\
# pytorch_lightning/trainer/logging.py#L139
UpperCAmelCase_: Optional[Any] = ret["""log"""]
# `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss`
return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs}
@staticmethod
def __snake_case (SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]:
# Add NER specific options
BaseTransformer.add_model_specific_args(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ )
parser.add_argument(
"""--task_type""", default="""NER""", type=SCREAMING_SNAKE_CASE_, help="""Task type to fine tune in training (e.g. NER, POS, etc)""" )
parser.add_argument(
"""--max_seq_length""", default=128, type=SCREAMING_SNAKE_CASE_, help=(
"""The maximum total input sequence length after tokenization. Sequences longer """
"""than this will be truncated, sequences shorter will be padded."""
), )
parser.add_argument(
"""--labels""", default="""""", type=SCREAMING_SNAKE_CASE_, help="""Path to a file containing all labels. If not specified, CoNLL-2003 labels are used.""", )
parser.add_argument(
"""--gpus""", default=0, type=SCREAMING_SNAKE_CASE_, help="""The number of GPUs allocated for this, it is by default 0 meaning none""", )
parser.add_argument(
"""--overwrite_cache""", action="""store_true""", help="""Overwrite the cached training and evaluation sets""" )
return parser
if __name__ == "__main__":
a : Optional[Any] = argparse.ArgumentParser()
add_generic_args(parser, os.getcwd())
a : List[Any] = NERTransformer.add_model_specific_args(parser, os.getcwd())
a : List[str] = parser.parse_args()
a : Tuple = NERTransformer(args)
a : Any = generic_train(model, args)
if args.do_predict:
# See https://github.com/huggingface/transformers/issues/3159
# pl use this default format to create a checkpoint:
# https://github.com/PyTorchLightning/pytorch-lightning/blob/master\
# /pytorch_lightning/callbacks/model_checkpoint.py#L322
a : Optional[int] = sorted(glob.glob(os.path.join(args.output_dir, 'checkpoint-epoch=*.ckpt'), recursive=True))
a : str = model.load_from_checkpoint(checkpoints[-1])
trainer.test(model)
| 556 |
import logging
import os
from dataclasses import dataclass
from typing import List, Optional, Union
import tqdm
from filelock import FileLock
from transformers import (
BartTokenizer,
BartTokenizerFast,
DataProcessor,
PreTrainedTokenizer,
RobertaTokenizer,
RobertaTokenizerFast,
XLMRobertaTokenizer,
is_tf_available,
is_torch_available,
)
a : Optional[Any] = logging.getLogger(__name__)
@dataclass(frozen=_lowerCAmelCase )
class _a :
A = 42
A = 42
A = None
A = None
A = None
@dataclass(frozen=_lowerCAmelCase )
class _a :
A = 42
A = None
A = None
A = None
A = None
if is_torch_available():
import torch
from torch.utils.data import Dataset
class _a ( _lowerCAmelCase ):
A = 42
def __init__(self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_=False, SCREAMING_SNAKE_CASE_ = False, ) -> Union[str, Any]:
UpperCAmelCase_: Optional[Any] = hans_processors[task]()
UpperCAmelCase_: Dict = os.path.join(
SCREAMING_SNAKE_CASE_, """cached_{}_{}_{}_{}""".format(
"""dev""" if evaluate else """train""", tokenizer.__class__.__name__, str(SCREAMING_SNAKE_CASE_ ), SCREAMING_SNAKE_CASE_, ), )
UpperCAmelCase_: Dict = processor.get_labels()
if tokenizer.__class__ in (
RobertaTokenizer,
RobertaTokenizerFast,
XLMRobertaTokenizer,
BartTokenizer,
BartTokenizerFast,
):
# HACK(label indices are swapped in RoBERTa pretrained model)
UpperCAmelCase_ , UpperCAmelCase_: Tuple = label_list[2], label_list[1]
UpperCAmelCase_: str = label_list
# Make sure only the first process in distributed training processes the dataset,
# and the others will use the cache.
UpperCAmelCase_: int = cached_features_file + """.lock"""
with FileLock(SCREAMING_SNAKE_CASE_ ):
if os.path.exists(SCREAMING_SNAKE_CASE_ ) and not overwrite_cache:
logger.info(f'Loading features from cached file {cached_features_file}' )
UpperCAmelCase_: Dict = torch.load(SCREAMING_SNAKE_CASE_ )
else:
logger.info(f'Creating features from dataset file at {data_dir}' )
UpperCAmelCase_: Union[str, Any] = (
processor.get_dev_examples(SCREAMING_SNAKE_CASE_ ) if evaluate else processor.get_train_examples(SCREAMING_SNAKE_CASE_ )
)
logger.info("""Training examples: %s""", len(SCREAMING_SNAKE_CASE_ ) )
UpperCAmelCase_: List[Any] = hans_convert_examples_to_features(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ )
logger.info("""Saving features into cached file %s""", SCREAMING_SNAKE_CASE_ )
torch.save(self.features, SCREAMING_SNAKE_CASE_ )
def __len__(self ) -> Optional[int]:
return len(self.features )
def __getitem__(self, SCREAMING_SNAKE_CASE_ ) -> InputFeatures:
return self.features[i]
def __snake_case (self ) -> List[str]:
return self.label_list
if is_tf_available():
import tensorflow as tf
class _a :
A = 42
def __init__(self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = 128, SCREAMING_SNAKE_CASE_=False, SCREAMING_SNAKE_CASE_ = False, ) -> Optional[int]:
UpperCAmelCase_: Union[str, Any] = hans_processors[task]()
UpperCAmelCase_: List[Any] = processor.get_labels()
if tokenizer.__class__ in (
RobertaTokenizer,
RobertaTokenizerFast,
XLMRobertaTokenizer,
BartTokenizer,
BartTokenizerFast,
):
# HACK(label indices are swapped in RoBERTa pretrained model)
UpperCAmelCase_ , UpperCAmelCase_: List[str] = label_list[2], label_list[1]
UpperCAmelCase_: Dict = label_list
UpperCAmelCase_: List[str] = processor.get_dev_examples(SCREAMING_SNAKE_CASE_ ) if evaluate else processor.get_train_examples(SCREAMING_SNAKE_CASE_ )
UpperCAmelCase_: Any = hans_convert_examples_to_features(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ )
def gen():
for ex_index, ex in tqdm.tqdm(enumerate(self.features ), desc="""convert examples to features""" ):
if ex_index % 10000 == 0:
logger.info("""Writing example %d of %d""" % (ex_index, len(SCREAMING_SNAKE_CASE_ )) )
yield (
{
"example_id": 0,
"input_ids": ex.input_ids,
"attention_mask": ex.attention_mask,
"token_type_ids": ex.token_type_ids,
},
ex.label,
)
UpperCAmelCase_: List[str] = tf.data.Dataset.from_generator(
SCREAMING_SNAKE_CASE_, (
{
"""example_id""": tf.intaa,
"""input_ids""": tf.intaa,
"""attention_mask""": tf.intaa,
"""token_type_ids""": tf.intaa,
},
tf.intaa,
), (
{
"""example_id""": tf.TensorShape([] ),
"""input_ids""": tf.TensorShape([None, None] ),
"""attention_mask""": tf.TensorShape([None, None] ),
"""token_type_ids""": tf.TensorShape([None, None] ),
},
tf.TensorShape([] ),
), )
def __snake_case (self ) -> Optional[Any]:
return self.dataset
def __len__(self ) -> Optional[int]:
return len(self.features )
def __getitem__(self, SCREAMING_SNAKE_CASE_ ) -> InputFeatures:
return self.features[i]
def __snake_case (self ) -> Union[str, Any]:
return self.label_list
class _a ( _lowerCAmelCase ):
def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> Dict:
return self._create_examples(self._read_tsv(os.path.join(SCREAMING_SNAKE_CASE_, """heuristics_train_set.txt""" ) ), """train""" )
def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> Dict:
return self._create_examples(self._read_tsv(os.path.join(SCREAMING_SNAKE_CASE_, """heuristics_evaluation_set.txt""" ) ), """dev""" )
def __snake_case (self ) -> Optional[int]:
return ["contradiction", "entailment", "neutral"]
def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> List[Any]:
UpperCAmelCase_: Optional[Any] = []
for i, line in enumerate(SCREAMING_SNAKE_CASE_ ):
if i == 0:
continue
UpperCAmelCase_: Tuple = """%s-%s""" % (set_type, line[0])
UpperCAmelCase_: int = line[5]
UpperCAmelCase_: int = line[6]
UpperCAmelCase_: List[str] = line[7][2:] if line[7].startswith("""ex""" ) else line[7]
UpperCAmelCase_: Any = line[0]
examples.append(InputExample(guid=SCREAMING_SNAKE_CASE_, text_a=SCREAMING_SNAKE_CASE_, text_b=SCREAMING_SNAKE_CASE_, label=SCREAMING_SNAKE_CASE_, pairID=SCREAMING_SNAKE_CASE_ ) )
return examples
def lowerCAmelCase_ (lowerCAmelCase__: List[InputExample] , lowerCAmelCase__: List[str] , lowerCAmelCase__: int , lowerCAmelCase__: PreTrainedTokenizer , ):
"""simple docstring"""
UpperCAmelCase_: List[str] = {label: i for i, label in enumerate(lowerCAmelCase__ )}
UpperCAmelCase_: Optional[int] = []
for ex_index, example in tqdm.tqdm(enumerate(lowerCAmelCase__ ) , desc="""convert examples to features""" ):
if ex_index % 1_0_0_0_0 == 0:
logger.info("""Writing example %d""" % (ex_index) )
UpperCAmelCase_: Tuple = tokenizer(
example.text_a , example.text_b , add_special_tokens=lowerCAmelCase__ , max_length=lowerCAmelCase__ , padding="""max_length""" , truncation=lowerCAmelCase__ , return_overflowing_tokens=lowerCAmelCase__ , )
UpperCAmelCase_: Optional[Any] = label_map[example.label] if example.label in label_map else 0
UpperCAmelCase_: Tuple = int(example.pairID )
features.append(InputFeatures(**lowerCAmelCase__ , label=lowerCAmelCase__ , pairID=lowerCAmelCase__ ) )
for i, example in enumerate(examples[:5] ):
logger.info("""*** Example ***""" )
logger.info(F'guid: {example}' )
logger.info(F'features: {features[i]}' )
return features
a : Optional[int] = {
'hans': 3,
}
a : Dict = {
'hans': HansProcessor,
}
| 556 | 1 |
import torch
from diffusers import DDPMScheduler
from .test_schedulers import SchedulerCommonTest
class _A ( UpperCAmelCase_):
SCREAMING_SNAKE_CASE : int = (DDPMScheduler,)
def UpperCAmelCase ( self , **_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ : Dict = {
'num_train_timesteps': 1000,
'beta_start': 0.0001,
'beta_end': 0.02,
'beta_schedule': 'linear',
'variance_type': 'fixed_small',
'clip_sample': True,
}
config.update(**_snake_case )
return config
def UpperCAmelCase ( self ):
for timesteps in [1, 5, 100, 1000]:
self.check_over_configs(num_train_timesteps=_snake_case )
def UpperCAmelCase ( self ):
for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ):
self.check_over_configs(beta_start=_snake_case , beta_end=_snake_case )
def UpperCAmelCase ( self ):
for schedule in ["linear", "squaredcos_cap_v2"]:
self.check_over_configs(beta_schedule=_snake_case )
def UpperCAmelCase ( self ):
for variance in ["fixed_small", "fixed_large", "other"]:
self.check_over_configs(variance_type=_snake_case )
def UpperCAmelCase ( self ):
for clip_sample in [True, False]:
self.check_over_configs(clip_sample=_snake_case )
def UpperCAmelCase ( self ):
self.check_over_configs(thresholding=_snake_case )
for threshold in [0.5, 1.0, 2.0]:
for prediction_type in ["epsilon", "sample", "v_prediction"]:
self.check_over_configs(
thresholding=_snake_case , prediction_type=_snake_case , sample_max_value=_snake_case , )
def UpperCAmelCase ( self ):
for prediction_type in ["epsilon", "sample", "v_prediction"]:
self.check_over_configs(prediction_type=_snake_case )
def UpperCAmelCase ( self ):
for t in [0, 500, 999]:
self.check_over_forward(time_step=_snake_case )
def UpperCAmelCase ( self ):
SCREAMING_SNAKE_CASE_ : List[str] = self.scheduler_classes[0]
SCREAMING_SNAKE_CASE_ : List[Any] = self.get_scheduler_config()
SCREAMING_SNAKE_CASE_ : int = scheduler_class(**_snake_case )
assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1e-5
assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.00979 ) ) < 1e-5
assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.02 ) ) < 1e-5
def UpperCAmelCase ( self ):
SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.scheduler_classes[0]
SCREAMING_SNAKE_CASE_ : List[str] = self.get_scheduler_config()
SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler_class(**_snake_case )
SCREAMING_SNAKE_CASE_ : Tuple = len(_snake_case )
SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_model()
SCREAMING_SNAKE_CASE_ : Tuple = self.dummy_sample_deter
SCREAMING_SNAKE_CASE_ : List[str] = torch.manual_seed(0 )
for t in reversed(range(_snake_case ) ):
# 1. predict noise residual
SCREAMING_SNAKE_CASE_ : List[str] = model(_snake_case , _snake_case )
# 2. predict previous mean of sample x_t-1
SCREAMING_SNAKE_CASE_ : Dict = scheduler.step(_snake_case , _snake_case , _snake_case , generator=_snake_case ).prev_sample
# if t > 0:
# noise = self.dummy_sample_deter
# variance = scheduler.get_variance(t) ** (0.5) * noise
#
# sample = pred_prev_sample + variance
SCREAMING_SNAKE_CASE_ : str = pred_prev_sample
SCREAMING_SNAKE_CASE_ : int = torch.sum(torch.abs(_snake_case ) )
SCREAMING_SNAKE_CASE_ : int = torch.mean(torch.abs(_snake_case ) )
assert abs(result_sum.item() - 258.9606 ) < 1e-2
assert abs(result_mean.item() - 0.3372 ) < 1e-3
def UpperCAmelCase ( self ):
SCREAMING_SNAKE_CASE_ : Any = self.scheduler_classes[0]
SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_scheduler_config(prediction_type='v_prediction' )
SCREAMING_SNAKE_CASE_ : Any = scheduler_class(**_snake_case )
SCREAMING_SNAKE_CASE_ : List[str] = len(_snake_case )
SCREAMING_SNAKE_CASE_ : str = self.dummy_model()
SCREAMING_SNAKE_CASE_ : Tuple = self.dummy_sample_deter
SCREAMING_SNAKE_CASE_ : Any = torch.manual_seed(0 )
for t in reversed(range(_snake_case ) ):
# 1. predict noise residual
SCREAMING_SNAKE_CASE_ : Tuple = model(_snake_case , _snake_case )
# 2. predict previous mean of sample x_t-1
SCREAMING_SNAKE_CASE_ : int = scheduler.step(_snake_case , _snake_case , _snake_case , generator=_snake_case ).prev_sample
# if t > 0:
# noise = self.dummy_sample_deter
# variance = scheduler.get_variance(t) ** (0.5) * noise
#
# sample = pred_prev_sample + variance
SCREAMING_SNAKE_CASE_ : List[str] = pred_prev_sample
SCREAMING_SNAKE_CASE_ : Tuple = torch.sum(torch.abs(_snake_case ) )
SCREAMING_SNAKE_CASE_ : int = torch.mean(torch.abs(_snake_case ) )
assert abs(result_sum.item() - 202.0296 ) < 1e-2
assert abs(result_mean.item() - 0.2631 ) < 1e-3
def UpperCAmelCase ( self ):
SCREAMING_SNAKE_CASE_ : Optional[Any] = self.scheduler_classes[0]
SCREAMING_SNAKE_CASE_ : Tuple = self.get_scheduler_config()
SCREAMING_SNAKE_CASE_ : List[str] = scheduler_class(**_snake_case )
SCREAMING_SNAKE_CASE_ : Optional[Any] = [100, 87, 50, 1, 0]
scheduler.set_timesteps(timesteps=_snake_case )
SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler.timesteps
for i, timestep in enumerate(_snake_case ):
if i == len(_snake_case ) - 1:
SCREAMING_SNAKE_CASE_ : Optional[Any] = -1
else:
SCREAMING_SNAKE_CASE_ : int = timesteps[i + 1]
SCREAMING_SNAKE_CASE_ : Union[str, Any] = scheduler.previous_timestep(_snake_case )
SCREAMING_SNAKE_CASE_ : List[str] = prev_t.item()
self.assertEqual(_snake_case , _snake_case )
def UpperCAmelCase ( self ):
SCREAMING_SNAKE_CASE_ : List[Any] = self.scheduler_classes[0]
SCREAMING_SNAKE_CASE_ : List[Any] = self.get_scheduler_config()
SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler_class(**_snake_case )
SCREAMING_SNAKE_CASE_ : List[Any] = [100, 87, 50, 51, 0]
with self.assertRaises(_snake_case , msg='`custom_timesteps` must be in descending order.' ):
scheduler.set_timesteps(timesteps=_snake_case )
def UpperCAmelCase ( self ):
SCREAMING_SNAKE_CASE_ : List[str] = self.scheduler_classes[0]
SCREAMING_SNAKE_CASE_ : int = self.get_scheduler_config()
SCREAMING_SNAKE_CASE_ : int = scheduler_class(**_snake_case )
SCREAMING_SNAKE_CASE_ : Any = [100, 87, 50, 1, 0]
SCREAMING_SNAKE_CASE_ : Any = len(_snake_case )
with self.assertRaises(_snake_case , msg='Can only pass one of `num_inference_steps` or `custom_timesteps`.' ):
scheduler.set_timesteps(num_inference_steps=_snake_case , timesteps=_snake_case )
def UpperCAmelCase ( self ):
SCREAMING_SNAKE_CASE_ : Tuple = self.scheduler_classes[0]
SCREAMING_SNAKE_CASE_ : List[str] = self.get_scheduler_config()
SCREAMING_SNAKE_CASE_ : Dict = scheduler_class(**_snake_case )
SCREAMING_SNAKE_CASE_ : str = [scheduler.config.num_train_timesteps]
with self.assertRaises(
_snake_case , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ):
scheduler.set_timesteps(timesteps=_snake_case )
| 708 |
import argparse
from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta
from transformers.utils import logging
logging.set_verbosity_info()
def A_ ( a , a , a ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : int = TaConfig.from_json_file(a )
print(f"Building PyTorch model from configuration: {config}" )
SCREAMING_SNAKE_CASE_ : Tuple = TaForConditionalGeneration(a )
# Load weights from tf checkpoint
load_tf_weights_in_ta(a , a , a )
# Save pytorch-model
print(f"Save PyTorch model to {pytorch_dump_path}" )
model.save_pretrained(a )
if __name__ == "__main__":
lowerCAmelCase : int = 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.'
)
lowerCAmelCase : List[str] = parser.parse_args()
convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
| 353 | 0 |
"""simple docstring"""
import numpy as np
a_ : Optional[int] = [
['''a''', '''b''', '''c''', '''d''', '''e'''],
['''f''', '''g''', '''h''', '''i''', '''k'''],
['''l''', '''m''', '''n''', '''o''', '''p'''],
['''q''', '''r''', '''s''', '''t''', '''u'''],
['''v''', '''w''', '''x''', '''y''', '''z'''],
]
class __lowercase:
'''simple docstring'''
def __init__( self ):
__lowerCamelCase : Optional[Any] = np.array(__a )
def snake_case_ ( self , __a ):
__lowerCamelCase , __lowerCamelCase : List[Any] = np.where(letter == self.SQUARE )
__lowerCamelCase : Tuple = np.concatenate([indexa + 1, indexa + 1] )
return indexes
def snake_case_ ( self , __a , __a ):
__lowerCamelCase : Optional[Any] = self.SQUARE[indexa - 1, indexa - 1]
return letter
def snake_case_ ( self , __a ):
__lowerCamelCase : Optional[int] = message.lower()
__lowerCamelCase : Optional[int] = message.replace(' ' , '' )
__lowerCamelCase : Tuple = message.replace('j' , 'i' )
__lowerCamelCase : Optional[int] = np.empty((2, len(__a )) )
for letter_index in range(len(__a ) ):
__lowerCamelCase : Tuple = self.letter_to_numbers(message[letter_index] )
__lowerCamelCase : List[str] = numbers[0]
__lowerCamelCase : Union[str, Any] = numbers[1]
__lowerCamelCase : Any = first_step.reshape(2 * len(__a ) )
__lowerCamelCase : str = ''
for numbers_index in range(len(__a ) ):
__lowerCamelCase : List[Any] = int(second_step[numbers_index * 2] )
__lowerCamelCase : List[Any] = int(second_step[(numbers_index * 2) + 1] )
__lowerCamelCase : Union[str, Any] = self.numbers_to_letter(__a , __a )
__lowerCamelCase : Dict = encoded_message + letter
return encoded_message
def snake_case_ ( self , __a ):
__lowerCamelCase : str = message.lower()
message.replace(' ' , '' )
__lowerCamelCase : str = np.empty(2 * len(__a ) )
for letter_index in range(len(__a ) ):
__lowerCamelCase : Optional[int] = self.letter_to_numbers(message[letter_index] )
__lowerCamelCase : Optional[int] = numbers[0]
__lowerCamelCase : Any = numbers[1]
__lowerCamelCase : List[Any] = first_step.reshape((2, len(__a )) )
__lowerCamelCase : Optional[Any] = ''
for numbers_index in range(len(__a ) ):
__lowerCamelCase : List[Any] = int(second_step[0, numbers_index] )
__lowerCamelCase : Dict = int(second_step[1, numbers_index] )
__lowerCamelCase : Optional[int] = self.numbers_to_letter(__a , __a )
__lowerCamelCase : Dict = decoded_message + letter
return decoded_message
| 594 |
"""simple docstring"""
import unittest
import torch
from torch import nn
from diffusers.models.activations import get_activation
class __lowercase( unittest.TestCase ):
'''simple docstring'''
def snake_case_ ( self ):
__lowerCamelCase : int = get_activation('swish' )
self.assertIsInstance(__a , nn.SiLU )
self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 )
self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 )
self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 )
self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
def snake_case_ ( self ):
__lowerCamelCase : Tuple = get_activation('silu' )
self.assertIsInstance(__a , nn.SiLU )
self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 )
self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 )
self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 )
self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
def snake_case_ ( self ):
__lowerCamelCase : Dict = get_activation('mish' )
self.assertIsInstance(__a , nn.Mish )
self.assertEqual(act(torch.tensor(-200 , dtype=torch.floataa ) ).item() , 0 )
self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 )
self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 )
self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
def snake_case_ ( self ):
__lowerCamelCase : Tuple = get_activation('gelu' )
self.assertIsInstance(__a , nn.GELU )
self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 )
self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 )
self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 )
self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
| 594 | 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
SCREAMING_SNAKE_CASE_ : Tuple = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE_ : Dict = {
'''microsoft/layoutlmv3-base''': '''https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json''',
}
class _A ( __a ):
__a = 'layoutlmv3'
def __init__( self , SCREAMING_SNAKE_CASE__=50265 , SCREAMING_SNAKE_CASE__=768 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=3072 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=512 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=1e-5 , SCREAMING_SNAKE_CASE__=1 , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=1024 , SCREAMING_SNAKE_CASE__=128 , SCREAMING_SNAKE_CASE__=128 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=32 , SCREAMING_SNAKE_CASE__=128 , SCREAMING_SNAKE_CASE__=64 , SCREAMING_SNAKE_CASE__=256 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=224 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=None , **SCREAMING_SNAKE_CASE__ , ) -> Union[str, Any]:
super().__init__(
vocab_size=SCREAMING_SNAKE_CASE__ , hidden_size=SCREAMING_SNAKE_CASE__ , num_hidden_layers=SCREAMING_SNAKE_CASE__ , num_attention_heads=SCREAMING_SNAKE_CASE__ , intermediate_size=SCREAMING_SNAKE_CASE__ , hidden_act=SCREAMING_SNAKE_CASE__ , hidden_dropout_prob=SCREAMING_SNAKE_CASE__ , attention_probs_dropout_prob=SCREAMING_SNAKE_CASE__ , max_position_embeddings=SCREAMING_SNAKE_CASE__ , type_vocab_size=SCREAMING_SNAKE_CASE__ , initializer_range=SCREAMING_SNAKE_CASE__ , layer_norm_eps=SCREAMING_SNAKE_CASE__ , pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
lowerCamelCase__ = max_ad_position_embeddings
lowerCamelCase__ = coordinate_size
lowerCamelCase__ = shape_size
lowerCamelCase__ = has_relative_attention_bias
lowerCamelCase__ = rel_pos_bins
lowerCamelCase__ = max_rel_pos
lowerCamelCase__ = has_spatial_attention_bias
lowerCamelCase__ = rel_ad_pos_bins
lowerCamelCase__ = max_rel_ad_pos
lowerCamelCase__ = text_embed
lowerCamelCase__ = visual_embed
lowerCamelCase__ = input_size
lowerCamelCase__ = num_channels
lowerCamelCase__ = patch_size
lowerCamelCase__ = classifier_dropout
class _A ( __a ):
__a = version.parse('1.12' )
@property
def _lowerCamelCase ( self ) -> Mapping[str, Mapping[int, str]]:
# The order of inputs is different for question answering and sequence classification
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 _lowerCamelCase ( self ) -> float:
return 1e-5
@property
def _lowerCamelCase ( self ) -> int:
return 12
def _lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = -1 , SCREAMING_SNAKE_CASE__ = -1 , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 3 , SCREAMING_SNAKE_CASE__ = 40 , SCREAMING_SNAKE_CASE__ = 40 , ) -> Mapping[str, Any]:
setattr(processor.image_processor , "apply_ocr" , SCREAMING_SNAKE_CASE__ )
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
lowerCamelCase__ = compute_effective_axis_dimension(
SCREAMING_SNAKE_CASE__ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 )
# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
lowerCamelCase__ = processor.tokenizer.num_special_tokens_to_add(SCREAMING_SNAKE_CASE__ )
lowerCamelCase__ = compute_effective_axis_dimension(
SCREAMING_SNAKE_CASE__ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=SCREAMING_SNAKE_CASE__ )
# Generate dummy inputs according to compute batch and sequence
lowerCamelCase__ = [[" ".join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size
# Generate dummy bounding boxes
lowerCamelCase__ = [[[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)
lowerCamelCase__ = self._generate_dummy_images(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
lowerCamelCase__ = dict(
processor(
SCREAMING_SNAKE_CASE__ , text=SCREAMING_SNAKE_CASE__ , boxes=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , ) )
return inputs
| 274 |
"""simple docstring"""
import operator as op
def UpperCAmelCase__ ( A__ ) -> Dict:
"""simple docstring"""
lowerCamelCase__ = []
lowerCamelCase__ = lambda A__ , A__ : int(x / y ) # noqa: E731 integer division operation
lowerCamelCase__ = {
"^": op.pow,
"*": op.mul,
"/": div,
"+": op.add,
"-": op.sub,
} # operators & their respective operation
# print table header
print("Symbol".center(8 ) , "Action".center(12 ) , "Stack" , sep=" | " )
print("-" * (30 + len(A__ )) )
for x in post_fix:
if x.isdigit(): # if x in digit
stack.append(A__ ) # append x to stack
# output in tabular format
print(x.rjust(8 ) , ("push(" + x + ")").ljust(12 ) , ",".join(A__ ) , sep=" | " )
else:
lowerCamelCase__ = stack.pop() # pop stack
# output in tabular format
print("".rjust(8 ) , ("pop(" + b + ")").ljust(12 ) , ",".join(A__ ) , sep=" | " )
lowerCamelCase__ = stack.pop() # pop stack
# output in tabular format
print("".rjust(8 ) , ("pop(" + a + ")").ljust(12 ) , ",".join(A__ ) , sep=" | " )
stack.append(
str(opr[x](int(A__ ) , int(A__ ) ) ) ) # evaluate the 2 values popped from stack & push result to stack
# output in tabular format
print(
x.rjust(8 ) , ("push(" + a + x + b + ")").ljust(12 ) , ",".join(A__ ) , sep=" | " , )
return int(stack[0] )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE_ : Tuple = input('''\n\nEnter a Postfix Equation (space separated) = ''').split(''' ''')
print('''\n\tResult = ''', solve(Postfix))
| 274 | 1 |
from datetime import datetime as dt
import os
from github import Github
__lowercase : Optional[int] =[
"""good first issue""",
"""good second issue""",
"""good difficult issue""",
"""feature request""",
"""new model""",
"""wip""",
]
def a__ ( ):
'''simple docstring'''
UpperCAmelCase_ =Github(os.environ["GITHUB_TOKEN"] )
UpperCAmelCase_ =g.get_repo("huggingface/transformers" )
UpperCAmelCase_ =repo.get_issues(state="open" )
for issue in open_issues:
UpperCAmelCase_ =sorted([comment for comment in issue.get_comments()] , key=lambda lowercase__ : i.created_at , reverse=lowercase__ )
UpperCAmelCase_ =comments[0] if len(lowercase__ ) > 0 else None
if (
last_comment is not None
and last_comment.user.login == "github-actions[bot]"
and (dt.utcnow() - issue.updated_at).days > 7
and (dt.utcnow() - issue.created_at).days >= 3_0
and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
):
# print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.")
issue.edit(state="closed" )
elif (
(dt.utcnow() - issue.updated_at).days > 2_3
and (dt.utcnow() - issue.created_at).days >= 3_0
and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
):
# print(f"Would add stale comment to {issue.number}")
issue.create_comment(
"This issue has been automatically marked as stale because it has not had "
"recent activity. If you think this still needs to be addressed "
"please comment on this thread.\n\nPlease note that issues that do not follow the "
"[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) "
"are likely to be ignored." )
if __name__ == "__main__":
main()
| 54 |
"""simple docstring"""
import warnings
from ...utils import logging
from .image_processing_deformable_detr import DeformableDetrImageProcessor
SCREAMING_SNAKE_CASE__:int = logging.get_logger(__name__)
class snake_case__ ( snake_case_ ):
def __init__( self , *lowerCamelCase , **lowerCamelCase ):
warnings.warn(
"The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers."
" Please use DeformableDetrImageProcessor instead." , lowerCamelCase , )
super().__init__(*lowerCamelCase , **lowerCamelCase )
| 528 | 0 |
'''simple docstring'''
import importlib.util
import os
import platform
from argparse import ArgumentParser
import huggingface_hub
from .. import __version__ as version
from ..utils import (
is_accelerate_available,
is_flax_available,
is_safetensors_available,
is_tf_available,
is_torch_available,
)
from . import BaseTransformersCLICommand
def UpperCAmelCase_ ( __lowercase : List[Any] ) -> Optional[int]:
'''simple docstring'''
return EnvironmentCommand()
def UpperCAmelCase_ ( __lowercase : Union[str, Any] ) -> Optional[Any]:
'''simple docstring'''
return EnvironmentCommand(args.accelerate_config_file )
class A_ ( lowerCAmelCase_ ):
@staticmethod
def lowercase ( snake_case_ : ArgumentParser ):
_UpperCAmelCase = parser.add_parser("env" )
download_parser.set_defaults(func=snake_case_ )
download_parser.add_argument(
"--accelerate-config_file" , default=snake_case_ , help="The accelerate config file to use for the default values in the launching script." , )
download_parser.set_defaults(func=snake_case_ )
def __init__( self : List[Any] , snake_case_ : List[Any] , *snake_case_ : Optional[Any] ):
_UpperCAmelCase = accelerate_config_file
def lowercase ( self : Tuple ):
_UpperCAmelCase = "not installed"
if is_safetensors_available():
import safetensors
_UpperCAmelCase = safetensors.__version__
elif importlib.util.find_spec("safetensors" ) is not None:
import safetensors
_UpperCAmelCase = f'{safetensors.__version__} but is ignored because of PyTorch version too old.'
_UpperCAmelCase = "not installed"
_UpperCAmelCase = _UpperCAmelCase = "not found"
if is_accelerate_available():
import accelerate
from accelerate.commands.config import default_config_file, load_config_from_file
_UpperCAmelCase = accelerate.__version__
# Get the default from the config file.
if self._accelerate_config_file is not None or os.path.isfile(snake_case_ ):
_UpperCAmelCase = load_config_from_file(self._accelerate_config_file ).to_dict()
_UpperCAmelCase = (
"\n".join([f'\t- {prop}: {val}' for prop, val in accelerate_config.items()] )
if isinstance(snake_case_ , snake_case_ )
else f'\t{accelerate_config}'
)
_UpperCAmelCase = "not installed"
_UpperCAmelCase = "NA"
if is_torch_available():
import torch
_UpperCAmelCase = torch.__version__
_UpperCAmelCase = torch.cuda.is_available()
_UpperCAmelCase = "not installed"
_UpperCAmelCase = "NA"
if is_tf_available():
import tensorflow as tf
_UpperCAmelCase = tf.__version__
try:
# deprecated in v2.1
_UpperCAmelCase = tf.test.is_gpu_available()
except AttributeError:
# returns list of devices, convert to bool
_UpperCAmelCase = bool(tf.config.list_physical_devices("GPU" ) )
_UpperCAmelCase = "not installed"
_UpperCAmelCase = "not installed"
_UpperCAmelCase = "not installed"
_UpperCAmelCase = "NA"
if is_flax_available():
import flax
import jax
import jaxlib
_UpperCAmelCase = flax.__version__
_UpperCAmelCase = jax.__version__
_UpperCAmelCase = jaxlib.__version__
_UpperCAmelCase = jax.lib.xla_bridge.get_backend().platform
_UpperCAmelCase = {
"`transformers` version": version,
"Platform": platform.platform(),
"Python version": platform.python_version(),
"Huggingface_hub version": huggingface_hub.__version__,
"Safetensors version": f'{safetensors_version}',
"Accelerate version": f'{accelerate_version}',
"Accelerate config": f'{accelerate_config_str}',
"PyTorch version (GPU?)": f'{pt_version} ({pt_cuda_available})',
"Tensorflow version (GPU?)": f'{tf_version} ({tf_cuda_available})',
"Flax version (CPU?/GPU?/TPU?)": f'{flax_version} ({jax_backend})',
"Jax version": f'{jax_version}',
"JaxLib version": f'{jaxlib_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(snake_case_ ) )
return info
@staticmethod
def lowercase ( snake_case_ : List[str] ):
return "\n".join([f'- {prop}: {val}' for prop, val in d.items()] ) + "\n"
| 119 |
'''simple docstring'''
import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union
import pandas as pd
import pyarrow as pa
import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal
__SCREAMING_SNAKE_CASE :List[str] = datasets.utils.logging.get_logger(__name__)
__SCREAMING_SNAKE_CASE :Union[str, Any] = ['''names''', '''prefix''']
__SCREAMING_SNAKE_CASE :Dict = ['''warn_bad_lines''', '''error_bad_lines''', '''mangle_dupe_cols''']
__SCREAMING_SNAKE_CASE :Union[str, Any] = ['''encoding_errors''', '''on_bad_lines''']
__SCREAMING_SNAKE_CASE :int = ['''date_format''']
@dataclass
class A_ ( datasets.BuilderConfig ):
_lowerCamelCase : str = ","
_lowerCamelCase : Optional[str] = None
_lowerCamelCase : Optional[Union[int, List[int], str]] = "infer"
_lowerCamelCase : Optional[List[str]] = None
_lowerCamelCase : Optional[List[str]] = None
_lowerCamelCase : Optional[Union[int, str, List[int], List[str]]] = None
_lowerCamelCase : Optional[Union[List[int], List[str]]] = None
_lowerCamelCase : Optional[str] = None
_lowerCamelCase : bool = True
_lowerCamelCase : Optional[Literal["c", "python", "pyarrow"]] = None
_lowerCamelCase : Dict[Union[int, str], Callable[[Any], Any]] = None
_lowerCamelCase : Optional[list] = None
_lowerCamelCase : Optional[list] = None
_lowerCamelCase : bool = False
_lowerCamelCase : Optional[Union[int, List[int]]] = None
_lowerCamelCase : Optional[int] = None
_lowerCamelCase : Optional[Union[str, List[str]]] = None
_lowerCamelCase : bool = True
_lowerCamelCase : bool = True
_lowerCamelCase : bool = False
_lowerCamelCase : bool = True
_lowerCamelCase : Optional[str] = None
_lowerCamelCase : str = "."
_lowerCamelCase : Optional[str] = None
_lowerCamelCase : str = '"'
_lowerCamelCase : int = 0
_lowerCamelCase : Optional[str] = None
_lowerCamelCase : Optional[str] = None
_lowerCamelCase : Optional[str] = None
_lowerCamelCase : Optional[str] = None
_lowerCamelCase : bool = True
_lowerCamelCase : bool = True
_lowerCamelCase : int = 0
_lowerCamelCase : bool = True
_lowerCamelCase : bool = False
_lowerCamelCase : Optional[str] = None
_lowerCamelCase : int = 1_00_00
_lowerCamelCase : Optional[datasets.Features] = None
_lowerCamelCase : Optional[str] = "strict"
_lowerCamelCase : Literal["error", "warn", "skip"] = "error"
_lowerCamelCase : Optional[str] = None
def lowercase ( self : int ):
if self.delimiter is not None:
_UpperCAmelCase = self.delimiter
if self.column_names is not None:
_UpperCAmelCase = self.column_names
@property
def lowercase ( self : List[Any] ):
_UpperCAmelCase = {
"sep": self.sep,
"header": self.header,
"names": self.names,
"index_col": self.index_col,
"usecols": self.usecols,
"prefix": self.prefix,
"mangle_dupe_cols": self.mangle_dupe_cols,
"engine": self.engine,
"converters": self.converters,
"true_values": self.true_values,
"false_values": self.false_values,
"skipinitialspace": self.skipinitialspace,
"skiprows": self.skiprows,
"nrows": self.nrows,
"na_values": self.na_values,
"keep_default_na": self.keep_default_na,
"na_filter": self.na_filter,
"verbose": self.verbose,
"skip_blank_lines": self.skip_blank_lines,
"thousands": self.thousands,
"decimal": self.decimal,
"lineterminator": self.lineterminator,
"quotechar": self.quotechar,
"quoting": self.quoting,
"escapechar": self.escapechar,
"comment": self.comment,
"encoding": self.encoding,
"dialect": self.dialect,
"error_bad_lines": self.error_bad_lines,
"warn_bad_lines": self.warn_bad_lines,
"skipfooter": self.skipfooter,
"doublequote": self.doublequote,
"memory_map": self.memory_map,
"float_precision": self.float_precision,
"chunksize": self.chunksize,
"encoding_errors": self.encoding_errors,
"on_bad_lines": self.on_bad_lines,
"date_format": self.date_format,
}
# some kwargs must not be passed if they don't have a default value
# some others are deprecated and we can also not pass them if they are the default value
for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , snake_case_ ):
del pd_read_csv_kwargs[pd_read_csv_parameter]
# Remove 2.0 new arguments
if not (datasets.config.PANDAS_VERSION.major >= 2):
for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
del pd_read_csv_kwargs[pd_read_csv_parameter]
# Remove 1.3 new arguments
if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
del pd_read_csv_kwargs[pd_read_csv_parameter]
return pd_read_csv_kwargs
class A_ ( datasets.ArrowBasedBuilder ):
_lowerCamelCase : Any = CsvConfig
def lowercase ( self : Tuple ):
return datasets.DatasetInfo(features=self.config.features )
def lowercase ( self : Any , snake_case_ : int ):
if not self.config.data_files:
raise ValueError(f'At least one data file must be specified, but got data_files={self.config.data_files}' )
_UpperCAmelCase = dl_manager.download_and_extract(self.config.data_files )
if isinstance(snake_case_ , (str, list, tuple) ):
_UpperCAmelCase = data_files
if isinstance(snake_case_ , snake_case_ ):
_UpperCAmelCase = [files]
_UpperCAmelCase = [dl_manager.iter_files(snake_case_ ) for file in files]
return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"files": files} )]
_UpperCAmelCase = []
for split_name, files in data_files.items():
if isinstance(snake_case_ , snake_case_ ):
_UpperCAmelCase = [files]
_UpperCAmelCase = [dl_manager.iter_files(snake_case_ ) for file in files]
splits.append(datasets.SplitGenerator(name=snake_case_ , gen_kwargs={"files": files} ) )
return splits
def lowercase ( self : List[str] , snake_case_ : pa.Table ):
if self.config.features is not None:
_UpperCAmelCase = self.config.features.arrow_schema
if all(not require_storage_cast(snake_case_ ) for feature in self.config.features.values() ):
# cheaper cast
_UpperCAmelCase = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=snake_case_ )
else:
# more expensive cast; allows str <-> int/float or str to Audio for example
_UpperCAmelCase = table_cast(snake_case_ , snake_case_ )
return pa_table
def lowercase ( self : Union[str, Any] , snake_case_ : Any ):
_UpperCAmelCase = self.config.features.arrow_schema if self.config.features else None
# dtype allows reading an int column as str
_UpperCAmelCase = (
{
name: dtype.to_pandas_dtype() if not require_storage_cast(snake_case_ ) else object
for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() )
}
if schema is not None
else None
)
for file_idx, file in enumerate(itertools.chain.from_iterable(snake_case_ ) ):
_UpperCAmelCase = pd.read_csv(snake_case_ , iterator=snake_case_ , dtype=snake_case_ , **self.config.pd_read_csv_kwargs )
try:
for batch_idx, df in enumerate(snake_case_ ):
_UpperCAmelCase = pa.Table.from_pandas(snake_case_ )
# Uncomment for debugging (will print the Arrow table size and elements)
# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
yield (file_idx, batch_idx), self._cast_table(snake_case_ )
except ValueError as e:
logger.error(f'Failed to read file \'{file}\' with error {type(snake_case_ )}: {e}' )
raise
| 119 | 1 |
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class _A( snake_case__ ):
"""simple docstring"""
UpperCamelCase : Union[str, Any] = ['''image_processor''', '''tokenizer''']
UpperCamelCase : List[Any] = '''ViTImageProcessor'''
UpperCamelCase : Optional[Any] = ('''CLIPTokenizer''', '''CLIPTokenizerFast''')
def __init__( self , _A=None , _A=None , **_A ):
__A : Optional[int] = None
if "feature_extractor" in kwargs:
warnings.warn(
'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
' instead.' , _A , )
__A : int = kwargs.pop('feature_extractor' )
__A : int = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError('You need to specify an `image_processor`.' )
if tokenizer is None:
raise ValueError('You need to specify a `tokenizer`.' )
super().__init__(_A , _A )
def __call__( self , _A=None , _A=None , _A=None , _A=None , **_A ):
if text is None and visual_prompt is None and images is None:
raise ValueError('You have to specify either text, visual prompt or images.' )
if text is not None and visual_prompt is not None:
raise ValueError('You have to specify exactly one type of prompt. Either text or visual prompt.' )
if text is not None:
__A : Any = self.tokenizer(_A , return_tensors=_A , **_A )
if visual_prompt is not None:
__A : Optional[int] = self.image_processor(_A , return_tensors=_A , **_A )
if images is not None:
__A : List[str] = self.image_processor(_A , return_tensors=_A , **_A )
if visual_prompt is not None and images is not None:
__A : List[Any] = {
'pixel_values': image_features.pixel_values,
'conditional_pixel_values': prompt_features.pixel_values,
}
return encoding
elif text is not None and images is not None:
__A : List[Any] = image_features.pixel_values
return encoding
elif text is not None:
return encoding
elif visual_prompt is not None:
__A : Tuple = {
'conditional_pixel_values': prompt_features.pixel_values,
}
return encoding
else:
return BatchEncoding(data=dict(**_A ) , tensor_type=_A )
def UpperCAmelCase_ ( self , *_A , **_A ):
return self.tokenizer.batch_decode(*_A , **_A )
def UpperCAmelCase_ ( self , *_A , **_A ):
return self.tokenizer.decode(*_A , **_A )
@property
def UpperCAmelCase_ ( self ):
warnings.warn(
'`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , _A , )
return self.image_processor_class
@property
def UpperCAmelCase_ ( self ):
warnings.warn(
'`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , _A , )
return self.image_processor
| 239 |
from collections import Counter
from pathlib import Path
from typing import Optional, Tuple
import yaml
class _A( yaml.SafeLoader ):
"""simple docstring"""
def UpperCAmelCase_ ( self , _A ):
__A : Optional[int] = [self.constructed_objects[key_node] for key_node, _ in node.value]
__A : Dict = [tuple(_A ) if isinstance(_A , _A ) else key for key in keys]
__A : Tuple = Counter(_A )
__A : Optional[int] = [key for key in counter if counter[key] > 1]
if duplicate_keys:
raise TypeError(F"""Got duplicate yaml keys: {duplicate_keys}""" )
def UpperCAmelCase_ ( self , _A , _A=False ):
__A : Union[str, Any] = super().construct_mapping(_A , deep=_A )
self._check_no_duplicates_on_constructed_node(_A )
return mapping
def _SCREAMING_SNAKE_CASE ( a ) -> Tuple[Optional[str], str]:
__A : List[str] = list(readme_content.splitlines() )
if full_content and full_content[0] == "---" and "---" in full_content[1:]:
__A : List[Any] = full_content[1:].index('---' ) + 1
__A : Dict = '\n'.join(full_content[1:sep_idx] )
return yamlblock, "\n".join(full_content[sep_idx + 1 :] )
return None, "\n".join(a )
class _A( snake_case__ ):
"""simple docstring"""
UpperCamelCase : Union[str, Any] = {'''train_eval_index'''} # train-eval-index in the YAML metadata
@classmethod
def UpperCAmelCase_ ( cls , _A ):
with open(_A , encoding='utf-8' ) as readme_file:
__A , __A : Any = _split_yaml_from_readme(readme_file.read() )
if yaml_string is not None:
return cls.from_yaml_string(_A )
else:
return cls()
def UpperCAmelCase_ ( self , _A ):
if path.exists():
with open(_A , encoding='utf-8' ) as readme_file:
__A : Union[str, Any] = readme_file.read()
else:
__A : List[Any] = None
__A : Any = self._to_readme(_A )
with open(_A , 'w' , encoding='utf-8' ) as readme_file:
readme_file.write(_A )
def UpperCAmelCase_ ( self , _A = None ):
if readme_content is not None:
__A , __A : str = _split_yaml_from_readme(_A )
__A : Any = '---\n' + self.to_yaml_string() + '---\n' + content
else:
__A : List[Any] = '---\n' + self.to_yaml_string() + '---\n'
return full_content
@classmethod
def UpperCAmelCase_ ( cls , _A ):
__A : Optional[int] = yaml.load(_A , Loader=_NoDuplicateSafeLoader ) or {}
# Convert the YAML keys to DatasetMetadata fields
__A : int = {
(key.replace('-' , '_' ) if key.replace('-' , '_' ) in cls._FIELDS_WITH_DASHES else key): value
for key, value in metadata_dict.items()
}
return cls(**_A )
def UpperCAmelCase_ ( self ):
return yaml.safe_dump(
{
(key.replace('_' , '-' ) if key in self._FIELDS_WITH_DASHES else key): value
for key, value in self.items()
} , sort_keys=_A , allow_unicode=_A , encoding='utf-8' , ).decode('utf-8' )
UpperCAmelCase : List[Any] = {
'''image-classification''': [],
'''translation''': [],
'''image-segmentation''': [],
'''fill-mask''': [],
'''automatic-speech-recognition''': [],
'''token-classification''': [],
'''sentence-similarity''': [],
'''audio-classification''': [],
'''question-answering''': [],
'''summarization''': [],
'''zero-shot-classification''': [],
'''table-to-text''': [],
'''feature-extraction''': [],
'''other''': [],
'''multiple-choice''': [],
'''text-classification''': [],
'''text-to-image''': [],
'''text2text-generation''': [],
'''zero-shot-image-classification''': [],
'''tabular-classification''': [],
'''tabular-regression''': [],
'''image-to-image''': [],
'''tabular-to-text''': [],
'''unconditional-image-generation''': [],
'''text-retrieval''': [],
'''text-to-speech''': [],
'''object-detection''': [],
'''audio-to-audio''': [],
'''text-generation''': [],
'''conversational''': [],
'''table-question-answering''': [],
'''visual-question-answering''': [],
'''image-to-text''': [],
'''reinforcement-learning''': [],
'''voice-activity-detection''': [],
'''time-series-forecasting''': [],
'''document-question-answering''': [],
}
if __name__ == "__main__":
from argparse import ArgumentParser
UpperCAmelCase : Any = ArgumentParser(usage='''Validate the yaml metadata block of a README.md file.''')
ap.add_argument('''readme_filepath''')
UpperCAmelCase : Any = ap.parse_args()
UpperCAmelCase : Any = Path(args.readme_filepath)
UpperCAmelCase : int = DatasetMetadata.from_readme(readme_filepath)
print(dataset_metadata)
dataset_metadata.to_readme(readme_filepath)
| 239 | 1 |
def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase ) -> int:
"""simple docstring"""
while a != 0:
snake_case__ , snake_case__ : str = b % a, a
return b
def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase ) -> int:
"""simple docstring"""
if gcd(__lowerCAmelCase , __lowerCAmelCase ) != 1:
snake_case__ : Dict = f"""mod inverse of {a!r} and {m!r} does not exist"""
raise ValueError(__lowerCAmelCase )
snake_case__ , snake_case__ , snake_case__ : Optional[int] = 1, 0, a
snake_case__ , snake_case__ , snake_case__ : Dict = 0, 1, m
while va != 0:
snake_case__ : str = ua // va
snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ : Optional[Any] = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va
return ua % m
| 219 |
# Copyright 2022 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import os
import subprocess
from packaging.version import Version, parse
from accelerate.commands.config.config_args import default_config_file, load_config_from_file
A__ = '''Run commands across TPU VMs for initial setup before running `accelerate launch`.'''
def _lowerCAmelCase ( __lowerCAmelCase=None ) -> Optional[Any]:
"""simple docstring"""
if subparsers is not None:
snake_case__ : Any = subparsers.add_parser('''tpu-config''' , description=_description )
else:
snake_case__ : int = argparse.ArgumentParser('''Accelerate tpu-config command''' , description=_description )
# Core arguments
snake_case__ : Tuple = parser.add_argument_group(
'''Config Arguments''' , '''Arguments that can be configured through `accelerate config`.''' )
config_args.add_argument(
'''--config_file''' , type=__lowerCAmelCase , default=__lowerCAmelCase , help='''Path to the config file to use for accelerate.''' , )
config_args.add_argument(
'''--tpu_name''' , default=__lowerCAmelCase , help='''The name of the TPU to use. If not specified, will use the TPU specified in the config file.''' , )
config_args.add_argument(
'''--tpu_zone''' , default=__lowerCAmelCase , help='''The zone of the TPU to use. If not specified, will use the zone specified in the config file.''' , )
snake_case__ : str = parser.add_argument_group('''TPU Arguments''' , '''Arguments for options ran inside the TPU.''' )
pod_args.add_argument(
'''--use_alpha''' , action='''store_true''' , help='''Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.''' , )
pod_args.add_argument(
'''--command_file''' , default=__lowerCAmelCase , help='''The path to the file containing the commands to run on the pod on startup.''' , )
pod_args.add_argument(
'''--command''' , action='''append''' , nargs='''+''' , help='''A command to run on the pod. Can be passed multiple times.''' , )
pod_args.add_argument(
'''--install_accelerate''' , action='''store_true''' , help='''Whether to install accelerate on the pod. Defaults to False.''' , )
pod_args.add_argument(
'''--accelerate_version''' , default='''latest''' , help='''The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.''' , )
pod_args.add_argument(
'''--debug''' , action='''store_true''' , help='''If set, will print the command that would be run instead of running it.''' )
if subparsers is not None:
parser.set_defaults(func=__lowerCAmelCase )
return parser
def _lowerCAmelCase ( __lowerCAmelCase ) -> Dict:
"""simple docstring"""
snake_case__ : Optional[int] = None
# Get the default from the config file if it exists.
if args.config_file is not None or os.path.isfile(__lowerCAmelCase ):
snake_case__ : Optional[int] = load_config_from_file(args.config_file )
if not args.command_file and defaults.command_file is not None and not args.command:
snake_case__ : Optional[int] = defaults.command_file
if not args.command and defaults.commands is not None:
snake_case__ : int = defaults.commands
if not args.tpu_name:
snake_case__ : List[Any] = defaults.tpu_name
if not args.tpu_zone:
snake_case__ : Optional[Any] = defaults.tpu_zone
if args.accelerate_version == "dev":
snake_case__ : Tuple = '''git+https://github.com/huggingface/accelerate.git'''
elif args.accelerate_version == "latest":
snake_case__ : Union[str, Any] = '''accelerate -U'''
elif isinstance(parse(args.accelerate_version ) , __lowerCAmelCase ):
snake_case__ : List[str] = f"""accelerate=={args.accelerate_version}"""
if not args.command_file and not args.command:
raise ValueError('''You must specify either a command file or a command to run on the pod.''' )
if args.command_file:
with open(args.command_file , '''r''' ) as f:
snake_case__ : Any = [f.read().splitlines()]
# To turn list of lists into list of strings
if isinstance(args.command[0] , __lowerCAmelCase ):
snake_case__ : Union[str, Any] = [line for cmd in args.command for line in cmd]
# Default to the shared folder and install accelerate
snake_case__ : List[str] = ['''cd /usr/share''']
if args.install_accelerate:
new_cmd += [f"""pip install {args.accelerate_version}"""]
new_cmd += args.command
snake_case__ : Dict = '''; '''.join(__lowerCAmelCase )
# Then send it to gcloud
# Eventually try to use google-api-core to do this instead of subprocess
snake_case__ : Optional[int] = ['''gcloud''']
if args.use_alpha:
cmd += ["alpha"]
cmd += [
"compute",
"tpus",
"tpu-vm",
"ssh",
args.tpu_name,
"--zone",
args.tpu_zone,
"--command",
args.command,
"--worker",
"all",
]
if args.debug:
print(f"""Running {' '.join(__lowerCAmelCase )}""" )
return
subprocess.run(__lowerCAmelCase )
print('''Successfully setup pod.''' )
def _lowerCAmelCase ( ) -> int:
"""simple docstring"""
snake_case__ : Optional[Any] = tpu_command_parser()
snake_case__ : int = parser.parse_args()
tpu_command_launcher(__lowerCAmelCase )
| 219 | 1 |
"""simple docstring"""
from datetime import datetime
import requests
def A__ ( __lowerCamelCase ):
"""simple docstring"""
_lowerCAmelCase = 'https://downloadgram.net/wp-json/wppress/video-downloader/video?url='
_lowerCAmelCase = requests.get(base_url + url ).json()[0]['urls'][0]['src']
return requests.get(__lowerCamelCase ).content
if __name__ == "__main__":
a__ : Optional[Any] = input("""Enter Video/IGTV url: """).strip()
a__ : List[Any] = 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}.')
| 589 |
"""simple docstring"""
import math
from typing import Optional
import numpy as np
from ...configuration_utils import PretrainedConfig
from ...utils import logging
a__ : Any = logging.get_logger(__name__)
a__ : Tuple = {
"""facebook/encodec_24khz""": """https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json""",
"""facebook/encodec_48khz""": """https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json""",
}
class __magic_name__ ( _UpperCamelCase ):
UpperCamelCase : Tuple = "encodec"
def __init__( self , __magic_name__=[1.5, 3.0, 6.0, 12.0, 24.0] , __magic_name__=2_4_0_0_0 , __magic_name__=1 , __magic_name__=False , __magic_name__=None , __magic_name__=None , __magic_name__=1_2_8 , __magic_name__=3_2 , __magic_name__=1 , __magic_name__=[8, 5, 4, 2] , __magic_name__="weight_norm" , __magic_name__=7 , __magic_name__=7 , __magic_name__=3 , __magic_name__=2 , __magic_name__=True , __magic_name__="reflect" , __magic_name__=2 , __magic_name__=2 , __magic_name__=1.0 , __magic_name__=1_0_2_4 , __magic_name__=None , __magic_name__=True , **__magic_name__ , ):
"""simple docstring"""
_lowerCAmelCase = target_bandwidths
_lowerCAmelCase = sampling_rate
_lowerCAmelCase = audio_channels
_lowerCAmelCase = normalize
_lowerCAmelCase = chunk_length_s
_lowerCAmelCase = overlap
_lowerCAmelCase = hidden_size
_lowerCAmelCase = num_filters
_lowerCAmelCase = num_residual_layers
_lowerCAmelCase = upsampling_ratios
_lowerCAmelCase = norm_type
_lowerCAmelCase = kernel_size
_lowerCAmelCase = last_kernel_size
_lowerCAmelCase = residual_kernel_size
_lowerCAmelCase = dilation_growth_rate
_lowerCAmelCase = use_causal_conv
_lowerCAmelCase = pad_mode
_lowerCAmelCase = compress
_lowerCAmelCase = num_lstm_layers
_lowerCAmelCase = trim_right_ratio
_lowerCAmelCase = codebook_size
_lowerCAmelCase = codebook_dim if codebook_dim is not None else hidden_size
_lowerCAmelCase = use_conv_shortcut
if self.norm_type not in ["weight_norm", "time_group_norm"]:
raise ValueError(
F'''self.norm_type must be one of `"weight_norm"`, `"time_group_norm"`), got {self.norm_type}''' )
super().__init__(**__magic_name__ )
@property
def _lowerCamelCase ( self ):
"""simple docstring"""
if self.chunk_length_s is None:
return None
else:
return int(self.chunk_length_s * self.sampling_rate )
@property
def _lowerCamelCase ( self ):
"""simple docstring"""
if self.chunk_length_s is None or self.overlap is None:
return None
else:
return max(1 , int((1.0 - self.overlap) * self.chunk_length ) )
@property
def _lowerCamelCase ( self ):
"""simple docstring"""
_lowerCAmelCase = np.prod(self.upsampling_ratios )
return math.ceil(self.sampling_rate / hop_length )
@property
def _lowerCamelCase ( self ):
"""simple docstring"""
return int(1_0_0_0 * self.target_bandwidths[-1] // (self.frame_rate * 1_0) )
| 589 | 1 |
import json
import os
from pathlib import Path
import pytest
from datasets.download.download_config import DownloadConfig
from datasets.download.download_manager import DownloadManager
from datasets.utils.file_utils import hash_url_to_filename
a_ = "http://www.mocksite.com/file1.txt"
a_ = "\"text\": [\"foo\", \"foo\"]"
a_ = "6d8ce9aa78a471c7477201efbeabd3bb01ac2e7d100a6dc024ba1608361f90a8"
class _lowerCamelCase :
"""simple docstring"""
lowerCAmelCase__ : Optional[Any] = 2_00
lowerCAmelCase__ : Dict = {"Content-Length": "100"}
lowerCAmelCase__ : Any = {}
def snake_case ( self : Any , **snake_case : List[str] ):
return [bytes(snake_case , '''utf-8''' )]
def __SCREAMING_SNAKE_CASE ( *lowercase_ , **lowercase_ ) -> Union[str, Any]:
"""simple docstring"""
return MockResponse()
@pytest.mark.parametrize('''urls_type''' , [str, list, dict] )
def __SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> Dict:
"""simple docstring"""
import requests
monkeypatch.setattr(lowercase_ , '''request''' , lowercase_ )
__UpperCamelCase = URL
if issubclass(lowercase_ , lowercase_ ):
__UpperCamelCase = url
elif issubclass(lowercase_ , lowercase_ ):
__UpperCamelCase = [url]
elif issubclass(lowercase_ , lowercase_ ):
__UpperCamelCase = {'''train''': url}
__UpperCamelCase = '''dummy'''
__UpperCamelCase = '''downloads'''
__UpperCamelCase = tmp_path
__UpperCamelCase = DownloadConfig(
cache_dir=os.path.join(lowercase_ , lowercase_ ) , use_etag=lowercase_ , )
__UpperCamelCase = DownloadManager(dataset_name=lowercase_ , download_config=lowercase_ )
__UpperCamelCase = dl_manager.download(lowercase_ )
__UpperCamelCase = urls
for downloaded_paths in [downloaded_paths]:
if isinstance(lowercase_ , lowercase_ ):
__UpperCamelCase = [downloaded_paths]
__UpperCamelCase = [urls]
elif isinstance(lowercase_ , lowercase_ ):
assert "train" in downloaded_paths.keys()
__UpperCamelCase = downloaded_paths.values()
__UpperCamelCase = urls.values()
assert downloaded_paths
for downloaded_path, input_url in zip(lowercase_ , lowercase_ ):
assert downloaded_path == dl_manager.downloaded_paths[input_url]
__UpperCamelCase = Path(lowercase_ )
__UpperCamelCase = downloaded_path.parts
assert parts[-1] == HASH
assert parts[-2] == cache_subdir
assert downloaded_path.exists()
__UpperCamelCase = downloaded_path.read_text()
assert content == CONTENT
__UpperCamelCase = downloaded_path.with_suffix('''.json''' )
assert metadata_downloaded_path.exists()
__UpperCamelCase = json.loads(metadata_downloaded_path.read_text() )
assert metadata_content == {"url": URL, "etag": None}
@pytest.mark.parametrize('''paths_type''' , [str, list, dict] )
def __SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> Optional[int]:
"""simple docstring"""
__UpperCamelCase = str(lowercase_ )
if issubclass(lowercase_ , lowercase_ ):
__UpperCamelCase = filename
elif issubclass(lowercase_ , lowercase_ ):
__UpperCamelCase = [filename]
elif issubclass(lowercase_ , lowercase_ ):
__UpperCamelCase = {'''train''': filename}
__UpperCamelCase = '''dummy'''
__UpperCamelCase = xz_file.parent
__UpperCamelCase = '''extracted'''
__UpperCamelCase = DownloadConfig(
cache_dir=lowercase_ , use_etag=lowercase_ , )
__UpperCamelCase = DownloadManager(dataset_name=lowercase_ , download_config=lowercase_ )
__UpperCamelCase = dl_manager.extract(lowercase_ )
__UpperCamelCase = paths
for extracted_paths in [extracted_paths]:
if isinstance(lowercase_ , lowercase_ ):
__UpperCamelCase = [extracted_paths]
__UpperCamelCase = [paths]
elif isinstance(lowercase_ , lowercase_ ):
assert "train" in extracted_paths.keys()
__UpperCamelCase = extracted_paths.values()
__UpperCamelCase = paths.values()
assert extracted_paths
for extracted_path, input_path in zip(lowercase_ , lowercase_ ):
assert extracted_path == dl_manager.extracted_paths[input_path]
__UpperCamelCase = Path(lowercase_ )
__UpperCamelCase = extracted_path.parts
assert parts[-1] == hash_url_to_filename(lowercase_ , etag=lowercase_ )
assert parts[-2] == extracted_subdir
assert extracted_path.exists()
__UpperCamelCase = extracted_path.read_text()
__UpperCamelCase = text_file.read_text()
assert extracted_file_content == expected_file_content
def __SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> str:
"""simple docstring"""
assert path.endswith('''.jsonl''' )
for num_items, line in enumerate(lowercase_ , start=1 ):
__UpperCamelCase = json.loads(line.decode('''utf-8''' ) )
assert item.keys() == {"col_1", "col_2", "col_3"}
assert num_items == 4
@pytest.mark.parametrize('''archive_jsonl''' , ['''tar_jsonl_path''', '''zip_jsonl_path'''] )
def __SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> Any:
"""simple docstring"""
__UpperCamelCase = request.getfixturevalue(lowercase_ )
__UpperCamelCase = DownloadManager()
for num_jsonl, (path, file) in enumerate(dl_manager.iter_archive(lowercase_ ) , start=1 ):
_test_jsonl(lowercase_ , lowercase_ )
assert num_jsonl == 2
@pytest.mark.parametrize('''archive_nested_jsonl''' , ['''tar_nested_jsonl_path''', '''zip_nested_jsonl_path'''] )
def __SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> int:
"""simple docstring"""
__UpperCamelCase = request.getfixturevalue(lowercase_ )
__UpperCamelCase = DownloadManager()
for num_tar, (path, file) in enumerate(dl_manager.iter_archive(lowercase_ ) , start=1 ):
for num_jsonl, (subpath, subfile) in enumerate(dl_manager.iter_archive(lowercase_ ) , start=1 ):
_test_jsonl(lowercase_ , lowercase_ )
assert num_tar == 1
assert num_jsonl == 2
def __SCREAMING_SNAKE_CASE ( lowercase_ ) -> Dict:
"""simple docstring"""
__UpperCamelCase = DownloadManager()
for num_file, file in enumerate(dl_manager.iter_files(lowercase_ ) , start=1 ):
assert os.path.basename(lowercase_ ) == ("test.txt" if num_file == 1 else "train.txt")
assert num_file == 2
| 375 |
import argparse
import torch
from datasets import load_dataset
from donut import DonutModel
from transformers import (
DonutImageProcessor,
DonutProcessor,
DonutSwinConfig,
DonutSwinModel,
MBartConfig,
MBartForCausalLM,
VisionEncoderDecoderModel,
XLMRobertaTokenizerFast,
)
def __SCREAMING_SNAKE_CASE ( lowercase_ ) -> Optional[int]:
"""simple docstring"""
__UpperCamelCase = model.config
__UpperCamelCase = DonutSwinConfig(
image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=1_28 , )
__UpperCamelCase = MBartConfig(
is_decoder=lowercase_ , is_encoder_decoder=lowercase_ , add_cross_attention=lowercase_ , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len(
model.decoder.tokenizer ) , scale_embedding=lowercase_ , add_final_layer_norm=lowercase_ , )
return encoder_config, decoder_config
def __SCREAMING_SNAKE_CASE ( lowercase_ ) -> Any:
"""simple docstring"""
if "encoder.model" in name:
__UpperCamelCase = name.replace('''encoder.model''' , '''encoder''' )
if "decoder.model" in name:
__UpperCamelCase = name.replace('''decoder.model''' , '''decoder''' )
if "patch_embed.proj" in name:
__UpperCamelCase = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' )
if "patch_embed.norm" in name:
__UpperCamelCase = name.replace('''patch_embed.norm''' , '''embeddings.norm''' )
if name.startswith('''encoder''' ):
if "layers" in name:
__UpperCamelCase = '''encoder.''' + name
if "attn.proj" in name:
__UpperCamelCase = name.replace('''attn.proj''' , '''attention.output.dense''' )
if "attn" in name and "mask" not in name:
__UpperCamelCase = name.replace('''attn''' , '''attention.self''' )
if "norm1" in name:
__UpperCamelCase = name.replace('''norm1''' , '''layernorm_before''' )
if "norm2" in name:
__UpperCamelCase = name.replace('''norm2''' , '''layernorm_after''' )
if "mlp.fc1" in name:
__UpperCamelCase = name.replace('''mlp.fc1''' , '''intermediate.dense''' )
if "mlp.fc2" in name:
__UpperCamelCase = name.replace('''mlp.fc2''' , '''output.dense''' )
if name == "encoder.norm.weight":
__UpperCamelCase = '''encoder.layernorm.weight'''
if name == "encoder.norm.bias":
__UpperCamelCase = '''encoder.layernorm.bias'''
return name
def __SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> int:
"""simple docstring"""
for key in orig_state_dict.copy().keys():
__UpperCamelCase = orig_state_dict.pop(lowercase_ )
if "qkv" in key:
__UpperCamelCase = key.split('''.''' )
__UpperCamelCase = int(key_split[3] )
__UpperCamelCase = int(key_split[5] )
__UpperCamelCase = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size
if "weight" in key:
__UpperCamelCase = val[:dim, :]
__UpperCamelCase = val[dim : dim * 2, :]
__UpperCamelCase = val[-dim:, :]
else:
__UpperCamelCase = val[:dim]
__UpperCamelCase = val[dim : dim * 2]
__UpperCamelCase = val[-dim:]
elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]:
# HuggingFace implementation doesn't use attn_mask buffer
# and model doesn't use final LayerNorms for the encoder
pass
else:
__UpperCamelCase = val
return orig_state_dict
def __SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=None , lowercase_=False ) -> Dict:
"""simple docstring"""
__UpperCamelCase = DonutModel.from_pretrained(lowercase_ ).eval()
# load HuggingFace model
__UpperCamelCase , __UpperCamelCase = get_configs(lowercase_ )
__UpperCamelCase = DonutSwinModel(lowercase_ )
__UpperCamelCase = MBartForCausalLM(lowercase_ )
__UpperCamelCase = VisionEncoderDecoderModel(encoder=lowercase_ , decoder=lowercase_ )
model.eval()
__UpperCamelCase = original_model.state_dict()
__UpperCamelCase = convert_state_dict(lowercase_ , lowercase_ )
model.load_state_dict(lowercase_ )
# verify results on scanned document
__UpperCamelCase = load_dataset('''hf-internal-testing/example-documents''' )
__UpperCamelCase = dataset['''test'''][0]['''image'''].convert('''RGB''' )
__UpperCamelCase = XLMRobertaTokenizerFast.from_pretrained(lowercase_ , from_slow=lowercase_ )
__UpperCamelCase = DonutImageProcessor(
do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] )
__UpperCamelCase = DonutProcessor(lowercase_ , lowercase_ )
__UpperCamelCase = processor(lowercase_ , return_tensors='''pt''' ).pixel_values
if model_name == "naver-clova-ix/donut-base-finetuned-docvqa":
__UpperCamelCase = '''<s_docvqa><s_question>{user_input}</s_question><s_answer>'''
__UpperCamelCase = '''When is the coffee break?'''
__UpperCamelCase = task_prompt.replace('''{user_input}''' , lowercase_ )
elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip":
__UpperCamelCase = '''<s_rvlcdip>'''
elif model_name in [
"naver-clova-ix/donut-base-finetuned-cord-v1",
"naver-clova-ix/donut-base-finetuned-cord-v1-2560",
]:
__UpperCamelCase = '''<s_cord>'''
elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2":
__UpperCamelCase = '''s_cord-v2>'''
elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket":
__UpperCamelCase = '''<s_zhtrainticket>'''
elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]:
# use a random prompt
__UpperCamelCase = '''hello world'''
else:
raise ValueError('''Model name not supported''' )
__UpperCamelCase = original_model.decoder.tokenizer(lowercase_ , add_special_tokens=lowercase_ , return_tensors='''pt''' )[
'''input_ids'''
]
__UpperCamelCase = original_model.encoder.model.patch_embed(lowercase_ )
__UpperCamelCase , __UpperCamelCase = model.encoder.embeddings(lowercase_ )
assert torch.allclose(lowercase_ , lowercase_ , atol=1E-3 )
# verify encoder hidden states
__UpperCamelCase = original_model.encoder(lowercase_ )
__UpperCamelCase = model.encoder(lowercase_ ).last_hidden_state
assert torch.allclose(lowercase_ , lowercase_ , atol=1E-2 )
# verify decoder hidden states
__UpperCamelCase = original_model(lowercase_ , lowercase_ , lowercase_ ).logits
__UpperCamelCase = model(lowercase_ , decoder_input_ids=lowercase_ ).logits
assert torch.allclose(lowercase_ , lowercase_ , atol=1E-3 )
print('''Looks ok!''' )
if pytorch_dump_folder_path is not None:
print(F"Saving model and processor to {pytorch_dump_folder_path}" )
model.save_pretrained(lowercase_ )
processor.save_pretrained(lowercase_ )
if push_to_hub:
model.push_to_hub('''nielsr/''' + model_name.split('''/''' )[-1] , commit_message='''Update model''' )
processor.push_to_hub('''nielsr/''' + model_name.split('''/''' )[-1] , commit_message='''Update model''' )
if __name__ == "__main__":
a_ = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--model_name",
default="naver-clova-ix/donut-base-finetuned-docvqa",
required=False,
type=str,
help="Name of the original model you'd like to convert.",
)
parser.add_argument(
"--pytorch_dump_folder_path",
default=None,
required=False,
type=str,
help="Path to the output PyTorch model directory.",
)
parser.add_argument(
"--push_to_hub",
action="store_true",
help="Whether or not to push the converted model and processor to the 🤗 hub.",
)
a_ = parser.parse_args()
convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 375 | 1 |
import heapq as hq
import math
from collections.abc import Iterator
class lowerCAmelCase_ :
def __init__( self , _lowerCAmelCase ):
_lowercase : List[str] = str(id_ )
_lowercase : Tuple = None
_lowercase : Optional[Any] = None
_lowercase : List[Any] = []
_lowercase : List[str] = {} # {vertex:distance}
def __lt__( self , _lowerCAmelCase ):
return self.key < other.key
def __repr__( self ):
return self.id
def __a ( self , _lowerCAmelCase ):
self.neighbors.append(_lowerCAmelCase )
def __a ( self , _lowerCAmelCase , _lowerCAmelCase ):
_lowercase : Union[str, Any] = weight
def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]:
# add the neighbors:
graph[a - 1].add_neighbor(graph[b - 1] )
graph[b - 1].add_neighbor(graph[a - 1] )
# add the edges:
graph[a - 1].add_edge(graph[b - 1] , SCREAMING_SNAKE_CASE )
graph[b - 1].add_edge(graph[a - 1] , SCREAMING_SNAKE_CASE )
def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> list:
_lowercase : str = []
for u in graph:
_lowercase : Optional[Any] = math.inf
_lowercase : List[str] = None
_lowercase : str = 0
_lowercase : Any = graph[:]
while q:
_lowercase : str = min(SCREAMING_SNAKE_CASE )
q.remove(SCREAMING_SNAKE_CASE )
for v in u.neighbors:
if (v in q) and (u.edges[v.id] < v.key):
_lowercase : Any = u
_lowercase : Dict = u.edges[v.id]
for i in range(1 , len(SCREAMING_SNAKE_CASE ) ):
a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) )
return a
def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Iterator[tuple]:
for u in graph:
_lowercase : Optional[Any] = math.inf
_lowercase : Optional[int] = None
_lowercase : Tuple = 0
_lowercase : Optional[int] = list(SCREAMING_SNAKE_CASE )
hq.heapify(SCREAMING_SNAKE_CASE )
while h:
_lowercase : List[Any] = hq.heappop(SCREAMING_SNAKE_CASE )
for v in u.neighbors:
if (v in h) and (u.edges[v.id] < v.key):
_lowercase : Any = u
_lowercase : List[Any] = u.edges[v.id]
hq.heapify(SCREAMING_SNAKE_CASE )
for i in range(1 , len(SCREAMING_SNAKE_CASE ) ):
yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1)
def __magic_name__ ( ) -> None:
pass
if __name__ == "__main__":
import doctest
doctest.testmod()
| 66 |
"""simple docstring"""
from typing import List, Optional, TypeVar
from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets
from .dataset_dict import DatasetDict, IterableDatasetDict
from .info import DatasetInfo
from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasets
from .splits import NamedSplit
from .utils import logging
from .utils.py_utils import Literal
__A : Dict = logging.get_logger(__name__)
__A : List[Any] = TypeVar('''DatasetType''', Dataset, IterableDataset)
def A_ ( snake_case_ : List[DatasetType] ,snake_case_ : Optional[List[float]] = None ,snake_case_ : Optional[int] = None ,snake_case_ : Optional[DatasetInfo] = None ,snake_case_ : Optional[NamedSplit] = None ,snake_case_ : Literal["first_exhausted", "all_exhausted"] = "first_exhausted" ,):
'''simple docstring'''
from .arrow_dataset import Dataset
from .iterable_dataset import IterableDataset
if not datasets:
raise ValueError("""Unable to interleave an empty list of datasets.""" )
for i, dataset in enumerate(snake_case_ ):
if not isinstance(snake_case_ ,(Dataset, IterableDataset) ):
if isinstance(snake_case_ ,(DatasetDict, IterableDatasetDict) ):
if not dataset:
raise ValueError(
f'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} '
"""is an empty dataset dictionary.""" )
raise ValueError(
f'Dataset at position {i} has at least one split: {list(snake_case_ )}\n'
f'Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(snake_case_ ) )}\']' )
raise ValueError(
f'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(snake_case_ ).__name__}.' )
if i == 0:
UpperCamelCase , UpperCamelCase : Dict = (
(Dataset, IterableDataset) if isinstance(snake_case_ ,snake_case_ ) else (IterableDataset, Dataset)
)
elif not isinstance(snake_case_ ,snake_case_ ):
raise ValueError(
f'Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.' )
if stopping_strategy not in ["first_exhausted", "all_exhausted"]:
raise ValueError(f'{stopping_strategy} is not supported. Please enter a valid stopping_strategy.' )
if dataset_type is Dataset:
return _interleave_map_style_datasets(
snake_case_ ,snake_case_ ,snake_case_ ,info=snake_case_ ,split=snake_case_ ,stopping_strategy=snake_case_ )
else:
return _interleave_iterable_datasets(
snake_case_ ,snake_case_ ,snake_case_ ,info=snake_case_ ,split=snake_case_ ,stopping_strategy=snake_case_ )
def A_ ( snake_case_ : List[DatasetType] ,snake_case_ : Optional[DatasetInfo] = None ,snake_case_ : Optional[NamedSplit] = None ,snake_case_ : int = 0 ,):
'''simple docstring'''
if not dsets:
raise ValueError("""Unable to concatenate an empty list of datasets.""" )
for i, dataset in enumerate(snake_case_ ):
if not isinstance(snake_case_ ,(Dataset, IterableDataset) ):
if isinstance(snake_case_ ,(DatasetDict, IterableDatasetDict) ):
if not dataset:
raise ValueError(
f'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} '
"""is an empty dataset dictionary.""" )
raise ValueError(
f'Dataset at position {i} has at least one split: {list(snake_case_ )}\n'
f'Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(snake_case_ ) )}\']' )
raise ValueError(
f'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(snake_case_ ).__name__}.' )
if i == 0:
UpperCamelCase , UpperCamelCase : List[str] = (
(Dataset, IterableDataset) if isinstance(snake_case_ ,snake_case_ ) else (IterableDataset, Dataset)
)
elif not isinstance(snake_case_ ,snake_case_ ):
raise ValueError(
f'Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.' )
if dataset_type is Dataset:
return _concatenate_map_style_datasets(snake_case_ ,info=snake_case_ ,split=snake_case_ ,axis=snake_case_ )
else:
return _concatenate_iterable_datasets(snake_case_ ,info=snake_case_ ,split=snake_case_ ,axis=snake_case_ )
| 499 | 0 |
"""simple docstring"""
import numpy as np
from transformers import Pipeline
def __A (_SCREAMING_SNAKE_CASE ) ->List[Any]:
"""simple docstring"""
lowerCAmelCase__ :Union[str, Any] = np.max(_SCREAMING_SNAKE_CASE , axis=-1 , keepdims=_SCREAMING_SNAKE_CASE )
lowerCAmelCase__ :List[Any] = np.exp(outputs - maxes )
return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_SCREAMING_SNAKE_CASE )
class _lowerCAmelCase ( a ):
"""simple docstring"""
def snake_case ( self , **__UpperCAmelCase ):
'''simple docstring'''
lowerCAmelCase__ :Dict = {}
if "second_text" in kwargs:
lowerCAmelCase__ :str = kwargs['second_text']
return preprocess_kwargs, {}, {}
def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=None ):
'''simple docstring'''
return self.tokenizer(__UpperCAmelCase , text_pair=__UpperCAmelCase , return_tensors=self.framework )
def snake_case ( self , __UpperCAmelCase ):
'''simple docstring'''
return self.model(**__UpperCAmelCase )
def snake_case ( self , __UpperCAmelCase ):
'''simple docstring'''
lowerCAmelCase__ :Tuple = model_outputs.logits[0].numpy()
lowerCAmelCase__ :Optional[int] = softmax(__UpperCAmelCase )
lowerCAmelCase__ :Tuple = np.argmax(__UpperCAmelCase )
lowerCAmelCase__ :Optional[Any] = self.model.config.idalabel[best_class]
lowerCAmelCase__ :Optional[Any] = probabilities[best_class].item()
lowerCAmelCase__ :Optional[int] = logits.tolist()
return {"label": label, "score": score, "logits": logits}
| 560 |
"""simple docstring"""
import shutil
import tempfile
import unittest
import numpy as np
import pytest
from transformers.testing_utils import require_vision
from transformers.utils import is_vision_available
if is_vision_available():
from PIL import Image
from transformers import AutoProcessor, BlipaProcessor, BlipImageProcessor, GPTaTokenizer, PreTrainedTokenizerFast
@require_vision
class _lowerCAmelCase ( unittest.TestCase ):
"""simple docstring"""
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :List[str] = tempfile.mkdtemp()
lowerCAmelCase__ :Optional[Any] = BlipImageProcessor()
lowerCAmelCase__ :Union[str, Any] = GPTaTokenizer.from_pretrained('hf-internal-testing/tiny-random-GPT2Model' )
lowerCAmelCase__ :Any = BlipaProcessor(__UpperCAmelCase , __UpperCAmelCase )
processor.save_pretrained(self.tmpdirname )
def snake_case ( self , **__UpperCAmelCase ):
'''simple docstring'''
return AutoProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ).tokenizer
def snake_case ( self , **__UpperCAmelCase ):
'''simple docstring'''
return AutoProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ).image_processor
def snake_case ( self ):
'''simple docstring'''
shutil.rmtree(self.tmpdirname )
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Any = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )]
lowerCAmelCase__ :int = [Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Union[str, Any] = BlipaProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
lowerCAmelCase__ :int = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' )
lowerCAmelCase__ :Any = self.get_image_processor(do_normalize=__UpperCAmelCase , padding_value=1.0 )
lowerCAmelCase__ :int = BlipaProcessor.from_pretrained(
self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=__UpperCAmelCase , padding_value=1.0 )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer , __UpperCAmelCase )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , __UpperCAmelCase )
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Any = self.get_image_processor()
lowerCAmelCase__ :Union[str, Any] = self.get_tokenizer()
lowerCAmelCase__ :Dict = BlipaProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase )
lowerCAmelCase__ :List[Any] = self.prepare_image_inputs()
lowerCAmelCase__ :int = image_processor(__UpperCAmelCase , return_tensors='np' )
lowerCAmelCase__ :Optional[int] = processor(images=__UpperCAmelCase , return_tensors='np' )
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 )
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Tuple = self.get_image_processor()
lowerCAmelCase__ :Any = self.get_tokenizer()
lowerCAmelCase__ :Any = BlipaProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase )
lowerCAmelCase__ :str = 'lower newer'
lowerCAmelCase__ :Optional[int] = processor(text=__UpperCAmelCase )
lowerCAmelCase__ :str = tokenizer(__UpperCAmelCase , return_token_type_ids=__UpperCAmelCase )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Dict = self.get_image_processor()
lowerCAmelCase__ :List[str] = self.get_tokenizer()
lowerCAmelCase__ :Optional[int] = BlipaProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase )
lowerCAmelCase__ :List[Any] = 'lower newer'
lowerCAmelCase__ :Tuple = self.prepare_image_inputs()
lowerCAmelCase__ :Dict = processor(text=__UpperCAmelCase , images=__UpperCAmelCase )
self.assertListEqual(list(inputs.keys() ) , ['pixel_values', 'input_ids', 'attention_mask'] )
# test if it raises when no input is passed
with pytest.raises(__UpperCAmelCase ):
processor()
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Optional[int] = self.get_image_processor()
lowerCAmelCase__ :Dict = self.get_tokenizer()
lowerCAmelCase__ :Any = BlipaProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase )
lowerCAmelCase__ :Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
lowerCAmelCase__ :Tuple = processor.batch_decode(__UpperCAmelCase )
lowerCAmelCase__ :Union[str, Any] = tokenizer.batch_decode(__UpperCAmelCase )
self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :List[str] = self.get_image_processor()
lowerCAmelCase__ :int = self.get_tokenizer()
lowerCAmelCase__ :Tuple = BlipaProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase )
lowerCAmelCase__ :Union[str, Any] = 'lower newer'
lowerCAmelCase__ :Tuple = self.prepare_image_inputs()
lowerCAmelCase__ :Optional[int] = processor(text=__UpperCAmelCase , images=__UpperCAmelCase )
# For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask']
self.assertListEqual(list(inputs.keys() ) , ['pixel_values', 'input_ids', 'attention_mask'] )
| 560 | 1 |
"""simple docstring"""
from typing import Optional, Union
import torch
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_mobilenet_va import MobileNetVaConfig
_a : Any = logging.get_logger(__name__)
# General docstring
_a : Dict = 'MobileNetV1Config'
# Base docstring
_a : Dict = 'google/mobilenet_v1_1.0_224'
_a : Dict = [1, 1_024, 7, 7]
# Image classification docstring
_a : Dict = 'google/mobilenet_v1_1.0_224'
_a : Any = 'tabby, tabby cat'
_a : int = [
'google/mobilenet_v1_1.0_224',
'google/mobilenet_v1_0.75_192',
# See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
]
def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[str] ,_lowerCamelCase : str ,_lowerCamelCase : Dict=None ) -> List[Any]:
_lowerCAmelCase : Any = {}
if isinstance(_lowerCamelCase ,_lowerCamelCase ):
_lowerCAmelCase : Tuple = model.mobilenet_va
else:
_lowerCAmelCase : int = model
_lowerCAmelCase : Union[str, Any] = """MobilenetV1/Conv2d_0/"""
_lowerCAmelCase : List[Any] = backbone.conv_stem.convolution.weight
_lowerCAmelCase : Dict = backbone.conv_stem.normalization.bias
_lowerCAmelCase : int = backbone.conv_stem.normalization.weight
_lowerCAmelCase : List[str] = backbone.conv_stem.normalization.running_mean
_lowerCAmelCase : Optional[Any] = backbone.conv_stem.normalization.running_var
for i in range(13 ):
_lowerCAmelCase : int = i + 1
_lowerCAmelCase : Union[str, Any] = i * 2
_lowerCAmelCase : Union[str, Any] = backbone.layer[pt_index]
_lowerCAmelCase : Optional[int] = f"MobilenetV1/Conv2d_{tf_index}_depthwise/"
_lowerCAmelCase : Optional[Any] = pointer.convolution.weight
_lowerCAmelCase : Optional[Any] = pointer.normalization.bias
_lowerCAmelCase : Optional[int] = pointer.normalization.weight
_lowerCAmelCase : Optional[int] = pointer.normalization.running_mean
_lowerCAmelCase : int = pointer.normalization.running_var
_lowerCAmelCase : int = backbone.layer[pt_index + 1]
_lowerCAmelCase : Tuple = f"MobilenetV1/Conv2d_{tf_index}_pointwise/"
_lowerCAmelCase : Dict = pointer.convolution.weight
_lowerCAmelCase : Dict = pointer.normalization.bias
_lowerCAmelCase : Tuple = pointer.normalization.weight
_lowerCAmelCase : str = pointer.normalization.running_mean
_lowerCAmelCase : str = pointer.normalization.running_var
if isinstance(_lowerCamelCase ,_lowerCamelCase ):
_lowerCAmelCase : Dict = """MobilenetV1/Logits/Conv2d_1c_1x1/"""
_lowerCAmelCase : Tuple = model.classifier.weight
_lowerCAmelCase : Any = model.classifier.bias
return tf_to_pt_map
def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any] ,_lowerCamelCase : int ,_lowerCamelCase : int ) -> Union[str, Any]:
try:
import numpy as np
import tensorflow as tf
except ImportError:
logger.error(
"""Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see """
"""https://www.tensorflow.org/install/ for installation instructions.""" )
raise
# Load weights from TF model
_lowerCAmelCase : Any = tf.train.list_variables(_lowerCamelCase )
_lowerCAmelCase : Any = {}
for name, shape in init_vars:
logger.info(f"Loading TF weight {name} with shape {shape}" )
_lowerCAmelCase : Any = tf.train.load_variable(_lowerCamelCase ,_lowerCamelCase )
_lowerCAmelCase : Optional[Any] = array
# Build TF to PyTorch weights loading map
_lowerCAmelCase : int = _build_tf_to_pytorch_map(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase )
for name, pointer in tf_to_pt_map.items():
logger.info(f"Importing {name}" )
if name not in tf_weights:
logger.info(f"{name} not in tf pre-trained weights, skipping" )
continue
_lowerCAmelCase : Optional[int] = tf_weights[name]
if "depthwise_weights" in name:
logger.info("""Transposing depthwise""" )
_lowerCAmelCase : Dict = np.transpose(_lowerCamelCase ,(2, 3, 0, 1) )
elif "weights" in name:
logger.info("""Transposing""" )
if len(pointer.shape ) == 2: # copying into linear layer
_lowerCAmelCase : List[str] = array.squeeze().transpose()
else:
_lowerCAmelCase : str = np.transpose(_lowerCamelCase ,(3, 2, 0, 1) )
if pointer.shape != array.shape:
raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched" )
logger.info(f"Initialize PyTorch weight {name} {array.shape}" )
_lowerCAmelCase : Optional[Any] = torch.from_numpy(_lowerCamelCase )
tf_weights.pop(_lowerCamelCase ,_lowerCamelCase )
tf_weights.pop(name + """/RMSProp""" ,_lowerCamelCase )
tf_weights.pop(name + """/RMSProp_1""" ,_lowerCamelCase )
tf_weights.pop(name + """/ExponentialMovingAverage""" ,_lowerCamelCase )
logger.info(f"Weights not copied to PyTorch model: {', '.join(tf_weights.keys() )}" )
return model
def SCREAMING_SNAKE_CASE ( _lowerCamelCase : torch.Tensor ,_lowerCamelCase : nn.Convad ) -> torch.Tensor:
_lowerCAmelCase , _lowerCAmelCase : Any = features.shape[-2:]
_lowerCAmelCase , _lowerCAmelCase : Dict = conv_layer.stride
_lowerCAmelCase , _lowerCAmelCase : int = conv_layer.kernel_size
if in_height % stride_height == 0:
_lowerCAmelCase : Optional[int] = max(kernel_height - stride_height ,0 )
else:
_lowerCAmelCase : int = max(kernel_height - (in_height % stride_height) ,0 )
if in_width % stride_width == 0:
_lowerCAmelCase : List[str] = max(kernel_width - stride_width ,0 )
else:
_lowerCAmelCase : Union[str, Any] = max(kernel_width - (in_width % stride_width) ,0 )
_lowerCAmelCase : Union[str, Any] = pad_along_width // 2
_lowerCAmelCase : Tuple = pad_along_width - pad_left
_lowerCAmelCase : Tuple = pad_along_height // 2
_lowerCAmelCase : str = pad_along_height - pad_top
_lowerCAmelCase : Tuple = (pad_left, pad_right, pad_top, pad_bottom)
return nn.functional.pad(_lowerCamelCase ,_lowerCamelCase ,"""constant""" ,0.0 )
class __A ( nn.Module ):
def __init__( self , a__ , a__ , a__ , a__ , a__ = 1 , a__ = 1 , a__ = False , a__ = True , a__ = True , ):
super().__init__()
_lowerCAmelCase : Dict = config
if in_channels % groups != 0:
raise ValueError(F"Input channels ({in_channels}) are not divisible by {groups} groups." )
if out_channels % groups != 0:
raise ValueError(F"Output channels ({out_channels}) are not divisible by {groups} groups." )
_lowerCAmelCase : int = 0 if config.tf_padding else int((kernel_size - 1) / 2 )
_lowerCAmelCase : int = nn.Convad(
in_channels=a__ , out_channels=a__ , kernel_size=a__ , stride=a__ , padding=a__ , groups=a__ , bias=a__ , padding_mode="""zeros""" , )
if use_normalization:
_lowerCAmelCase : Dict = nn.BatchNormad(
num_features=a__ , eps=config.layer_norm_eps , momentum=0.9_9_9_7 , affine=a__ , track_running_stats=a__ , )
else:
_lowerCAmelCase : Any = None
if use_activation:
if isinstance(a__ , a__ ):
_lowerCAmelCase : Tuple = ACTaFN[use_activation]
elif isinstance(config.hidden_act , a__ ):
_lowerCAmelCase : int = ACTaFN[config.hidden_act]
else:
_lowerCAmelCase : List[Any] = config.hidden_act
else:
_lowerCAmelCase : int = None
def __A ( self , a__ ):
if self.config.tf_padding:
_lowerCAmelCase : Dict = apply_tf_padding(a__ , self.convolution )
_lowerCAmelCase : Optional[int] = self.convolution(a__ )
if self.normalization is not None:
_lowerCAmelCase : Tuple = self.normalization(a__ )
if self.activation is not None:
_lowerCAmelCase : List[str] = self.activation(a__ )
return features
class __A ( SCREAMING_SNAKE_CASE_ ):
_UpperCamelCase : Optional[Any] = MobileNetVaConfig
_UpperCamelCase : List[Any] = load_tf_weights_in_mobilenet_va
_UpperCamelCase : List[Any] = "mobilenet_v1"
_UpperCamelCase : Union[str, Any] = "pixel_values"
_UpperCamelCase : Any = False
def __A ( self , a__ ):
if isinstance(a__ , (nn.Linear, nn.Convad) ):
module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range )
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(a__ , nn.BatchNormad ):
module.bias.data.zero_()
module.weight.data.fill_(1.0 )
_a : str = r'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n'
_a : List[Any] = r'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`MobileNetV1ImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n'
@add_start_docstrings(
"The bare MobileNetV1 model outputting raw hidden-states without any specific head on top." , SCREAMING_SNAKE_CASE_ , )
class __A ( SCREAMING_SNAKE_CASE_ ):
def __init__( self , a__ , a__ = True ):
super().__init__(a__ )
_lowerCAmelCase : Any = config
_lowerCAmelCase : str = 32
_lowerCAmelCase : List[str] = max(int(depth * config.depth_multiplier ) , config.min_depth )
_lowerCAmelCase : Dict = MobileNetVaConvLayer(
a__ , in_channels=config.num_channels , out_channels=a__ , kernel_size=3 , stride=2 , )
_lowerCAmelCase : Dict = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]
_lowerCAmelCase : Dict = nn.ModuleList()
for i in range(13 ):
_lowerCAmelCase : str = out_channels
if strides[i] == 2 or i == 0:
depth *= 2
_lowerCAmelCase : List[str] = max(int(depth * config.depth_multiplier ) , config.min_depth )
self.layer.append(
MobileNetVaConvLayer(
a__ , in_channels=a__ , out_channels=a__ , kernel_size=3 , stride=strides[i] , groups=a__ , ) )
self.layer.append(
MobileNetVaConvLayer(
a__ , in_channels=a__ , out_channels=a__ , kernel_size=1 , ) )
_lowerCAmelCase : str = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None
# Initialize weights and apply final processing
self.post_init()
def __A ( self , a__ ):
raise NotImplementedError
@add_start_docstrings_to_model_forward(a__ )
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC , output_type=a__ , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , )
def __A ( self , a__ = None , a__ = None , a__ = None , ):
_lowerCAmelCase : Optional[int] = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
_lowerCAmelCase : Any = return_dict if return_dict is not None else self.config.use_return_dict
if pixel_values is None:
raise ValueError("""You have to specify pixel_values""" )
_lowerCAmelCase : Optional[int] = self.conv_stem(a__ )
_lowerCAmelCase : Dict = () if output_hidden_states else None
for i, layer_module in enumerate(self.layer ):
_lowerCAmelCase : List[str] = layer_module(a__ )
if output_hidden_states:
_lowerCAmelCase : List[str] = all_hidden_states + (hidden_states,)
_lowerCAmelCase : int = hidden_states
if self.pooler is not None:
_lowerCAmelCase : str = torch.flatten(self.pooler(a__ ) , start_dim=1 )
else:
_lowerCAmelCase : Optional[int] = None
if not return_dict:
return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None )
return BaseModelOutputWithPoolingAndNoAttention(
last_hidden_state=a__ , pooler_output=a__ , hidden_states=a__ , )
@add_start_docstrings(
"\n MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , SCREAMING_SNAKE_CASE_ , )
class __A ( SCREAMING_SNAKE_CASE_ ):
def __init__( self , a__ ):
super().__init__(a__ )
_lowerCAmelCase : Union[str, Any] = config.num_labels
_lowerCAmelCase : Dict = MobileNetVaModel(a__ )
_lowerCAmelCase : Dict = self.mobilenet_va.layer[-1].convolution.out_channels
# Classifier head
_lowerCAmelCase : Tuple = nn.Dropout(config.classifier_dropout_prob , inplace=a__ )
_lowerCAmelCase : Any = nn.Linear(a__ , config.num_labels ) if config.num_labels > 0 else nn.Identity()
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(a__ )
@add_code_sample_docstrings(
checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=a__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , )
def __A ( self , a__ = None , a__ = None , a__ = None , a__ = None , ):
_lowerCAmelCase : Tuple = return_dict if return_dict is not None else self.config.use_return_dict
_lowerCAmelCase : List[str] = self.mobilenet_va(a__ , output_hidden_states=a__ , return_dict=a__ )
_lowerCAmelCase : str = outputs.pooler_output if return_dict else outputs[1]
_lowerCAmelCase : Union[str, Any] = self.classifier(self.dropout(a__ ) )
_lowerCAmelCase : List[Any] = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
_lowerCAmelCase : Dict = """regression"""
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
_lowerCAmelCase : Dict = """single_label_classification"""
else:
_lowerCAmelCase : Dict = """multi_label_classification"""
if self.config.problem_type == "regression":
_lowerCAmelCase : Tuple = MSELoss()
if self.num_labels == 1:
_lowerCAmelCase : Optional[Any] = loss_fct(logits.squeeze() , labels.squeeze() )
else:
_lowerCAmelCase : str = loss_fct(a__ , a__ )
elif self.config.problem_type == "single_label_classification":
_lowerCAmelCase : List[Any] = CrossEntropyLoss()
_lowerCAmelCase : Optional[int] = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) )
elif self.config.problem_type == "multi_label_classification":
_lowerCAmelCase : Any = BCEWithLogitsLoss()
_lowerCAmelCase : Optional[Any] = loss_fct(a__ , a__ )
if not return_dict:
_lowerCAmelCase : Any = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return ImageClassifierOutputWithNoAttention(
loss=a__ , logits=a__ , hidden_states=outputs.hidden_states , )
| 213 |
"""simple docstring"""
import random
import unittest
import numpy as np
import torch
from diffusers import (
DPMSolverMultistepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
LMSDiscreteScheduler,
OnnxStableDiffusionUpscalePipeline,
PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
is_onnx_available,
load_image,
nightly,
require_onnxruntime,
require_torch_gpu,
)
from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin
if is_onnx_available():
import onnxruntime as ort
class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ):
# TODO: is there an appropriate internal test set?
_UpperCamelCase : int = "ssube/stable-diffusion-x4-upscaler-onnx"
def __A ( self , a__=0 ):
_lowerCAmelCase : Optional[int] = floats_tensor((1, 3, 128, 128) , rng=random.Random(a__ ) )
_lowerCAmelCase : List[Any] = torch.manual_seed(a__ )
_lowerCAmelCase : Any = {
"""prompt""": """A painting of a squirrel eating a burger""",
"""image""": image,
"""generator""": generator,
"""num_inference_steps""": 3,
"""guidance_scale""": 7.5,
"""output_type""": """numpy""",
}
return inputs
def __A ( self ):
_lowerCAmelCase : Optional[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" )
pipe.set_progress_bar_config(disable=a__ )
_lowerCAmelCase : List[Any] = self.get_dummy_inputs()
_lowerCAmelCase : Any = pipe(**a__ ).images
_lowerCAmelCase : Optional[Any] = image[0, -3:, -3:, -1].flatten()
# started as 128, should now be 512
assert image.shape == (1, 512, 512, 3)
_lowerCAmelCase : List[Any] = np.array(
[0.6_9_7_4_7_8_2, 0.6_8_9_0_2_0_9_3, 0.7_0_1_3_5_8_8_5, 0.7_5_8_3_6_1_8, 0.7_8_0_4_5_4_5, 0.7_8_5_4_9_1_2, 0.7_8_6_6_7_4_2_6, 0.7_8_7_4_3_8_6_3, 0.7_8_0_7_0_2_2_3] )
assert np.abs(image_slice - expected_slice ).max() < 1e-1
def __A ( self ):
_lowerCAmelCase : List[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" )
_lowerCAmelCase : Optional[int] = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=a__ )
pipe.set_progress_bar_config(disable=a__ )
_lowerCAmelCase : Dict = self.get_dummy_inputs()
_lowerCAmelCase : Any = pipe(**a__ ).images
_lowerCAmelCase : Union[str, Any] = image[0, -3:, -3:, -1]
assert image.shape == (1, 512, 512, 3)
_lowerCAmelCase : Any = np.array(
[0.6_8_9_8_8_9_2, 0.5_9_2_4_0_5_5_6, 0.5_2_4_9_9_5_2_7, 0.5_8_8_6_6_2_1_5, 0.5_2_2_5_8_2_3_5, 0.5_2_5_7_2_7_1_5, 0.6_2_4_1_4_4_7_3, 0.6_1_7_4_3_8_7, 0.6_2_1_4_9_6_4] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
def __A ( self ):
_lowerCAmelCase : str = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" )
_lowerCAmelCase : Dict = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=a__ )
_lowerCAmelCase : str = self.get_dummy_inputs()
_lowerCAmelCase : str = pipe(**a__ ).images
_lowerCAmelCase : Any = image[0, -3:, -3:, -1]
assert image.shape == (1, 512, 512, 3)
_lowerCAmelCase : Any = np.array(
[0.7_6_5_9_2_7_8, 0.7_6_4_3_7_6_6_4, 0.7_5_5_7_9_1_0_7, 0.7_6_9_1_1_1_6, 0.7_7_6_6_6_9_8_6, 0.7_7_2_7_6_7_2, 0.7_7_5_8_6_6_4, 0.7_8_1_2_2_2_6, 0.7_6_9_4_2_5_1_5] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
def __A ( self ):
_lowerCAmelCase : Union[str, Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" )
_lowerCAmelCase : Union[str, Any] = EulerDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=a__ )
_lowerCAmelCase : Any = self.get_dummy_inputs()
_lowerCAmelCase : str = pipe(**a__ ).images
_lowerCAmelCase : int = image[0, -3:, -3:, -1]
assert image.shape == (1, 512, 512, 3)
_lowerCAmelCase : List[str] = np.array(
[0.6_9_7_4_7_8_2, 0.6_8_9_0_2_0_9_3, 0.7_0_1_3_5_8_8_5, 0.7_5_8_3_6_1_8, 0.7_8_0_4_5_4_5, 0.7_8_5_4_9_1_2, 0.7_8_6_6_7_4_2_6, 0.7_8_7_4_3_8_6_3, 0.7_8_0_7_0_2_2_3] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
def __A ( self ):
_lowerCAmelCase : Optional[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" )
_lowerCAmelCase : Tuple = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=a__ )
_lowerCAmelCase : Tuple = self.get_dummy_inputs()
_lowerCAmelCase : Any = pipe(**a__ ).images
_lowerCAmelCase : int = image[0, -3:, -3:, -1]
assert image.shape == (1, 512, 512, 3)
_lowerCAmelCase : Dict = np.array(
[0.7_7_4_2_4_4_9_6, 0.7_7_3_6_0_1, 0.7_6_4_5_2_8_8, 0.7_7_6_9_5_9_8, 0.7_7_7_2_7_3_9, 0.7_7_3_8_6_8_8, 0.7_8_1_8_7_2_3_3, 0.7_7_8_7_9_5_8_4, 0.7_6_7_0_4_3] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
@nightly
@require_onnxruntime
@require_torch_gpu
class __A ( unittest.TestCase ):
@property
def __A ( self ):
return (
"CUDAExecutionProvider",
{
"gpu_mem_limit": "15000000000", # 15GB
"arena_extend_strategy": "kSameAsRequested",
},
)
@property
def __A ( self ):
_lowerCAmelCase : str = ort.SessionOptions()
_lowerCAmelCase : Tuple = False
return options
def __A ( self ):
_lowerCAmelCase : str = load_image(
"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
"""/img2img/sketch-mountains-input.jpg""" )
_lowerCAmelCase : Any = init_image.resize((128, 128) )
# using the PNDM scheduler by default
_lowerCAmelCase : str = OnnxStableDiffusionUpscalePipeline.from_pretrained(
"""ssube/stable-diffusion-x4-upscaler-onnx""" , provider=self.gpu_provider , sess_options=self.gpu_options , )
pipe.set_progress_bar_config(disable=a__ )
_lowerCAmelCase : Optional[int] = """A fantasy landscape, trending on artstation"""
_lowerCAmelCase : List[str] = torch.manual_seed(0 )
_lowerCAmelCase : Dict = pipe(
prompt=a__ , image=a__ , guidance_scale=7.5 , num_inference_steps=10 , generator=a__ , output_type="""np""" , )
_lowerCAmelCase : List[str] = output.images
_lowerCAmelCase : Tuple = images[0, 255:258, 383:386, -1]
assert images.shape == (1, 512, 512, 3)
_lowerCAmelCase : Dict = np.array([0.4_8_8_3, 0.4_9_4_7, 0.4_9_8_0, 0.4_9_7_5, 0.4_9_8_2, 0.4_9_8_0, 0.5_0_0_0, 0.5_0_0_6, 0.4_9_7_2] )
# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues
assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
def __A ( self ):
_lowerCAmelCase : Optional[int] = load_image(
"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
"""/img2img/sketch-mountains-input.jpg""" )
_lowerCAmelCase : Union[str, Any] = init_image.resize((128, 128) )
_lowerCAmelCase : int = LMSDiscreteScheduler.from_pretrained(
"""ssube/stable-diffusion-x4-upscaler-onnx""" , subfolder="""scheduler""" )
_lowerCAmelCase : int = OnnxStableDiffusionUpscalePipeline.from_pretrained(
"""ssube/stable-diffusion-x4-upscaler-onnx""" , scheduler=a__ , provider=self.gpu_provider , sess_options=self.gpu_options , )
pipe.set_progress_bar_config(disable=a__ )
_lowerCAmelCase : List[Any] = """A fantasy landscape, trending on artstation"""
_lowerCAmelCase : List[Any] = torch.manual_seed(0 )
_lowerCAmelCase : Optional[int] = pipe(
prompt=a__ , image=a__ , guidance_scale=7.5 , num_inference_steps=20 , generator=a__ , output_type="""np""" , )
_lowerCAmelCase : List[Any] = output.images
_lowerCAmelCase : Optional[Any] = images[0, 255:258, 383:386, -1]
assert images.shape == (1, 512, 512, 3)
_lowerCAmelCase : Optional[Any] = np.array(
[0.5_0_1_7_3_7_5_3, 0.5_0_2_2_3_3_5_6, 0.5_0_2_0_3_9, 0.5_0_2_3_3_0_3_6, 0.5_0_2_3_7_2_5, 0.5_0_2_2_6_0_1, 0.5_0_1_8_7_5_8, 0.5_0_2_3_4_0_8_5, 0.5_0_2_4_1_5_6_6] )
# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues
assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
| 213 | 1 |
'''simple docstring'''
import tensorflow as tf
from ...tf_utils import shape_list
class SCREAMING_SNAKE_CASE( tf.keras.layers.Layer ):
def __init__( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=1 , lowerCamelCase__=False , **lowerCamelCase__ ) -> List[Any]:
"""simple docstring"""
super().__init__(**lowerCamelCase__ )
__lowercase = vocab_size
__lowercase = d_embed
__lowercase = d_proj
__lowercase = cutoffs + [vocab_size]
__lowercase = [0] + self.cutoffs
__lowercase = div_val
__lowercase = self.cutoffs[0]
__lowercase = len(self.cutoffs ) - 1
__lowercase = self.shortlist_size + self.n_clusters
__lowercase = keep_order
__lowercase = []
__lowercase = []
def snake_case__ ( self , lowerCamelCase__ ) -> Tuple:
"""simple docstring"""
if self.n_clusters > 0:
__lowercase = self.add_weight(
shape=(self.n_clusters, self.d_embed) , initializer="""zeros""" , trainable=lowerCamelCase__ , name="""cluster_weight""" )
__lowercase = self.add_weight(
shape=(self.n_clusters,) , initializer="""zeros""" , trainable=lowerCamelCase__ , name="""cluster_bias""" )
if self.div_val == 1:
for i in range(len(self.cutoffs ) ):
if self.d_proj != self.d_embed:
__lowercase = self.add_weight(
shape=(self.d_embed, self.d_proj) , initializer="""zeros""" , trainable=lowerCamelCase__ , name=F'out_projs_._{i}' , )
self.out_projs.append(lowerCamelCase__ )
else:
self.out_projs.append(lowerCamelCase__ )
__lowercase = self.add_weight(
shape=(self.vocab_size, self.d_embed) , initializer="""zeros""" , trainable=lowerCamelCase__ , name=F'out_layers_._{i}_._weight' , )
__lowercase = self.add_weight(
shape=(self.vocab_size,) , initializer="""zeros""" , trainable=lowerCamelCase__ , name=F'out_layers_._{i}_._bias' , )
self.out_layers.append((weight, bias) )
else:
for i in range(len(self.cutoffs ) ):
__lowercase ,__lowercase = self.cutoff_ends[i], self.cutoff_ends[i + 1]
__lowercase = self.d_embed // (self.div_val**i)
__lowercase = self.add_weight(
shape=(d_emb_i, self.d_proj) , initializer="""zeros""" , trainable=lowerCamelCase__ , name=F'out_projs_._{i}' )
self.out_projs.append(lowerCamelCase__ )
__lowercase = self.add_weight(
shape=(r_idx - l_idx, d_emb_i) , initializer="""zeros""" , trainable=lowerCamelCase__ , name=F'out_layers_._{i}_._weight' , )
__lowercase = self.add_weight(
shape=(r_idx - l_idx,) , initializer="""zeros""" , trainable=lowerCamelCase__ , name=F'out_layers_._{i}_._bias' , )
self.out_layers.append((weight, bias) )
super().build(lowerCamelCase__ )
@staticmethod
def snake_case__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None ) -> Optional[int]:
"""simple docstring"""
__lowercase = x
if proj is not None:
__lowercase = tf.einsum("""ibd,ed->ibe""" , lowerCamelCase__ , lowerCamelCase__ )
return tf.einsum("""ibd,nd->ibn""" , lowerCamelCase__ , lowerCamelCase__ ) + b
@staticmethod
def snake_case__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int:
"""simple docstring"""
__lowercase = shape_list(lowerCamelCase__ )
__lowercase = tf.range(lp_size[0] , dtype=target.dtype )
__lowercase = tf.stack([r, target] , 1 )
return tf.gather_nd(lowerCamelCase__ , lowerCamelCase__ )
def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=True , lowerCamelCase__=False ) -> Optional[Any]:
"""simple docstring"""
__lowercase = 0
if self.n_clusters == 0:
__lowercase = self._logit(lowerCamelCase__ , self.out_layers[0][0] , self.out_layers[0][1] , self.out_projs[0] )
if target is not None:
__lowercase = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=lowerCamelCase__ , logits=lowerCamelCase__ )
__lowercase = tf.nn.log_softmax(lowerCamelCase__ , axis=-1 )
else:
__lowercase = shape_list(lowerCamelCase__ )
__lowercase = []
__lowercase = tf.zeros(hidden_sizes[:2] )
for i in range(len(self.cutoffs ) ):
__lowercase ,__lowercase = self.cutoff_ends[i], self.cutoff_ends[i + 1]
if target is not None:
__lowercase = (target >= l_idx) & (target < r_idx)
__lowercase = tf.where(lowerCamelCase__ )
__lowercase = tf.boolean_mask(lowerCamelCase__ , lowerCamelCase__ ) - l_idx
if self.div_val == 1:
__lowercase = self.out_layers[0][0][l_idx:r_idx]
__lowercase = self.out_layers[0][1][l_idx:r_idx]
else:
__lowercase = self.out_layers[i][0]
__lowercase = self.out_layers[i][1]
if i == 0:
__lowercase = tf.concat([cur_W, self.cluster_weight] , 0 )
__lowercase = tf.concat([cur_b, self.cluster_bias] , 0 )
__lowercase = self._logit(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , self.out_projs[0] )
__lowercase = tf.nn.log_softmax(lowerCamelCase__ )
out.append(head_logprob[..., : self.cutoffs[0]] )
if target is not None:
__lowercase = tf.boolean_mask(lowerCamelCase__ , lowerCamelCase__ )
__lowercase = self._gather_logprob(lowerCamelCase__ , lowerCamelCase__ )
else:
__lowercase = self._logit(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , self.out_projs[i] )
__lowercase = tf.nn.log_softmax(lowerCamelCase__ )
__lowercase = self.cutoffs[0] + i - 1 # No probability for the head cluster
__lowercase = head_logprob[..., cluster_prob_idx, None] + tail_logprob
out.append(lowerCamelCase__ )
if target is not None:
__lowercase = tf.boolean_mask(lowerCamelCase__ , lowerCamelCase__ )
__lowercase = tf.boolean_mask(lowerCamelCase__ , lowerCamelCase__ )
__lowercase = self._gather_logprob(lowerCamelCase__ , lowerCamelCase__ )
cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1]
if target is not None:
loss += tf.scatter_nd(lowerCamelCase__ , -cur_logprob , shape_list(lowerCamelCase__ ) )
__lowercase = tf.concat(lowerCamelCase__ , axis=-1 )
if target is not None:
if return_mean:
__lowercase = tf.reduce_mean(lowerCamelCase__ )
# Add the training-time loss value to the layer using `self.add_loss()`.
self.add_loss(lowerCamelCase__ )
# Log the loss as a metric (we could log arbitrary metrics,
# including different metrics for training and inference.
self.add_metric(lowerCamelCase__ , name=self.name , aggregation="""mean""" if return_mean else """""" )
return out
| 163 |
'''simple docstring'''
from __future__ import annotations
import unittest
import numpy as np
from transformers import LayoutLMConfig, is_tf_available
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers.models.layoutlm.modeling_tf_layoutlm import (
TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
TFLayoutLMForMaskedLM,
TFLayoutLMForQuestionAnswering,
TFLayoutLMForSequenceClassification,
TFLayoutLMForTokenClassification,
TFLayoutLMModel,
)
class SCREAMING_SNAKE_CASE:
def __init__( self , lowerCamelCase__ , lowerCamelCase__=13 , lowerCamelCase__=7 , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=99 , lowerCamelCase__=32 , lowerCamelCase__=2 , lowerCamelCase__=4 , lowerCamelCase__=37 , lowerCamelCase__="gelu" , lowerCamelCase__=0.1 , lowerCamelCase__=0.1 , lowerCamelCase__=512 , lowerCamelCase__=16 , lowerCamelCase__=2 , lowerCamelCase__=0.02 , lowerCamelCase__=3 , lowerCamelCase__=4 , lowerCamelCase__=None , lowerCamelCase__=1000 , ) -> Union[str, Any]:
"""simple docstring"""
__lowercase = parent
__lowercase = batch_size
__lowercase = seq_length
__lowercase = is_training
__lowercase = use_input_mask
__lowercase = use_token_type_ids
__lowercase = use_labels
__lowercase = vocab_size
__lowercase = hidden_size
__lowercase = num_hidden_layers
__lowercase = num_attention_heads
__lowercase = intermediate_size
__lowercase = hidden_act
__lowercase = hidden_dropout_prob
__lowercase = attention_probs_dropout_prob
__lowercase = max_position_embeddings
__lowercase = type_vocab_size
__lowercase = type_sequence_label_size
__lowercase = initializer_range
__lowercase = num_labels
__lowercase = num_choices
__lowercase = scope
__lowercase = range_bbox
def snake_case__ ( self ) -> Tuple:
"""simple docstring"""
__lowercase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
# convert bbox to numpy since TF does not support item assignment
__lowercase = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ).numpy()
# Ensure that bbox is legal
for i in range(bbox.shape[0] ):
for j in range(bbox.shape[1] ):
if bbox[i, j, 3] < bbox[i, j, 1]:
__lowercase = bbox[i, j, 3]
__lowercase = bbox[i, j, 1]
__lowercase = t
if bbox[i, j, 2] < bbox[i, j, 0]:
__lowercase = bbox[i, j, 2]
__lowercase = bbox[i, j, 0]
__lowercase = t
__lowercase = tf.convert_to_tensor(lowerCamelCase__ )
__lowercase = None
if self.use_input_mask:
__lowercase = random_attention_mask([self.batch_size, self.seq_length] )
__lowercase = None
if self.use_token_type_ids:
__lowercase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
__lowercase = None
__lowercase = None
__lowercase = None
if self.use_labels:
__lowercase = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__lowercase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__lowercase = ids_tensor([self.batch_size] , self.num_choices )
__lowercase = LayoutLMConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , )
return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]:
"""simple docstring"""
__lowercase = TFLayoutLMModel(config=lowerCamelCase__ )
__lowercase = model(lowerCamelCase__ , lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ )
__lowercase = model(lowerCamelCase__ , lowerCamelCase__ , token_type_ids=lowerCamelCase__ )
__lowercase = model(lowerCamelCase__ , lowerCamelCase__ )
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 snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]:
"""simple docstring"""
__lowercase = TFLayoutLMForMaskedLM(config=lowerCamelCase__ )
__lowercase = model(lowerCamelCase__ , lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ , labels=lowerCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]:
"""simple docstring"""
__lowercase = self.num_labels
__lowercase = TFLayoutLMForSequenceClassification(config=lowerCamelCase__ )
__lowercase = model(lowerCamelCase__ , lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Tuple:
"""simple docstring"""
__lowercase = self.num_labels
__lowercase = TFLayoutLMForTokenClassification(config=lowerCamelCase__ )
__lowercase = model(lowerCamelCase__ , lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ , labels=lowerCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Tuple:
"""simple docstring"""
__lowercase = TFLayoutLMForQuestionAnswering(config=lowerCamelCase__ )
__lowercase = model(lowerCamelCase__ , lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ )
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 snake_case__ ( self ) -> Optional[int]:
"""simple docstring"""
__lowercase = self.prepare_config_and_inputs()
(
(
__lowercase
) ,(
__lowercase
) ,(
__lowercase
) ,(
__lowercase
) ,(
__lowercase
) ,(
__lowercase
) ,(
__lowercase
) ,(
__lowercase
) ,
) = config_and_inputs
__lowercase = {
"""input_ids""": input_ids,
"""bbox""": bbox,
"""token_type_ids""": token_type_ids,
"""attention_mask""": input_mask,
}
return config, inputs_dict
@require_tf
class SCREAMING_SNAKE_CASE( __A , __A , unittest.TestCase ):
snake_case_ : Union[str, Any] = (
(
TFLayoutLMModel,
TFLayoutLMForMaskedLM,
TFLayoutLMForTokenClassification,
TFLayoutLMForSequenceClassification,
TFLayoutLMForQuestionAnswering,
)
if is_tf_available()
else ()
)
snake_case_ : Tuple = (
{
"""feature-extraction""": TFLayoutLMModel,
"""fill-mask""": TFLayoutLMForMaskedLM,
"""text-classification""": TFLayoutLMForSequenceClassification,
"""token-classification""": TFLayoutLMForTokenClassification,
"""zero-shot""": TFLayoutLMForSequenceClassification,
}
if is_tf_available()
else {}
)
snake_case_ : Optional[int] = False
snake_case_ : Optional[int] = True
snake_case_ : Tuple = 10
def snake_case__ ( self ) -> Optional[int]:
"""simple docstring"""
__lowercase = TFLayoutLMModelTester(self )
__lowercase = ConfigTester(self , config_class=lowerCamelCase__ , hidden_size=37 )
def snake_case__ ( self ) -> List[Any]:
"""simple docstring"""
self.config_tester.run_common_tests()
def snake_case__ ( self ) -> Optional[int]:
"""simple docstring"""
__lowercase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCamelCase__ )
def snake_case__ ( self ) -> Tuple:
"""simple docstring"""
__lowercase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase__ )
def snake_case__ ( self ) -> Any:
"""simple docstring"""
__lowercase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase__ )
def snake_case__ ( self ) -> Union[str, Any]:
"""simple docstring"""
__lowercase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*lowerCamelCase__ )
def snake_case__ ( self ) -> Tuple:
"""simple docstring"""
__lowercase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*lowerCamelCase__ )
@slow
def snake_case__ ( self ) -> Dict:
"""simple docstring"""
for model_name in TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__lowercase = TFLayoutLMModel.from_pretrained(lowerCamelCase__ )
self.assertIsNotNone(lowerCamelCase__ )
@unittest.skip("""Onnx compliancy broke with TF 2.10""" )
def snake_case__ ( self ) -> str:
"""simple docstring"""
pass
def snake_case_ ( ):
"""simple docstring"""
__lowercase = tf.convert_to_tensor([[1_01,10_19,10_14,10_16,10_37,1_28_49,47_47,10_04,1_42_46,22_78,54_39,45_24,50_02,29_30,21_93,29_30,43_41,32_08,10_05,10_55,21_71,28_48,1_13_00,35_31,1_02],[1_01,40_70,40_34,70_20,10_24,30_58,10_15,10_13,28_61,10_13,60_70,1_92_74,27_72,62_05,2_78_14,1_61_47,1_61_47,43_43,20_47,1_02_83,1_09_69,1_43_89,10_12,23_38,1_02]] ) # noqa: E231
__lowercase = tf.convert_to_tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],[1, 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: E231
__lowercase = tf.convert_to_tensor([[[0,0,0,0],[4_23,2_37,4_40,2_51],[4_27,2_72,4_41,2_87],[4_19,1_15,4_37,1_29],[9_61,8_85,9_92,9_12],[2_56,38,3_30,58],[2_56,38,3_30,58],[3_36,42,3_53,57],[3_60,39,4_01,56],[3_60,39,4_01,56],[4_11,39,4_71,59],[4_79,41,5_28,59],[5_33,39,6_30,60],[67,1_13,1_34,1_31],[1_41,1_15,2_09,1_32],[68,1_49,1_33,1_66],[1_41,1_49,1_87,1_64],[1_95,1_48,2_87,1_65],[1_95,1_48,2_87,1_65],[1_95,1_48,2_87,1_65],[2_95,1_48,3_49,1_65],[4_41,1_49,4_92,1_66],[4_97,1_49,5_46,1_64],[64,2_01,1_25,2_18],[10_00,10_00,10_00,10_00]],[[0,0,0,0],[6_62,1_50,7_54,1_66],[6_65,1_99,7_42,2_11],[5_19,2_13,5_54,2_28],[5_19,2_13,5_54,2_28],[1_34,4_33,1_87,4_54],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[3_14,4_69,3_76,4_82],[5_04,6_84,5_82,7_06],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[6_10,7_49,6_52,7_65],[1_30,6_59,1_68,6_72],[1_76,6_57,2_37,6_72],[2_38,6_57,3_12,6_72],[4_43,6_53,6_28,6_72],[4_43,6_53,6_28,6_72],[7_16,3_01,8_25,3_17],[10_00,10_00,10_00,10_00]]] ) # noqa: E231
__lowercase = tf.convert_to_tensor([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]] ) # noqa: E231
# these are sequence labels (i.e. at the token level)
__lowercase = tf.convert_to_tensor([[-1_00,10,10,10,9,1,-1_00,7,7,-1_00,7,7,4,2,5,2,8,8,-1_00,-1_00,5,0,3,2,-1_00],[-1_00,12,12,12,-1_00,12,10,-1_00,-1_00,-1_00,-1_00,10,12,9,-1_00,-1_00,-1_00,10,10,10,9,12,-1_00,10,-1_00]] ) # noqa: E231
# fmt: on
return input_ids, attention_mask, bbox, token_type_ids, labels
@require_tf
class SCREAMING_SNAKE_CASE( unittest.TestCase ):
@slow
def snake_case__ ( self ) -> Optional[Any]:
"""simple docstring"""
__lowercase = TFLayoutLMModel.from_pretrained("""microsoft/layoutlm-base-uncased""" )
__lowercase ,__lowercase ,__lowercase ,__lowercase ,__lowercase = prepare_layoutlm_batch_inputs()
# forward pass
__lowercase = model(input_ids=lowerCamelCase__ , bbox=lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ )
# test the sequence output on [0, :3, :3]
__lowercase = tf.convert_to_tensor(
[[0.17_85, -0.19_47, -0.04_25], [-0.32_54, -0.28_07, 0.25_53], [-0.53_91, -0.33_22, 0.33_64]] , )
self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , lowerCamelCase__ , atol=1E-3 ) )
# test the pooled output on [1, :3]
__lowercase = tf.convert_to_tensor([-0.65_80, -0.02_14, 0.85_52] )
self.assertTrue(np.allclose(outputs.pooler_output[1, :3] , lowerCamelCase__ , atol=1E-3 ) )
@slow
def snake_case__ ( self ) -> Union[str, Any]:
"""simple docstring"""
__lowercase = TFLayoutLMForSequenceClassification.from_pretrained("""microsoft/layoutlm-base-uncased""" , num_labels=2 )
__lowercase ,__lowercase ,__lowercase ,__lowercase ,__lowercase = prepare_layoutlm_batch_inputs()
# forward pass
__lowercase = model(
input_ids=lowerCamelCase__ , bbox=lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ , labels=tf.convert_to_tensor([1, 1] ) , )
# test whether we get a loss as a scalar
__lowercase = outputs.loss
__lowercase = (2,)
self.assertEqual(loss.shape , lowerCamelCase__ )
# test the shape of the logits
__lowercase = outputs.logits
__lowercase = (2, 2)
self.assertEqual(logits.shape , lowerCamelCase__ )
@slow
def snake_case__ ( self ) -> Optional[Any]:
"""simple docstring"""
__lowercase = TFLayoutLMForTokenClassification.from_pretrained("""microsoft/layoutlm-base-uncased""" , num_labels=13 )
__lowercase ,__lowercase ,__lowercase ,__lowercase ,__lowercase = prepare_layoutlm_batch_inputs()
# forward pass
__lowercase = model(
input_ids=lowerCamelCase__ , bbox=lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ , labels=lowerCamelCase__ )
# test the shape of the logits
__lowercase = outputs.logits
__lowercase = tf.convert_to_tensor((2, 25, 13) )
self.assertEqual(logits.shape , lowerCamelCase__ )
@slow
def snake_case__ ( self ) -> str:
"""simple docstring"""
__lowercase = TFLayoutLMForQuestionAnswering.from_pretrained("""microsoft/layoutlm-base-uncased""" )
__lowercase ,__lowercase ,__lowercase ,__lowercase ,__lowercase = prepare_layoutlm_batch_inputs()
# forward pass
__lowercase = model(input_ids=lowerCamelCase__ , bbox=lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ )
# test the shape of the logits
__lowercase = tf.convert_to_tensor((2, 25) )
self.assertEqual(outputs.start_logits.shape , lowerCamelCase__ )
self.assertEqual(outputs.end_logits.shape , lowerCamelCase__ )
| 163 | 1 |
"""simple docstring"""
import json
import pathlib
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import DetrImageProcessor
class a ( unittest.TestCase ):
def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Dict=7 , __SCREAMING_SNAKE_CASE : Any=3 , __SCREAMING_SNAKE_CASE : Dict=30 , __SCREAMING_SNAKE_CASE : Optional[Any]=400 , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : str=None , __SCREAMING_SNAKE_CASE : Union[str, Any]=True , __SCREAMING_SNAKE_CASE : Optional[int]=1 / 255 , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : Optional[int]=[0.5, 0.5, 0.5] , __SCREAMING_SNAKE_CASE : Union[str, Any]=[0.5, 0.5, 0.5] , __SCREAMING_SNAKE_CASE : List[Any]=True , ) -> str:
# by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
lowerCamelCase_ = size if size is not None else {"""shortest_edge""": 18, """longest_edge""": 1333}
lowerCamelCase_ = parent
lowerCamelCase_ = batch_size
lowerCamelCase_ = num_channels
lowerCamelCase_ = min_resolution
lowerCamelCase_ = max_resolution
lowerCamelCase_ = do_resize
lowerCamelCase_ = size
lowerCamelCase_ = do_rescale
lowerCamelCase_ = rescale_factor
lowerCamelCase_ = do_normalize
lowerCamelCase_ = image_mean
lowerCamelCase_ = image_std
lowerCamelCase_ = do_pad
def UpperCamelCase ( self : Any ) -> Optional[int]:
return {
"do_resize": self.do_resize,
"size": self.size,
"do_rescale": self.do_rescale,
"rescale_factor": self.rescale_factor,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_pad": self.do_pad,
}
def UpperCamelCase ( self : str , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Optional[Any]:
if not batched:
lowerCamelCase_ = image_inputs[0]
if isinstance(__SCREAMING_SNAKE_CASE , Image.Image ):
lowerCamelCase_ = image.size
else:
lowerCamelCase_ = image.shape[1], image.shape[2]
if w < h:
lowerCamelCase_ = int(self.size['shortest_edge'] * h / w )
lowerCamelCase_ = self.size["""shortest_edge"""]
elif w > h:
lowerCamelCase_ = self.size["""shortest_edge"""]
lowerCamelCase_ = int(self.size['shortest_edge'] * w / h )
else:
lowerCamelCase_ = self.size["""shortest_edge"""]
lowerCamelCase_ = self.size["""shortest_edge"""]
else:
lowerCamelCase_ = []
for image in image_inputs:
lowerCamelCase_ = self.get_expected_values([image] )
expected_values.append((expected_height, expected_width) )
lowerCamelCase_ = max(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : item[0] )[0]
lowerCamelCase_ = max(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : item[1] )[1]
return expected_height, expected_width
@require_torch
@require_vision
class a ( __SCREAMING_SNAKE_CASE , unittest.TestCase ):
SCREAMING_SNAKE_CASE : Union[str, Any] = DetrImageProcessor if is_vision_available() else None
def UpperCamelCase ( self : Tuple ) -> Any:
lowerCamelCase_ = DetrImageProcessingTester(self )
@property
def UpperCamelCase ( self : str ) -> str:
return self.image_processor_tester.prepare_image_processor_dict()
def UpperCamelCase ( self : Dict ) -> Optional[int]:
lowerCamelCase_ = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , 'image_mean' ) )
self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , 'image_std' ) )
self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , 'do_normalize' ) )
self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , 'do_rescale' ) )
self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , 'rescale_factor' ) )
self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , 'do_resize' ) )
self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , 'size' ) )
self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , 'do_pad' ) )
def UpperCamelCase ( self : str ) -> List[str]:
lowerCamelCase_ = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 1333} )
self.assertEqual(image_processor.do_pad , __SCREAMING_SNAKE_CASE )
lowerCamelCase_ = self.image_processing_class.from_dict(
self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=__SCREAMING_SNAKE_CASE )
self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} )
self.assertEqual(image_processor.do_pad , __SCREAMING_SNAKE_CASE )
def UpperCamelCase ( self : Optional[Any] ) -> str:
pass
def UpperCamelCase ( self : int ) -> Tuple:
# Initialize image_processing
lowerCamelCase_ = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
lowerCamelCase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE )
for image in image_inputs:
self.assertIsInstance(__SCREAMING_SNAKE_CASE , Image.Image )
# Test not batched input
lowerCamelCase_ = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
lowerCamelCase_ = self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
lowerCamelCase_ = self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE , batched=__SCREAMING_SNAKE_CASE )
lowerCamelCase_ = image_processing(__SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def UpperCamelCase ( self : List[str] ) -> int:
# Initialize image_processing
lowerCamelCase_ = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
lowerCamelCase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE , numpify=__SCREAMING_SNAKE_CASE )
for image in image_inputs:
self.assertIsInstance(__SCREAMING_SNAKE_CASE , np.ndarray )
# Test not batched input
lowerCamelCase_ = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
lowerCamelCase_ = self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
lowerCamelCase_ = image_processing(__SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values
lowerCamelCase_ = self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE , batched=__SCREAMING_SNAKE_CASE )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def UpperCamelCase ( self : Optional[Any] ) -> Optional[Any]:
# Initialize image_processing
lowerCamelCase_ = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
lowerCamelCase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE , torchify=__SCREAMING_SNAKE_CASE )
for image in image_inputs:
self.assertIsInstance(__SCREAMING_SNAKE_CASE , torch.Tensor )
# Test not batched input
lowerCamelCase_ = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
lowerCamelCase_ = self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
lowerCamelCase_ = image_processing(__SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values
lowerCamelCase_ = self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE , batched=__SCREAMING_SNAKE_CASE )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
@slow
def UpperCamelCase ( self : Optional[int] ) -> List[str]:
# prepare image and target
lowerCamelCase_ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f:
lowerCamelCase_ = json.loads(f.read() )
lowerCamelCase_ = {"""image_id""": 39769, """annotations""": target}
# encode them
lowerCamelCase_ = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50' )
lowerCamelCase_ = image_processing(images=__SCREAMING_SNAKE_CASE , annotations=__SCREAMING_SNAKE_CASE , return_tensors='pt' )
# verify pixel values
lowerCamelCase_ = torch.Size([1, 3, 800, 1066] )
self.assertEqual(encoding['pixel_values'].shape , __SCREAMING_SNAKE_CASE )
lowerCamelCase_ = torch.tensor([0.2_796, 0.3_138, 0.3_481] )
self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
# verify area
lowerCamelCase_ = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] )
self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , __SCREAMING_SNAKE_CASE ) )
# verify boxes
lowerCamelCase_ = torch.Size([6, 4] )
self.assertEqual(encoding['labels'][0]['boxes'].shape , __SCREAMING_SNAKE_CASE )
lowerCamelCase_ = torch.tensor([0.5_503, 0.2_765, 0.0_604, 0.2_215] )
self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , __SCREAMING_SNAKE_CASE , atol=1e-3 ) )
# verify image_id
lowerCamelCase_ = torch.tensor([39769] )
self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , __SCREAMING_SNAKE_CASE ) )
# verify is_crowd
lowerCamelCase_ = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , __SCREAMING_SNAKE_CASE ) )
# verify class_labels
lowerCamelCase_ = torch.tensor([75, 75, 63, 65, 17, 17] )
self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , __SCREAMING_SNAKE_CASE ) )
# verify orig_size
lowerCamelCase_ = torch.tensor([480, 640] )
self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , __SCREAMING_SNAKE_CASE ) )
# verify size
lowerCamelCase_ = torch.tensor([800, 1066] )
self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , __SCREAMING_SNAKE_CASE ) )
@slow
def UpperCamelCase ( self : Tuple ) -> str:
# prepare image, target and masks_path
lowerCamelCase_ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f:
lowerCamelCase_ = json.loads(f.read() )
lowerCamelCase_ = {"""file_name""": """000000039769.png""", """image_id""": 39769, """segments_info""": target}
lowerCamelCase_ = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' )
# encode them
lowerCamelCase_ = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50-panoptic' )
lowerCamelCase_ = image_processing(images=__SCREAMING_SNAKE_CASE , annotations=__SCREAMING_SNAKE_CASE , masks_path=__SCREAMING_SNAKE_CASE , return_tensors='pt' )
# verify pixel values
lowerCamelCase_ = torch.Size([1, 3, 800, 1066] )
self.assertEqual(encoding['pixel_values'].shape , __SCREAMING_SNAKE_CASE )
lowerCamelCase_ = torch.tensor([0.2_796, 0.3_138, 0.3_481] )
self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
# verify area
lowerCamelCase_ = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] )
self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , __SCREAMING_SNAKE_CASE ) )
# verify boxes
lowerCamelCase_ = torch.Size([6, 4] )
self.assertEqual(encoding['labels'][0]['boxes'].shape , __SCREAMING_SNAKE_CASE )
lowerCamelCase_ = torch.tensor([0.2_625, 0.5_437, 0.4_688, 0.8_625] )
self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , __SCREAMING_SNAKE_CASE , atol=1e-3 ) )
# verify image_id
lowerCamelCase_ = torch.tensor([39769] )
self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , __SCREAMING_SNAKE_CASE ) )
# verify is_crowd
lowerCamelCase_ = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , __SCREAMING_SNAKE_CASE ) )
# verify class_labels
lowerCamelCase_ = torch.tensor([17, 17, 63, 75, 75, 93] )
self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , __SCREAMING_SNAKE_CASE ) )
# verify masks
lowerCamelCase_ = 822873
self.assertEqual(encoding['labels'][0]['masks'].sum().item() , __SCREAMING_SNAKE_CASE )
# verify orig_size
lowerCamelCase_ = torch.tensor([480, 640] )
self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , __SCREAMING_SNAKE_CASE ) )
# verify size
lowerCamelCase_ = torch.tensor([800, 1066] )
self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , __SCREAMING_SNAKE_CASE ) )
| 549 |
import PIL.Image
import PIL.ImageOps
from packaging import version
from PIL import Image
if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("""9.1.0"""):
_lowerCamelCase ={
"""linear""": PIL.Image.Resampling.BILINEAR,
"""bilinear""": PIL.Image.Resampling.BILINEAR,
"""bicubic""": PIL.Image.Resampling.BICUBIC,
"""lanczos""": PIL.Image.Resampling.LANCZOS,
"""nearest""": PIL.Image.Resampling.NEAREST,
}
else:
_lowerCamelCase ={
"""linear""": PIL.Image.LINEAR,
"""bilinear""": PIL.Image.BILINEAR,
"""bicubic""": PIL.Image.BICUBIC,
"""lanczos""": PIL.Image.LANCZOS,
"""nearest""": PIL.Image.NEAREST,
}
def _a ( lowerCamelCase ):
lowerCamelCase : Optional[Any] = (images / 2 + 0.5).clamp(0, 1 )
lowerCamelCase : Optional[Any] = images.cpu().permute(0, 2, 3, 1 ).float().numpy()
lowerCamelCase : Any = numpy_to_pil(lowerCamelCase )
return images
def _a ( lowerCamelCase ):
if images.ndim == 3:
lowerCamelCase : Optional[Any] = images[None, ...]
lowerCamelCase : List[Any] = (images * 255).round().astype("""uint8""" )
if images.shape[-1] == 1:
# special case for grayscale (single channel) images
lowerCamelCase : Optional[int] = [Image.fromarray(image.squeeze(), mode="""L""" ) for image in images]
else:
lowerCamelCase : int = [Image.fromarray(lowerCamelCase ) for image in images]
return pil_images
| 681 | 0 |
'''simple docstring'''
import os
import unittest
from tempfile import TemporaryDirectory
import torch
import torch.nn as nn
from accelerate.utils import (
OffloadedWeightsLoader,
extract_submodules_state_dict,
load_offloaded_weight,
offload_state_dict,
offload_weight,
)
class lowerCAmelCase__ ( nn.Module ):
'''simple docstring'''
def __init__( self : str ):
super().__init__()
UpperCAmelCase = nn.Linear(3 , 4 )
UpperCAmelCase = nn.BatchNormad(4 )
UpperCAmelCase = nn.Linear(4 , 5 )
def __snake_case ( self : Dict , a__ : int ):
return self.lineara(self.batchnorm(self.lineara(a_ ) ) )
class lowerCAmelCase__ ( unittest.TestCase ):
'''simple docstring'''
def __snake_case ( self : List[Any] ):
UpperCAmelCase = ModelForTest()
with TemporaryDirectory() as tmp_dir:
offload_state_dict(a_ , model.state_dict() )
UpperCAmelCase = os.path.join(a_ , '''index.json''' )
self.assertTrue(os.path.isfile(a_ ) )
# TODO: add tests on what is inside the index
for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]:
UpperCAmelCase = os.path.join(a_ , f"{key}.dat" )
self.assertTrue(os.path.isfile(a_ ) )
# TODO: add tests on the fact weights are properly loaded
def __snake_case ( self : Tuple ):
UpperCAmelCase = [torch.floataa, torch.floataa, torch.bfloataa]
for dtype in dtypes:
UpperCAmelCase = torch.randn(2 , 3 , dtype=a_ )
with TemporaryDirectory() as tmp_dir:
UpperCAmelCase = offload_weight(a_ , '''weight''' , a_ , {} )
UpperCAmelCase = os.path.join(a_ , '''weight.dat''' )
self.assertTrue(os.path.isfile(a_ ) )
self.assertDictEqual(a_ , {'''weight''': {'''shape''': [2, 3], '''dtype''': str(a_ ).split('''.''' )[1]}} )
UpperCAmelCase = load_offloaded_weight(a_ , index['''weight'''] )
self.assertTrue(torch.equal(a_ , a_ ) )
def __snake_case ( self : Optional[int] ):
UpperCAmelCase = ModelForTest()
UpperCAmelCase = model.state_dict()
UpperCAmelCase = {k: v for k, v in state_dict.items() if """linear2""" not in k}
UpperCAmelCase = {k: v for k, v in state_dict.items() if """linear2""" in k}
with TemporaryDirectory() as tmp_dir:
offload_state_dict(a_ , a_ )
UpperCAmelCase = OffloadedWeightsLoader(state_dict=a_ , save_folder=a_ )
# Every key is there with the right value
self.assertEqual(sorted(a_ ) , sorted(state_dict.keys() ) )
for key, param in state_dict.items():
self.assertTrue(torch.allclose(a_ , weight_map[key] ) )
UpperCAmelCase = {k: v for k, v in state_dict.items() if """weight""" in k}
UpperCAmelCase = {k: v for k, v in state_dict.items() if """weight""" not in k}
with TemporaryDirectory() as tmp_dir:
offload_state_dict(a_ , a_ )
UpperCAmelCase = OffloadedWeightsLoader(state_dict=a_ , save_folder=a_ )
# Every key is there with the right value
self.assertEqual(sorted(a_ ) , sorted(state_dict.keys() ) )
for key, param in state_dict.items():
self.assertTrue(torch.allclose(a_ , weight_map[key] ) )
with TemporaryDirectory() as tmp_dir:
offload_state_dict(a_ , a_ )
# Duplicates are removed
UpperCAmelCase = OffloadedWeightsLoader(state_dict=a_ , save_folder=a_ )
# Every key is there with the right value
self.assertEqual(sorted(a_ ) , sorted(state_dict.keys() ) )
for key, param in state_dict.items():
self.assertTrue(torch.allclose(a_ , weight_map[key] ) )
def __snake_case ( self : Optional[Any] ):
UpperCAmelCase = {"""a.1""": 0, """a.10""": 1, """a.2""": 2}
UpperCAmelCase = extract_submodules_state_dict(a_ , ['''a.1''', '''a.2'''] )
self.assertDictEqual(a_ , {'''a.1''': 0, '''a.2''': 2} )
UpperCAmelCase = {"""a.1.a""": 0, """a.10.a""": 1, """a.2.a""": 2}
UpperCAmelCase = extract_submodules_state_dict(a_ , ['''a.1''', '''a.2'''] )
self.assertDictEqual(a_ , {'''a.1.a''': 0, '''a.2.a''': 2} )
| 706 |
'''simple docstring'''
import importlib.metadata
from typing import Union
from packaging.version import Version, parse
from .constants import STR_OPERATION_TO_FUNC
a__ : Any = parse(importlib.metadata.version('torch'))
def __snake_case ( SCREAMING_SNAKE_CASE_ : Union[str, Version] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ) -> List[Any]:
"""simple docstring"""
if operation not in STR_OPERATION_TO_FUNC.keys():
raise ValueError(f"`operation` must be one of {list(STR_OPERATION_TO_FUNC.keys() )}, received {operation}" )
UpperCAmelCase = STR_OPERATION_TO_FUNC[operation]
if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
UpperCAmelCase = parse(importlib.metadata.version(SCREAMING_SNAKE_CASE_ ) )
return operation(SCREAMING_SNAKE_CASE_ , parse(SCREAMING_SNAKE_CASE_ ) )
def __snake_case ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ) -> str:
"""simple docstring"""
return compare_versions(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
| 570 | 0 |
from typing import Dict, Optional
import numpy as np
import datasets
_lowerCamelCase : Optional[int] = '''
IoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union
between the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,
the mean IoU of the image is calculated by taking the IoU of each class and averaging them.
'''
_lowerCamelCase : Optional[Any] = '''
Args:
predictions (`List[ndarray]`):
List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.
references (`List[ndarray]`):
List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.
num_labels (`int`):
Number of classes (categories).
ignore_index (`int`):
Index that will be ignored during evaluation.
nan_to_num (`int`, *optional*):
If specified, NaN values will be replaced by the number defined by the user.
label_map (`dict`, *optional*):
If specified, dictionary mapping old label indices to new label indices.
reduce_labels (`bool`, *optional*, defaults to `False`):
Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,
and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.
Returns:
`Dict[str, float | ndarray]` comprising various elements:
- *mean_iou* (`float`):
Mean Intersection-over-Union (IoU averaged over all categories).
- *mean_accuracy* (`float`):
Mean accuracy (averaged over all categories).
- *overall_accuracy* (`float`):
Overall accuracy on all images.
- *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):
Per category accuracy.
- *per_category_iou* (`ndarray` of shape `(num_labels,)`):
Per category IoU.
Examples:
>>> import numpy as np
>>> mean_iou = datasets.load_metric("mean_iou")
>>> # suppose one has 3 different segmentation maps predicted
>>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])
>>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])
>>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])
>>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])
>>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])
>>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])
>>> predicted = [predicted_1, predicted_2, predicted_3]
>>> ground_truth = [actual_1, actual_2, actual_3]
>>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)
>>> print(results) # doctest: +NORMALIZE_WHITESPACE
{\'mean_iou\': 0.47750000000000004, \'mean_accuracy\': 0.5916666666666666, \'overall_accuracy\': 0.5263157894736842, \'per_category_iou\': array([0. , 0. , 0.375, 0.4 , 0.5 , 0. , 0.5 , 1. , 1. , 1. ]), \'per_category_accuracy\': array([0. , 0. , 0.75 , 0.66666667, 1. , 0. , 0.5 , 1. , 1. , 1. ])}
'''
_lowerCamelCase : Optional[int] = '''\
@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,
author = {{MMSegmentation Contributors}},
license = {Apache-2.0},
month = {7},
title = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},
url = {https://github.com/open-mmlab/mmsegmentation},
year = {2020}
}'''
def _a ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : bool , SCREAMING_SNAKE_CASE__ : Optional[Dict[int, int]] = None , SCREAMING_SNAKE_CASE__ : bool = False , ) -> Tuple:
'''simple docstring'''
if label_map is not None:
for old_id, new_id in label_map.items():
SCREAMING_SNAKE_CASE__ : List[Any] = new_id
# turn into Numpy arrays
SCREAMING_SNAKE_CASE__ : Dict = np.array(SCREAMING_SNAKE_CASE__ )
SCREAMING_SNAKE_CASE__ : Dict = np.array(SCREAMING_SNAKE_CASE__ )
if reduce_labels:
SCREAMING_SNAKE_CASE__ : Optional[int] = 2_55
SCREAMING_SNAKE_CASE__ : Union[str, Any] = label - 1
SCREAMING_SNAKE_CASE__ : str = 2_55
SCREAMING_SNAKE_CASE__ : Union[str, Any] = label != ignore_index
SCREAMING_SNAKE_CASE__ : Any = np.not_equal(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = pred_label[mask]
SCREAMING_SNAKE_CASE__ : Dict = np.array(SCREAMING_SNAKE_CASE__ )[mask]
SCREAMING_SNAKE_CASE__ : List[Any] = pred_label[pred_label == label]
SCREAMING_SNAKE_CASE__ : Tuple = np.histogram(SCREAMING_SNAKE_CASE__ , bins=SCREAMING_SNAKE_CASE__ , range=(0, num_labels - 1) )[0]
SCREAMING_SNAKE_CASE__ : Optional[Any] = np.histogram(SCREAMING_SNAKE_CASE__ , bins=SCREAMING_SNAKE_CASE__ , range=(0, num_labels - 1) )[0]
SCREAMING_SNAKE_CASE__ : Any = np.histogram(SCREAMING_SNAKE_CASE__ , bins=SCREAMING_SNAKE_CASE__ , range=(0, num_labels - 1) )[0]
SCREAMING_SNAKE_CASE__ : int = area_pred_label + area_label - area_intersect
return area_intersect, area_union, area_pred_label, area_label
def _a ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : bool , SCREAMING_SNAKE_CASE__ : Optional[Dict[int, int]] = None , SCREAMING_SNAKE_CASE__ : bool = False , ) -> Optional[int]:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Optional[int] = np.zeros((num_labels,) , dtype=np.floataa )
SCREAMING_SNAKE_CASE__ : int = np.zeros((num_labels,) , dtype=np.floataa )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.zeros((num_labels,) , dtype=np.floataa )
SCREAMING_SNAKE_CASE__ : Tuple = np.zeros((num_labels,) , dtype=np.floataa )
for result, gt_seg_map in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[Any] = intersect_and_union(
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
total_area_intersect += area_intersect
total_area_union += area_union
total_area_pred_label += area_pred_label
total_area_label += area_label
return total_area_intersect, total_area_union, total_area_pred_label, total_area_label
def _a ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : bool , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[Dict[int, int]] = None , SCREAMING_SNAKE_CASE__ : bool = False , ) -> Any:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Tuple = total_intersect_and_union(
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
# compute metrics
SCREAMING_SNAKE_CASE__ : Union[str, Any] = {}
SCREAMING_SNAKE_CASE__ : Dict = total_area_intersect.sum() / total_area_label.sum()
SCREAMING_SNAKE_CASE__ : int = total_area_intersect / total_area_union
SCREAMING_SNAKE_CASE__ : Tuple = total_area_intersect / total_area_label
SCREAMING_SNAKE_CASE__ : Optional[Any] = np.nanmean(SCREAMING_SNAKE_CASE__ )
SCREAMING_SNAKE_CASE__ : Tuple = np.nanmean(SCREAMING_SNAKE_CASE__ )
SCREAMING_SNAKE_CASE__ : int = all_acc
SCREAMING_SNAKE_CASE__ : Any = iou
SCREAMING_SNAKE_CASE__ : str = acc
if nan_to_num is not None:
SCREAMING_SNAKE_CASE__ : Optional[int] = {metric: np.nan_to_num(SCREAMING_SNAKE_CASE__ , nan=SCREAMING_SNAKE_CASE__ ) for metric, metric_value in metrics.items()}
return metrics
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class lowerCamelCase (datasets.Metric ):
"""simple docstring"""
def A_ ( self : Any ) -> Tuple:
"""simple docstring"""
return datasets.MetricInfo(
description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features(
# 1st Seq - height dim, 2nd - width dim
{
"predictions": datasets.Sequence(datasets.Sequence(datasets.Value("uint16" ) ) ),
"references": datasets.Sequence(datasets.Sequence(datasets.Value("uint16" ) ) ),
} ), reference_urls=[
"https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py"
], )
def A_ ( self : Optional[Any], _UpperCAmelCase : Optional[int], _UpperCAmelCase : Dict, _UpperCAmelCase : int, _UpperCAmelCase : bool, _UpperCAmelCase : Optional[int] = None, _UpperCAmelCase : Optional[Dict[int, int]] = None, _UpperCAmelCase : bool = False, ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Union[str, Any] = mean_iou(
results=_UpperCAmelCase, gt_seg_maps=_UpperCAmelCase, num_labels=_UpperCAmelCase, ignore_index=_UpperCAmelCase, nan_to_num=_UpperCAmelCase, label_map=_UpperCAmelCase, reduce_labels=_UpperCAmelCase, )
return iou_result
| 663 |
import argparse
import gc
import json
import os
import shutil
import warnings
import torch
from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer
try:
from transformers import LlamaTokenizerFast
except ImportError as e:
warnings.warn(e)
warnings.warn(
'''The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion'''
)
_lowerCamelCase : List[str] = None
_lowerCamelCase : Union[str, Any] = {
'''7B''': 1_1_0_0_8,
'''13B''': 1_3_8_2_4,
'''30B''': 1_7_9_2_0,
'''65B''': 2_2_0_1_6,
'''70B''': 2_8_6_7_2,
}
_lowerCamelCase : Optional[Any] = {
'''7B''': 1,
'''7Bf''': 1,
'''13B''': 2,
'''13Bf''': 2,
'''30B''': 4,
'''65B''': 8,
'''70B''': 8,
'''70Bf''': 8,
}
def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=1 , SCREAMING_SNAKE_CASE__ : str=2_56 ) -> int:
'''simple docstring'''
return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of)
def _a ( SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[int]:
'''simple docstring'''
with open(SCREAMING_SNAKE_CASE__ , "r" ) as f:
return json.load(SCREAMING_SNAKE_CASE__ )
def _a ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str] ) -> str:
'''simple docstring'''
with open(SCREAMING_SNAKE_CASE__ , "w" ) as f:
json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
def _a ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str=True ) -> int:
'''simple docstring'''
os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ )
SCREAMING_SNAKE_CASE__ : Dict = os.path.join(SCREAMING_SNAKE_CASE__ , "tmp" )
os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ )
SCREAMING_SNAKE_CASE__ : Any = read_json(os.path.join(SCREAMING_SNAKE_CASE__ , "params.json" ) )
SCREAMING_SNAKE_CASE__ : int = NUM_SHARDS[model_size]
SCREAMING_SNAKE_CASE__ : Union[str, Any] = params["n_layers"]
SCREAMING_SNAKE_CASE__ : List[str] = params["n_heads"]
SCREAMING_SNAKE_CASE__ : Optional[Any] = n_heads // num_shards
SCREAMING_SNAKE_CASE__ : str = params["dim"]
SCREAMING_SNAKE_CASE__ : List[str] = dim // n_heads
SCREAMING_SNAKE_CASE__ : Optional[Any] = 1_0_0_0_0.0
SCREAMING_SNAKE_CASE__ : Tuple = 1.0 / (base ** (torch.arange(0 , SCREAMING_SNAKE_CASE__ , 2 ).float() / dims_per_head))
if "n_kv_heads" in params:
SCREAMING_SNAKE_CASE__ : int = params["n_kv_heads"] # for GQA / MQA
SCREAMING_SNAKE_CASE__ : Optional[int] = n_heads_per_shard // num_key_value_heads
SCREAMING_SNAKE_CASE__ : int = dim // num_key_value_heads
else: # compatibility with other checkpoints
SCREAMING_SNAKE_CASE__ : Dict = n_heads
SCREAMING_SNAKE_CASE__ : str = n_heads_per_shard
SCREAMING_SNAKE_CASE__ : Dict = dim
# permute for sliced rotary
def permute(SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=n_heads , SCREAMING_SNAKE_CASE__ : List[str]=dim , SCREAMING_SNAKE_CASE__ : Dict=dim ):
return w.view(SCREAMING_SNAKE_CASE__ , dima // n_heads // 2 , 2 , SCREAMING_SNAKE_CASE__ ).transpose(1 , 2 ).reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
print(f'''Fetching all parameters from the checkpoint at {input_base_path}.''' )
# Load weights
if model_size == "7B":
# Not sharded
# (The sharded implementation would also work, but this is simpler.)
SCREAMING_SNAKE_CASE__ : Dict = torch.load(os.path.join(SCREAMING_SNAKE_CASE__ , "consolidated.00.pth" ) , map_location="cpu" )
else:
# Sharded
SCREAMING_SNAKE_CASE__ : List[Any] = [
torch.load(os.path.join(SCREAMING_SNAKE_CASE__ , f'''consolidated.{i:02d}.pth''' ) , map_location="cpu" )
for i in range(SCREAMING_SNAKE_CASE__ )
]
SCREAMING_SNAKE_CASE__ : Any = 0
SCREAMING_SNAKE_CASE__ : List[str] = {"weight_map": {}}
for layer_i in range(SCREAMING_SNAKE_CASE__ ):
SCREAMING_SNAKE_CASE__ : int = f'''pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin'''
if model_size == "7B":
# Unsharded
SCREAMING_SNAKE_CASE__ : List[Any] = {
f'''model.layers.{layer_i}.self_attn.q_proj.weight''': permute(
loaded[f'''layers.{layer_i}.attention.wq.weight'''] ),
f'''model.layers.{layer_i}.self_attn.k_proj.weight''': permute(
loaded[f'''layers.{layer_i}.attention.wk.weight'''] ),
f'''model.layers.{layer_i}.self_attn.v_proj.weight''': loaded[f'''layers.{layer_i}.attention.wv.weight'''],
f'''model.layers.{layer_i}.self_attn.o_proj.weight''': loaded[f'''layers.{layer_i}.attention.wo.weight'''],
f'''model.layers.{layer_i}.mlp.gate_proj.weight''': loaded[f'''layers.{layer_i}.feed_forward.w1.weight'''],
f'''model.layers.{layer_i}.mlp.down_proj.weight''': loaded[f'''layers.{layer_i}.feed_forward.w2.weight'''],
f'''model.layers.{layer_i}.mlp.up_proj.weight''': loaded[f'''layers.{layer_i}.feed_forward.w3.weight'''],
f'''model.layers.{layer_i}.input_layernorm.weight''': loaded[f'''layers.{layer_i}.attention_norm.weight'''],
f'''model.layers.{layer_i}.post_attention_layernorm.weight''': loaded[f'''layers.{layer_i}.ffn_norm.weight'''],
}
else:
# Sharded
# Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share
# the same storage object, saving attention_norm and ffn_norm will save other weights too, which is
# redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned.
SCREAMING_SNAKE_CASE__ : Any = {
f'''model.layers.{layer_i}.input_layernorm.weight''': loaded[0][
f'''layers.{layer_i}.attention_norm.weight'''
].clone(),
f'''model.layers.{layer_i}.post_attention_layernorm.weight''': loaded[0][
f'''layers.{layer_i}.ffn_norm.weight'''
].clone(),
}
SCREAMING_SNAKE_CASE__ : int = permute(
torch.cat(
[
loaded[i][f'''layers.{layer_i}.attention.wq.weight'''].view(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
for i in range(SCREAMING_SNAKE_CASE__ )
] , dim=0 , ).reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
SCREAMING_SNAKE_CASE__ : Tuple = permute(
torch.cat(
[
loaded[i][f'''layers.{layer_i}.attention.wk.weight'''].view(
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
for i in range(SCREAMING_SNAKE_CASE__ )
] , dim=0 , ).reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , )
SCREAMING_SNAKE_CASE__ : List[str] = torch.cat(
[
loaded[i][f'''layers.{layer_i}.attention.wv.weight'''].view(
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
for i in range(SCREAMING_SNAKE_CASE__ )
] , dim=0 , ).reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
SCREAMING_SNAKE_CASE__ : int = torch.cat(
[loaded[i][f'''layers.{layer_i}.attention.wo.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=1 )
SCREAMING_SNAKE_CASE__ : List[str] = torch.cat(
[loaded[i][f'''layers.{layer_i}.feed_forward.w1.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=0 )
SCREAMING_SNAKE_CASE__ : Tuple = torch.cat(
[loaded[i][f'''layers.{layer_i}.feed_forward.w2.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=1 )
SCREAMING_SNAKE_CASE__ : int = torch.cat(
[loaded[i][f'''layers.{layer_i}.feed_forward.w3.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=0 )
SCREAMING_SNAKE_CASE__ : List[str] = inv_freq
for k, v in state_dict.items():
SCREAMING_SNAKE_CASE__ : str = filename
param_count += v.numel()
torch.save(SCREAMING_SNAKE_CASE__ , os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
SCREAMING_SNAKE_CASE__ : int = f'''pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin'''
if model_size == "7B":
# Unsharded
SCREAMING_SNAKE_CASE__ : List[str] = {
"model.embed_tokens.weight": loaded["tok_embeddings.weight"],
"model.norm.weight": loaded["norm.weight"],
"lm_head.weight": loaded["output.weight"],
}
else:
SCREAMING_SNAKE_CASE__ : Optional[Any] = {
"model.norm.weight": loaded[0]["norm.weight"],
"model.embed_tokens.weight": torch.cat(
[loaded[i]["tok_embeddings.weight"] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=1 ),
"lm_head.weight": torch.cat([loaded[i]["output.weight"] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=0 ),
}
for k, v in state_dict.items():
SCREAMING_SNAKE_CASE__ : Optional[int] = filename
param_count += v.numel()
torch.save(SCREAMING_SNAKE_CASE__ , os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
# Write configs
SCREAMING_SNAKE_CASE__ : Optional[Any] = {"total_size": param_count * 2}
write_json(SCREAMING_SNAKE_CASE__ , os.path.join(SCREAMING_SNAKE_CASE__ , "pytorch_model.bin.index.json" ) )
SCREAMING_SNAKE_CASE__ : List[str] = params["ffn_dim_multiplier"] if "ffn_dim_multiplier" in params else 1
SCREAMING_SNAKE_CASE__ : Dict = params["multiple_of"] if "multiple_of" in params else 2_56
SCREAMING_SNAKE_CASE__ : Dict = LlamaConfig(
hidden_size=SCREAMING_SNAKE_CASE__ , intermediate_size=compute_intermediate_size(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , num_attention_heads=params["n_heads"] , num_hidden_layers=params["n_layers"] , rms_norm_eps=params["norm_eps"] , num_key_value_heads=SCREAMING_SNAKE_CASE__ , )
config.save_pretrained(SCREAMING_SNAKE_CASE__ )
# Make space so we can load the model properly now.
del state_dict
del loaded
gc.collect()
print("Loading the checkpoint in a Llama model." )
SCREAMING_SNAKE_CASE__ : int = LlamaForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__ , torch_dtype=torch.floataa , low_cpu_mem_usage=SCREAMING_SNAKE_CASE__ )
# Avoid saving this as part of the config.
del model.config._name_or_path
print("Saving in the Transformers format." )
model.save_pretrained(SCREAMING_SNAKE_CASE__ , safe_serialization=SCREAMING_SNAKE_CASE__ )
shutil.rmtree(SCREAMING_SNAKE_CASE__ )
def _a ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Any ) -> int:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Optional[Any] = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast
print(f'''Saving a {tokenizer_class.__name__} to {tokenizer_path}.''' )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer_class(SCREAMING_SNAKE_CASE__ )
tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ )
def _a ( ) -> Any:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : int = argparse.ArgumentParser()
parser.add_argument(
"--input_dir" , help="Location of LLaMA weights, which contains tokenizer.model and model folders" , )
parser.add_argument(
"--model_size" , choices=["7B", "7Bf", "13B", "13Bf", "30B", "65B", "70B", "70Bf", "tokenizer_only"] , )
parser.add_argument(
"--output_dir" , help="Location to write HF model and tokenizer" , )
parser.add_argument("--safe_serialization" , type=SCREAMING_SNAKE_CASE__ , help="Whether or not to save using `safetensors`." )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.parse_args()
if args.model_size != "tokenizer_only":
write_model(
model_path=args.output_dir , input_base_path=os.path.join(args.input_dir , args.model_size ) , model_size=args.model_size , safe_serialization=args.safe_serialization , )
SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(args.input_dir , "tokenizer.model" )
write_tokenizer(args.output_dir , SCREAMING_SNAKE_CASE__ )
if __name__ == "__main__":
main()
| 663 | 1 |
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
convert_to_rgb,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
OPENAI_CLIP_MEAN,
OPENAI_CLIP_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
UpperCamelCase = logging.get_logger(__name__)
if is_vision_available():
import PIL
class lowerCamelCase__ ( UpperCAmelCase ):
lowerCamelCase_ : Tuple = ['pixel_values']
def __init__(self : str , _snake_case : bool = True , _snake_case : Dict[str, int] = None , _snake_case : PILImageResampling = PILImageResampling.BICUBIC , _snake_case : bool = True , _snake_case : Dict[str, int] = None , _snake_case : bool = True , _snake_case : Union[int, float] = 1 / 255 , _snake_case : bool = True , _snake_case : Optional[Union[float, List[float]]] = None , _snake_case : Optional[Union[float, List[float]]] = None , _snake_case : bool = True , **_snake_case : int , ) -> None:
"""simple docstring"""
super().__init__(**_snake_case )
lowerCamelCase_ : Optional[Any] = size if size is not None else {'shortest_edge': 224}
lowerCamelCase_ : str = get_size_dict(_snake_case , default_to_square=_snake_case )
lowerCamelCase_ : Dict = crop_size if crop_size is not None else {'height': 224, 'width': 224}
lowerCamelCase_ : Any = get_size_dict(_snake_case , default_to_square=_snake_case , param_name='crop_size' )
lowerCamelCase_ : List[Any] = do_resize
lowerCamelCase_ : Union[str, Any] = size
lowerCamelCase_ : Optional[Any] = resample
lowerCamelCase_ : Any = do_center_crop
lowerCamelCase_ : str = crop_size
lowerCamelCase_ : Optional[int] = do_rescale
lowerCamelCase_ : Optional[Any] = rescale_factor
lowerCamelCase_ : Dict = do_normalize
lowerCamelCase_ : Optional[Any] = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
lowerCamelCase_ : Union[str, Any] = image_std if image_std is not None else OPENAI_CLIP_STD
lowerCamelCase_ : List[Any] = do_convert_rgb
def UpperCAmelCase_ (self : List[Any] , _snake_case : np.ndarray , _snake_case : Dict[str, int] , _snake_case : PILImageResampling = PILImageResampling.BICUBIC , _snake_case : Optional[Union[str, ChannelDimension]] = None , **_snake_case : List[Any] , ) -> np.ndarray:
"""simple docstring"""
lowerCamelCase_ : List[Any] = get_size_dict(_snake_case , default_to_square=_snake_case )
if "shortest_edge" not in size:
raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' )
lowerCamelCase_ : int = get_resize_output_image_size(_snake_case , size=size['shortest_edge'] , default_to_square=_snake_case )
return resize(_snake_case , size=_snake_case , resample=_snake_case , data_format=_snake_case , **_snake_case )
def UpperCAmelCase_ (self : Union[str, Any] , _snake_case : np.ndarray , _snake_case : Dict[str, int] , _snake_case : Optional[Union[str, ChannelDimension]] = None , **_snake_case : Optional[Any] , ) -> np.ndarray:
"""simple docstring"""
lowerCamelCase_ : Any = get_size_dict(_snake_case )
if "height" not in size or "width" not in size:
raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}' )
return center_crop(_snake_case , size=(size['height'], size['width']) , data_format=_snake_case , **_snake_case )
def UpperCAmelCase_ (self : Union[str, Any] , _snake_case : np.ndarray , _snake_case : Union[int, float] , _snake_case : Optional[Union[str, ChannelDimension]] = None , **_snake_case : Dict , ) -> int:
"""simple docstring"""
return rescale(_snake_case , scale=_snake_case , data_format=_snake_case , **_snake_case )
def UpperCAmelCase_ (self : Optional[int] , _snake_case : np.ndarray , _snake_case : Union[float, List[float]] , _snake_case : Union[float, List[float]] , _snake_case : Optional[Union[str, ChannelDimension]] = None , **_snake_case : Union[str, Any] , ) -> np.ndarray:
"""simple docstring"""
return normalize(_snake_case , mean=_snake_case , std=_snake_case , data_format=_snake_case , **_snake_case )
def UpperCAmelCase_ (self : int , _snake_case : ImageInput , _snake_case : bool = None , _snake_case : Dict[str, int] = None , _snake_case : PILImageResampling = None , _snake_case : bool = None , _snake_case : int = None , _snake_case : bool = None , _snake_case : float = None , _snake_case : bool = None , _snake_case : Optional[Union[float, List[float]]] = None , _snake_case : Optional[Union[float, List[float]]] = None , _snake_case : bool = None , _snake_case : Optional[Union[str, TensorType]] = None , _snake_case : Optional[ChannelDimension] = ChannelDimension.FIRST , **_snake_case : str , ) -> PIL.Image.Image:
"""simple docstring"""
lowerCamelCase_ : str = do_resize if do_resize is not None else self.do_resize
lowerCamelCase_ : List[Any] = size if size is not None else self.size
lowerCamelCase_ : int = get_size_dict(_snake_case , param_name='size' , default_to_square=_snake_case )
lowerCamelCase_ : int = resample if resample is not None else self.resample
lowerCamelCase_ : List[str] = do_center_crop if do_center_crop is not None else self.do_center_crop
lowerCamelCase_ : Optional[Any] = crop_size if crop_size is not None else self.crop_size
lowerCamelCase_ : Any = get_size_dict(_snake_case , param_name='crop_size' , default_to_square=_snake_case )
lowerCamelCase_ : List[Any] = do_rescale if do_rescale is not None else self.do_rescale
lowerCamelCase_ : Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor
lowerCamelCase_ : Any = do_normalize if do_normalize is not None else self.do_normalize
lowerCamelCase_ : List[str] = image_mean if image_mean is not None else self.image_mean
lowerCamelCase_ : Optional[int] = image_std if image_std is not None else self.image_std
lowerCamelCase_ : List[str] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
lowerCamelCase_ : List[Any] = make_list_of_images(_snake_case )
if not valid_images(_snake_case ):
raise ValueError(
'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
'torch.Tensor, tf.Tensor or jax.ndarray.' )
if do_resize and size is None:
raise ValueError('Size must be specified if do_resize is True.' )
if do_center_crop and crop_size is None:
raise ValueError('Crop size must be specified if do_center_crop is True.' )
if do_rescale and rescale_factor is None:
raise ValueError('Rescale factor must be specified if do_rescale is True.' )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError('Image mean and std must be specified if do_normalize is True.' )
# PIL RGBA images are converted to RGB
if do_convert_rgb:
lowerCamelCase_ : List[str] = [convert_to_rgb(_snake_case ) for image in images]
# All transformations expect numpy arrays.
lowerCamelCase_ : Optional[int] = [to_numpy_array(_snake_case ) for image in images]
if do_resize:
lowerCamelCase_ : Optional[Any] = [self.resize(image=_snake_case , size=_snake_case , resample=_snake_case ) for image in images]
if do_center_crop:
lowerCamelCase_ : Optional[Any] = [self.center_crop(image=_snake_case , size=_snake_case ) for image in images]
if do_rescale:
lowerCamelCase_ : Optional[int] = [self.rescale(image=_snake_case , scale=_snake_case ) for image in images]
if do_normalize:
lowerCamelCase_ : Tuple = [self.normalize(image=_snake_case , mean=_snake_case , std=_snake_case ) for image in images]
lowerCamelCase_ : Any = [to_channel_dimension_format(_snake_case , _snake_case ) for image in images]
lowerCamelCase_ : Union[str, Any] = {'pixel_values': images}
return BatchFeature(data=_snake_case , tensor_type=_snake_case )
| 144 |
import json
import logging
import math
import os
import sys
from dataclasses import dataclass, field
from typing import Optional
from datasets import Dataset, load_dataset
import transformers
from transformers import (
CONFIG_MAPPING,
MODEL_FOR_MASKED_LM_MAPPING,
AutoConfig,
AutoModelForMaskedLM,
AutoTokenizer,
DataCollatorForWholeWordMask,
HfArgumentParser,
Trainer,
TrainingArguments,
set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process
UpperCamelCase = logging.getLogger(__name__)
UpperCamelCase = list(MODEL_FOR_MASKED_LM_MAPPING.keys())
UpperCamelCase = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
@dataclass
class lowerCamelCase__ :
lowerCamelCase_ : Optional[str] = field(
default=UpperCAmelCase, metadata={
'help': (
'The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.'
)
}, )
lowerCamelCase_ : Optional[str] = field(
default=UpperCAmelCase, metadata={'help': 'If training from scratch, pass a model type from the list: ' + ', '.join(UpperCAmelCase )}, )
lowerCamelCase_ : Optional[str] = field(
default=UpperCAmelCase, metadata={
'help': (
'Override some existing default config settings when a model is trained from scratch. Example: '
'n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index'
)
}, )
lowerCamelCase_ : Optional[str] = field(
default=UpperCAmelCase, metadata={'help': 'Pretrained config name or path if not the same as model_name'} )
lowerCamelCase_ : Optional[str] = field(
default=UpperCAmelCase, metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} )
lowerCamelCase_ : Optional[str] = field(
default=UpperCAmelCase, metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}, )
lowerCamelCase_ : bool = field(
default=UpperCAmelCase, metadata={'help': 'Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'}, )
lowerCamelCase_ : str = field(
default='main', metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'}, )
lowerCamelCase_ : bool = field(
default=UpperCAmelCase, metadata={
'help': (
'Will use the token generated when running `huggingface-cli login` (necessary to use this script '
'with private models).'
)
}, )
def UpperCAmelCase_ (self : Any ) -> List[str]:
"""simple docstring"""
if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None):
raise ValueError(
'--config_overrides can\'t be used in combination with --config_name or --model_name_or_path' )
@dataclass
class lowerCamelCase__ :
lowerCamelCase_ : Optional[str] = field(
default=UpperCAmelCase, metadata={'help': 'The name of the dataset to use (via the datasets library).'} )
lowerCamelCase_ : Optional[str] = field(
default=UpperCAmelCase, metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} )
lowerCamelCase_ : Optional[str] = field(default=UpperCAmelCase, metadata={'help': 'The input training data file (a text file).'} )
lowerCamelCase_ : Optional[str] = field(
default=UpperCAmelCase, metadata={'help': 'An optional input evaluation data file to evaluate the perplexity on (a text file).'}, )
lowerCamelCase_ : Optional[str] = field(
default=UpperCAmelCase, metadata={'help': 'An optional input train ref data file for whole word masking in Chinese.'}, )
lowerCamelCase_ : Optional[str] = field(
default=UpperCAmelCase, metadata={'help': 'An optional input validation ref data file for whole word masking in Chinese.'}, )
lowerCamelCase_ : bool = field(
default=UpperCAmelCase, metadata={'help': 'Overwrite the cached training and evaluation sets'} )
lowerCamelCase_ : Optional[int] = field(
default=5, metadata={
'help': 'The percentage of the train set used as validation set in case there\'s no validation split'
}, )
lowerCamelCase_ : Optional[int] = field(
default=UpperCAmelCase, metadata={
'help': (
'The maximum total input sequence length after tokenization. Sequences longer '
'than this will be truncated. Default to the max input length of the model.'
)
}, )
lowerCamelCase_ : Optional[int] = field(
default=UpperCAmelCase, metadata={'help': 'The number of processes to use for the preprocessing.'}, )
lowerCamelCase_ : float = field(
default=0.1_5, metadata={'help': 'Ratio of tokens to mask for masked language modeling loss'} )
lowerCamelCase_ : bool = field(
default=UpperCAmelCase, metadata={
'help': (
'Whether to pad all samples to `max_seq_length`. '
'If False, will pad the samples dynamically when batching to the maximum length in the batch.'
)
}, )
def UpperCAmelCase_ (self : List[str] ) -> Optional[int]:
"""simple docstring"""
if self.train_file is not None:
lowerCamelCase_ : List[str] = self.train_file.split('.' )[-1]
assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
if self.validation_file is not None:
lowerCamelCase_ : Optional[Any] = self.validation_file.split('.' )[-1]
assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
def _a ( lowerCamelCase__ , lowerCamelCase__ ) -> Any:
with open(lowerCamelCase__ , 'r' , encoding='utf-8' ) as f:
lowerCamelCase_ : Any = [json.loads(lowerCamelCase__ ) for line in f.read().splitlines() if (len(lowerCamelCase__ ) > 0 and not line.isspace())]
assert len(lowerCamelCase__ ) == len(lowerCamelCase__ )
lowerCamelCase_ : str = {c: dataset[c] for c in dataset.column_names}
lowerCamelCase_ : List[Any] = refs
return Dataset.from_dict(lowerCamelCase__ )
def _a ( ) -> int:
# See all possible arguments in src/transformers/training_args.py
# or by passing the --help flag to this script.
# We now keep distinct sets of args, for a cleaner separation of concerns.
lowerCamelCase_ : str = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ : List[Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) )
else:
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ : Tuple = parser.parse_args_into_dataclasses()
# Detecting last checkpoint.
lowerCamelCase_ : List[Any] = None
if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir:
lowerCamelCase_ : str = get_last_checkpoint(training_args.output_dir )
if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0:
raise ValueError(
F'Output directory ({training_args.output_dir}) already exists and is not empty. '
'Use --overwrite_output_dir to overcome.' )
elif last_checkpoint is not None:
logger.info(
F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '
'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' )
# Setup logging
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , )
logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN )
# Log on each process the small summary:
logger.warning(
F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'
+ F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' )
# Set the verbosity to info of the Transformers logger (on main process only):
if is_main_process(training_args.local_rank ):
transformers.utils.logging.set_verbosity_info()
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
logger.info('Training/evaluation parameters %s' , lowerCamelCase__ )
# Set seed before initializing model.
set_seed(training_args.seed )
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
# (the dataset will be downloaded automatically from the datasets Hub).
#
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
# 'text' is found. You can easily tweak this behavior (see below).
#
# In distributed training, the load_dataset function guarantee that only one local process can concurrently
# download the dataset.
if data_args.dataset_name is not None:
# Downloading and loading a dataset from the hub.
lowerCamelCase_ : Optional[int] = load_dataset(data_args.dataset_name , data_args.dataset_config_name )
if "validation" not in datasets.keys():
lowerCamelCase_ : List[str] = load_dataset(
data_args.dataset_name , data_args.dataset_config_name , split=F'train[:{data_args.validation_split_percentage}%]' , )
lowerCamelCase_ : List[Any] = load_dataset(
data_args.dataset_name , data_args.dataset_config_name , split=F'train[{data_args.validation_split_percentage}%:]' , )
else:
lowerCamelCase_ : List[str] = {}
if data_args.train_file is not None:
lowerCamelCase_ : int = data_args.train_file
if data_args.validation_file is not None:
lowerCamelCase_ : str = data_args.validation_file
lowerCamelCase_ : str = data_args.train_file.split('.' )[-1]
if extension == "txt":
lowerCamelCase_ : Optional[int] = 'text'
lowerCamelCase_ : List[str] = load_dataset(lowerCamelCase__ , data_files=lowerCamelCase__ )
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
# Load pretrained model and tokenizer
#
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
lowerCamelCase_ : Optional[Any] = {
'cache_dir': model_args.cache_dir,
'revision': model_args.model_revision,
'use_auth_token': True if model_args.use_auth_token else None,
}
if model_args.config_name:
lowerCamelCase_ : Tuple = AutoConfig.from_pretrained(model_args.config_name , **lowerCamelCase__ )
elif model_args.model_name_or_path:
lowerCamelCase_ : Optional[Any] = AutoConfig.from_pretrained(model_args.model_name_or_path , **lowerCamelCase__ )
else:
lowerCamelCase_ : Any = CONFIG_MAPPING[model_args.model_type]()
logger.warning('You are instantiating a new config instance from scratch.' )
if model_args.config_overrides is not None:
logger.info(F'Overriding config: {model_args.config_overrides}' )
config.update_from_string(model_args.config_overrides )
logger.info(F'New config: {config}' )
lowerCamelCase_ : Optional[int] = {
'cache_dir': model_args.cache_dir,
'use_fast': model_args.use_fast_tokenizer,
'revision': model_args.model_revision,
'use_auth_token': True if model_args.use_auth_token else None,
}
if model_args.tokenizer_name:
lowerCamelCase_ : List[str] = AutoTokenizer.from_pretrained(model_args.tokenizer_name , **lowerCamelCase__ )
elif model_args.model_name_or_path:
lowerCamelCase_ : Union[str, Any] = AutoTokenizer.from_pretrained(model_args.model_name_or_path , **lowerCamelCase__ )
else:
raise ValueError(
'You are instantiating a new tokenizer from scratch. This is not supported by this script.'
'You can do it from another script, save it, and load it from here, using --tokenizer_name.' )
if model_args.model_name_or_path:
lowerCamelCase_ : List[Any] = AutoModelForMaskedLM.from_pretrained(
model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=lowerCamelCase__ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , )
else:
logger.info('Training new model from scratch' )
lowerCamelCase_ : Union[str, Any] = AutoModelForMaskedLM.from_config(lowerCamelCase__ )
model.resize_token_embeddings(len(lowerCamelCase__ ) )
# Preprocessing the datasets.
# First we tokenize all the texts.
if training_args.do_train:
lowerCamelCase_ : Dict = datasets['train'].column_names
else:
lowerCamelCase_ : List[str] = datasets['validation'].column_names
lowerCamelCase_ : Any = 'text' if 'text' in column_names else column_names[0]
lowerCamelCase_ : List[Any] = 'max_length' if data_args.pad_to_max_length else False
def tokenize_function(lowerCamelCase__ ):
# Remove empty lines
lowerCamelCase_ : List[str] = [line for line in examples['text'] if len(lowerCamelCase__ ) > 0 and not line.isspace()]
return tokenizer(examples['text'] , padding=lowerCamelCase__ , truncation=lowerCamelCase__ , max_length=data_args.max_seq_length )
lowerCamelCase_ : Any = datasets.map(
lowerCamelCase__ , batched=lowerCamelCase__ , num_proc=data_args.preprocessing_num_workers , remove_columns=[text_column_name] , load_from_cache_file=not data_args.overwrite_cache , )
# Add the chinese references if provided
if data_args.train_ref_file is not None:
lowerCamelCase_ : Dict = add_chinese_references(tokenized_datasets['train'] , data_args.train_ref_file )
if data_args.validation_ref_file is not None:
lowerCamelCase_ : Tuple = add_chinese_references(
tokenized_datasets['validation'] , data_args.validation_ref_file )
# If we have ref files, need to avoid it removed by trainer
lowerCamelCase_ : Optional[int] = data_args.train_ref_file or data_args.validation_ref_file
if has_ref:
lowerCamelCase_ : int = False
# Data collator
# This one will take care of randomly masking the tokens.
lowerCamelCase_ : Tuple = DataCollatorForWholeWordMask(tokenizer=lowerCamelCase__ , mlm_probability=data_args.mlm_probability )
# Initialize our Trainer
lowerCamelCase_ : Optional[Any] = Trainer(
model=lowerCamelCase__ , args=lowerCamelCase__ , train_dataset=tokenized_datasets['train'] if training_args.do_train else None , eval_dataset=tokenized_datasets['validation'] if training_args.do_eval else None , tokenizer=lowerCamelCase__ , data_collator=lowerCamelCase__ , )
# Training
if training_args.do_train:
if last_checkpoint is not None:
lowerCamelCase_ : List[str] = last_checkpoint
elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ):
lowerCamelCase_ : int = model_args.model_name_or_path
else:
lowerCamelCase_ : Union[str, Any] = None
lowerCamelCase_ : Tuple = trainer.train(resume_from_checkpoint=lowerCamelCase__ )
trainer.save_model() # Saves the tokenizer too for easy upload
lowerCamelCase_ : Union[str, Any] = os.path.join(training_args.output_dir , 'train_results.txt' )
if trainer.is_world_process_zero():
with open(lowerCamelCase__ , 'w' ) as writer:
logger.info('***** Train results *****' )
for key, value in sorted(train_result.metrics.items() ):
logger.info(F' {key} = {value}' )
writer.write(F'{key} = {value}\n' )
# Need to save the state, since Trainer.save_model saves only the tokenizer with the model
trainer.state.save_to_json(os.path.join(training_args.output_dir , 'trainer_state.json' ) )
# Evaluation
lowerCamelCase_ : Dict = {}
if training_args.do_eval:
logger.info('*** Evaluate ***' )
lowerCamelCase_ : Optional[Any] = trainer.evaluate()
lowerCamelCase_ : Optional[int] = math.exp(eval_output['eval_loss'] )
lowerCamelCase_ : Dict = perplexity
lowerCamelCase_ : Dict = os.path.join(training_args.output_dir , 'eval_results_mlm_wwm.txt' )
if trainer.is_world_process_zero():
with open(lowerCamelCase__ , 'w' ) as writer:
logger.info('***** Eval results *****' )
for key, value in sorted(results.items() ):
logger.info(F' {key} = {value}' )
writer.write(F'{key} = {value}\n' )
return results
def _a ( lowerCamelCase__ ) -> Any:
# For xla_spawn (TPUs)
main()
if __name__ == "__main__":
main()
| 144 | 1 |
"""simple docstring"""
import os
import socket
from contextlib import contextmanager
import torch
from ..commands.config.default import write_basic_config # noqa: F401
from ..state import PartialState
from .dataclasses import DistributedType
from .imports import is_deepspeed_available, is_tpu_available
from .transformer_engine import convert_model
from .versions import is_torch_version
if is_deepspeed_available():
from deepspeed import DeepSpeedEngine
if is_tpu_available(check_device=False):
import torch_xla.core.xla_model as xm
def _snake_case ( lowerCamelCase__ : Tuple ) -> str:
if is_torch_version("<" , "2.0.0" ) or not hasattr(__UpperCamelCase , "_dynamo" ):
return False
return isinstance(__UpperCamelCase , torch._dynamo.eval_frame.OptimizedModule )
def _snake_case ( lowerCamelCase__ : Optional[int] , lowerCamelCase__ : List[str] = True ) -> Optional[int]:
lowerCamelCase_ : Optional[Any] =(torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)
lowerCamelCase_ : int =is_compiled_module(__UpperCamelCase )
if is_compiled:
lowerCamelCase_ : List[str] =model
lowerCamelCase_ : str =model._orig_mod
if is_deepspeed_available():
options += (DeepSpeedEngine,)
while isinstance(__UpperCamelCase , __UpperCamelCase ):
lowerCamelCase_ : Dict =model.module
if not keep_fpaa_wrapper:
lowerCamelCase_ : Union[str, Any] =getattr(__UpperCamelCase , "forward" )
lowerCamelCase_ : List[str] =model.__dict__.pop("_original_forward" , __UpperCamelCase )
if original_forward is not None:
while hasattr(__UpperCamelCase , "__wrapped__" ):
lowerCamelCase_ : Optional[Any] =forward.__wrapped__
if forward == original_forward:
break
lowerCamelCase_ : List[str] =forward
if getattr(__UpperCamelCase , "_converted_to_transformer_engine" , __UpperCamelCase ):
convert_model(__UpperCamelCase , to_transformer_engine=__UpperCamelCase )
if is_compiled:
lowerCamelCase_ : List[str] =model
lowerCamelCase_ : int =compiled_model
return model
def _snake_case ( ) -> Optional[Any]:
PartialState().wait_for_everyone()
def _snake_case ( lowerCamelCase__ : Dict , lowerCamelCase__ : Union[str, Any] ) -> int:
if PartialState().distributed_type == DistributedType.TPU:
xm.save(__UpperCamelCase , __UpperCamelCase )
elif PartialState().local_process_index == 0:
torch.save(__UpperCamelCase , __UpperCamelCase )
@contextmanager
def _snake_case ( **lowerCamelCase__ : Union[str, Any] ) -> List[str]:
for key, value in kwargs.items():
lowerCamelCase_ : str =str(__UpperCamelCase )
yield
for key in kwargs:
if key.upper() in os.environ:
del os.environ[key.upper()]
def _snake_case ( lowerCamelCase__ : Any ) -> Optional[Any]:
if not hasattr(__UpperCamelCase , "__qualname__" ) and not hasattr(__UpperCamelCase , "__name__" ):
lowerCamelCase_ : Dict =getattr(__UpperCamelCase , "__class__" , __UpperCamelCase )
if hasattr(__UpperCamelCase , "__qualname__" ):
return obj.__qualname__
if hasattr(__UpperCamelCase , "__name__" ):
return obj.__name__
return str(__UpperCamelCase )
def _snake_case ( lowerCamelCase__ : Dict , lowerCamelCase__ : Dict ) -> Dict:
for key, value in source.items():
if isinstance(__UpperCamelCase , __UpperCamelCase ):
lowerCamelCase_ : int =destination.setdefault(__UpperCamelCase , {} )
merge_dicts(__UpperCamelCase , __UpperCamelCase )
else:
lowerCamelCase_ : Dict =value
return destination
def _snake_case ( lowerCamelCase__ : int = None ) -> bool:
if port is None:
lowerCamelCase_ : int =29_500
with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s:
return s.connect_ex(("localhost", port) ) == 0
| 153 |
"""simple docstring"""
import os
from typing import Dict, List, Union
import tensorflow as tf
from keras_nlp.tokenizers import BytePairTokenizer
from tensorflow_text import pad_model_inputs
from .tokenization_gpta import GPTaTokenizer
class _lowercase ( tf.keras.layers.Layer ):
def __init__( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = None ):
super().__init__()
__magic_name__ = pad_token_id
__magic_name__ = max_length
__magic_name__ = vocab
__magic_name__ = merges
__magic_name__ = BytePairTokenizer(UpperCamelCase_ , UpperCamelCase_ , sequence_length=UpperCamelCase_ )
@classmethod
def lowerCAmelCase__ ( cls , UpperCamelCase_ , *UpperCamelCase_ , **UpperCamelCase_ ):
__magic_name__ = [''' '''.join(UpperCamelCase_ ) for m in tokenizer.bpe_ranks.keys()]
__magic_name__ = tokenizer.get_vocab()
return cls(UpperCamelCase_ , UpperCamelCase_ , *UpperCamelCase_ , **UpperCamelCase_ )
@classmethod
def lowerCAmelCase__ ( cls , UpperCamelCase_ , *UpperCamelCase_ , **UpperCamelCase_ ):
__magic_name__ = GPTaTokenizer.from_pretrained(UpperCamelCase_ , *UpperCamelCase_ , **UpperCamelCase_ )
return cls.from_tokenizer(UpperCamelCase_ , *UpperCamelCase_ , **UpperCamelCase_ )
@classmethod
def lowerCAmelCase__ ( cls , UpperCamelCase_ ):
return cls(**UpperCamelCase_ )
def lowerCAmelCase__ ( self ):
return {
"vocab": self.vocab,
"merges": self.merges,
"max_length": self.max_length,
"pad_token_id": self.pad_token_id,
}
def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = None ):
__magic_name__ = self.tf_tokenizer(UpperCamelCase_ )
__magic_name__ = tf.ones_like(UpperCamelCase_ )
if self.pad_token_id is not None:
# pad the tokens up to max length
__magic_name__ = max_length if max_length is not None else self.max_length
if max_length is not None:
__magic_name__ , __magic_name__ = pad_model_inputs(
UpperCamelCase_ , max_seq_length=UpperCamelCase_ , pad_value=self.pad_token_id )
return {"attention_mask": attention_mask, "input_ids": input_ids}
| 490 | 0 |
def UpperCAmelCase_ ( _UpperCAmelCase ):
return sum(i for i in range(1 , number // 2 + 1 ) if number % i == 0 ) == number
if __name__ == "__main__":
print("""Program to check whether a number is a Perfect number or not...""")
lowercase : List[Any] = int(input("""Enter number: """).strip())
print(F"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")
| 584 |
import argparse
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing the experiment tracking capability,
# and builds off the `nlp_example.py` script.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
# - single CPU or single GPU
# - multi GPUS (using PyTorch distributed mode)
# - (multi) TPUs
# - fp16 (mixed-precision) or fp32 (normal precision)
#
# To help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################
lowercase : Dict = 1_6
lowercase : Optional[int] = 3_2
def UpperCAmelCase_ ( _UpperCAmelCase , _UpperCAmelCase = 1_6 ):
lowerCamelCase_: List[Any] = AutoTokenizer.from_pretrained("""bert-base-cased""" )
lowerCamelCase_: List[str] = load_dataset("""glue""" , """mrpc""" )
def tokenize_function(_UpperCAmelCase ):
# max_length=None => use the model max length (it's actually the default)
lowerCamelCase_: Optional[Any] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase )
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
lowerCamelCase_: List[Any] = datasets.map(
_UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
lowerCamelCase_: Optional[int] = tokenized_datasets.rename_column("""label""" , """labels""" )
def collate_fn(_UpperCAmelCase ):
# On TPU it's best to pad everything to the same length or training will be very slow.
lowerCamelCase_: Optional[int] = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
lowerCamelCase_: int = 1_6
elif accelerator.mixed_precision != "no":
lowerCamelCase_: List[str] = 8
else:
lowerCamelCase_: List[Any] = None
return tokenizer.pad(
_UpperCAmelCase , padding="""longest""" , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_tensors="""pt""" , )
# Instantiate dataloaders.
lowerCamelCase_: int = DataLoader(
tokenized_datasets["""train"""] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase )
lowerCamelCase_: Optional[int] = DataLoader(
tokenized_datasets["""validation"""] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase )
return train_dataloader, eval_dataloader
# For testing only
if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1":
from accelerate.test_utils.training import mocked_dataloaders
lowercase : Any = mocked_dataloaders # noqa: F811
def UpperCAmelCase_ ( _UpperCAmelCase , _UpperCAmelCase ):
# For testing only
if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , _UpperCAmelCase ) == "1":
lowerCamelCase_: List[str] = 2
# Initialize Accelerator
# New Code #
# We pass in "all" to `log_with` to grab all available trackers in the environment
# Note: If using a custom `Tracker` class, should be passed in here such as:
# >>> log_with = ["all", MyCustomTrackerClassInstance()]
if args.with_tracking:
lowerCamelCase_: int = Accelerator(
cpu=args.cpu , mixed_precision=args.mixed_precision , log_with="""all""" , project_dir=args.project_dir )
else:
lowerCamelCase_: Dict = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
lowerCamelCase_: Tuple = config["""lr"""]
lowerCamelCase_: Optional[Any] = int(config["""num_epochs"""] )
lowerCamelCase_: int = int(config["""seed"""] )
lowerCamelCase_: Any = int(config["""batch_size"""] )
set_seed(_UpperCAmelCase )
lowerCamelCase_ , lowerCamelCase_: Tuple = get_dataloaders(_UpperCAmelCase , _UpperCAmelCase )
lowerCamelCase_: List[Any] = evaluate.load("""glue""" , """mrpc""" )
# If the batch size is too big we use gradient accumulation
lowerCamelCase_: Dict = 1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
lowerCamelCase_: Union[str, Any] = batch_size // MAX_GPU_BATCH_SIZE
lowerCamelCase_: Optional[Any] = MAX_GPU_BATCH_SIZE
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
lowerCamelCase_: Tuple = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=_UpperCAmelCase )
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
lowerCamelCase_: Dict = model.to(accelerator.device )
# Instantiate optimizer
lowerCamelCase_: str = AdamW(params=model.parameters() , lr=_UpperCAmelCase )
# Instantiate scheduler
lowerCamelCase_: Optional[int] = get_linear_schedule_with_warmup(
optimizer=_UpperCAmelCase , num_warmup_steps=1_0_0 , num_training_steps=(len(_UpperCAmelCase ) * num_epochs) // gradient_accumulation_steps , )
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_: Dict = accelerator.prepare(
_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
# New Code #
# We need to initialize the trackers we use. Overall configurations can also be stored
if args.with_tracking:
lowerCamelCase_: int = os.path.split(_UpperCAmelCase )[-1].split(""".""" )[0]
accelerator.init_trackers(_UpperCAmelCase , _UpperCAmelCase )
# Now we train the model
for epoch in range(_UpperCAmelCase ):
model.train()
# New Code #
# For our tracking example, we will log the total loss of each epoch
if args.with_tracking:
lowerCamelCase_: Tuple = 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 )
lowerCamelCase_: Tuple = model(**_UpperCAmelCase )
lowerCamelCase_: Any = outputs.loss
# New Code #
if args.with_tracking:
total_loss += loss.detach().float()
lowerCamelCase_: Dict = loss / gradient_accumulation_steps
accelerator.backward(_UpperCAmelCase )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
for step, batch in enumerate(_UpperCAmelCase ):
# We could avoid this line since we set the accelerator with `device_placement=True` (the default).
batch.to(accelerator.device )
with torch.no_grad():
lowerCamelCase_: Dict = model(**_UpperCAmelCase )
lowerCamelCase_: Tuple = outputs.logits.argmax(dim=-1 )
lowerCamelCase_ , lowerCamelCase_: List[str] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) )
metric.add_batch(
predictions=_UpperCAmelCase , references=_UpperCAmelCase , )
lowerCamelCase_: List[Any] = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f"""epoch {epoch}:""" , _UpperCAmelCase )
# New Code #
# To actually log, we call `Accelerator.log`
# The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int`
if args.with_tracking:
accelerator.log(
{
"""accuracy""": eval_metric["""accuracy"""],
"""f1""": eval_metric["""f1"""],
"""train_loss""": total_loss.item() / len(_UpperCAmelCase ),
"""epoch""": epoch,
} , step=_UpperCAmelCase , )
# New Code #
# When a run is finished, you should call `accelerator.end_training()`
# to close all of the open trackers
if args.with_tracking:
accelerator.end_training()
def UpperCAmelCase_ ( ):
lowerCamelCase_: Union[str, Any] = argparse.ArgumentParser(description="""Simple example of training script.""" )
parser.add_argument(
"""--mixed_precision""" , type=_UpperCAmelCase , default=_UpperCAmelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose"""
"""between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."""
"""and an Nvidia Ampere GPU.""" , )
parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" )
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""" , )
lowerCamelCase_: Union[str, Any] = parser.parse_args()
lowerCamelCase_: Optional[Any] = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 1_6}
training_function(_UpperCAmelCase , _UpperCAmelCase )
if __name__ == "__main__":
main()
| 584 | 1 |
# 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 argparse import ArgumentParser
from accelerate.commands.config import get_config_parser
from accelerate.commands.env import env_command_parser
from accelerate.commands.launch import launch_command_parser
from accelerate.commands.test import test_command_parser
from accelerate.commands.tpu import tpu_command_parser
def a ( ) -> Any:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : List[str] = ArgumentParser('''Accelerate CLI tool''' , usage='''accelerate <command> [<args>]''' , allow_abbrev=A__ )
SCREAMING_SNAKE_CASE__ : List[Any] = parser.add_subparsers(help='''accelerate command helpers''' )
# Register commands
get_config_parser(subparsers=A__ )
env_command_parser(subparsers=A__ )
launch_command_parser(subparsers=A__ )
tpu_command_parser(subparsers=A__ )
test_command_parser(subparsers=A__ )
# Let's go
SCREAMING_SNAKE_CASE__ : str = parser.parse_args()
if not hasattr(A__ , '''func''' ):
parser.print_help()
exit(1 )
# Run
args.func(A__ )
if __name__ == "__main__":
main()
| 35 |
"""simple docstring"""
from typing import List, Optional, Union
import numpy as np
from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ....feature_extraction_sequence_utils import SequenceFeatureExtractor
from ....feature_extraction_utils import BatchFeature
from ....file_utils import PaddingStrategy, TensorType
from ....utils import logging
lowercase__ : int = logging.get_logger(__name__)
class _UpperCAmelCase ( lowerCAmelCase__):
_lowerCAmelCase : str = ["""input_features""", """attention_mask"""]
def __init__( self : Optional[int] , lowercase_ : str=80 , lowercase_ : Optional[int]=16000 , lowercase_ : List[Any]=0.0 , lowercase_ : int=10 , lowercase_ : Optional[int]=25 , lowercase_ : List[Any]="hamming_window" , lowercase_ : Tuple=3_27_68.0 , lowercase_ : Any=0.97 , lowercase_ : Dict=1.0 , lowercase_ : Union[str, Any]=True , lowercase_ : Any=True , lowercase_ : Optional[Any]=False , **lowercase_ : str , ):
super().__init__(feature_size=lowercase_ , sampling_rate=lowercase_ , padding_value=lowercase_ , **lowercase_ )
snake_case_ : List[Any] = feature_size
snake_case_ : List[Any] = sampling_rate
snake_case_ : str = padding_value
snake_case_ : List[Any] = hop_length
snake_case_ : Dict = win_length
snake_case_ : Optional[int] = frame_signal_scale
snake_case_ : int = preemphasis_coeff
snake_case_ : Optional[int] = mel_floor
snake_case_ : List[str] = normalize_means
snake_case_ : Union[str, Any] = normalize_vars
snake_case_ : Optional[int] = win_function
snake_case_ : List[Any] = return_attention_mask
snake_case_ : Any = win_length * sampling_rate // 1000
snake_case_ : Union[str, Any] = hop_length * sampling_rate // 1000
snake_case_ : Dict = optimal_fft_length(self.sample_size )
snake_case_ : List[str] = (self.n_fft // 2) + 1
def _snake_case ( self : Union[str, Any] , lowercase_ : np.array ):
if self.win_function == "hamming_window":
snake_case_ : List[Any] = window_function(window_length=self.sample_size , name=self.win_function , periodic=lowercase_ )
else:
snake_case_ : Optional[Any] = window_function(window_length=self.sample_size , name=self.win_function )
snake_case_ : List[Any] = mel_filter_bank(
num_frequency_bins=self.n_freqs , num_mel_filters=self.feature_size , min_frequency=0.0 , max_frequency=self.sampling_rate / 2.0 , sampling_rate=self.sampling_rate , )
snake_case_ : str = spectrogram(
one_waveform * self.frame_signal_scale , window=lowercase_ , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , center=lowercase_ , preemphasis=self.preemphasis_coeff , mel_filters=lowercase_ , mel_floor=self.mel_floor , log_mel='''log''' , )
return msfc_features.T
def _snake_case ( self : Optional[int] , lowercase_ : Any , lowercase_ : int , lowercase_ : List[Any] ):
# make sure we normalize float32 arrays
if self.normalize_means:
snake_case_ : int = x[:input_length].mean(axis=0 )
snake_case_ : int = np.subtract(lowercase_ , lowercase_ )
if self.normalize_vars:
snake_case_ : Tuple = x[:input_length].std(axis=0 )
snake_case_ : Union[str, Any] = np.divide(lowercase_ , lowercase_ )
if input_length < x.shape[0]:
snake_case_ : Tuple = padding_value
# make sure array is in float32
snake_case_ : List[Any] = x.astype(np.floataa )
return x
def _snake_case ( self : Union[str, Any] , lowercase_ : List[np.ndarray] , lowercase_ : Optional[np.ndarray] = None ):
snake_case_ : List[str] = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features]
return [self._normalize_one(lowercase_ , lowercase_ , self.padding_value ) for x, n in zip(lowercase_ , lowercase_ )]
def __call__( self : Tuple , lowercase_ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , lowercase_ : Union[bool, str, PaddingStrategy] = False , lowercase_ : Optional[int] = None , lowercase_ : bool = False , lowercase_ : Optional[int] = None , lowercase_ : Optional[bool] = None , lowercase_ : Optional[Union[str, TensorType]] = None , lowercase_ : Optional[int] = None , **lowercase_ : Union[str, Any] , ):
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
f" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with"
f" {self.sampling_rate} and not {sampling_rate}." )
else:
logger.warning(
'''It is strongly recommended to pass the ``sampling_rate`` argument to this function. '''
'''Failing to do so can result in silent errors that might be hard to debug.''' )
snake_case_ : Dict = isinstance(lowercase_ , 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_ : List[Any] = is_batched_numpy or (
isinstance(lowercase_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) ))
)
if is_batched:
snake_case_ : int = [np.asarray(lowercase_ , dtype=np.floataa ) for speech in raw_speech]
elif not is_batched and not isinstance(lowercase_ , np.ndarray ):
snake_case_ : int = np.asarray(lowercase_ , dtype=np.floataa )
elif isinstance(lowercase_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ):
snake_case_ : Optional[Any] = raw_speech.astype(np.floataa )
# always return batch
if not is_batched:
snake_case_ : Dict = [raw_speech]
# extract fbank features
snake_case_ : Optional[int] = [self._extract_mfsc_features(lowercase_ ) for one_waveform in raw_speech]
# convert into correct format for padding
snake_case_ : int = BatchFeature({'''input_features''': features} )
snake_case_ : Tuple = self.pad(
lowercase_ , padding=lowercase_ , max_length=lowercase_ , truncation=lowercase_ , pad_to_multiple_of=lowercase_ , return_attention_mask=lowercase_ , **lowercase_ , )
# make sure list is in array format
snake_case_ : Dict = padded_inputs.get('''input_features''' )
if isinstance(input_features[0] , lowercase_ ):
snake_case_ : Tuple = [np.asarray(lowercase_ , dtype=np.floataa ) for feature in input_features]
snake_case_ : List[Any] = padded_inputs.get('''attention_mask''' )
if attention_mask is not None:
snake_case_ : Tuple = [np.asarray(lowercase_ , dtype=np.intaa ) for array in attention_mask]
if self.normalize_means or self.normalize_vars:
snake_case_ : str = (
np.array(lowercase_ , dtype=np.intaa )
if self._get_padding_strategies(lowercase_ , max_length=lowercase_ ) is not PaddingStrategy.DO_NOT_PAD
and padding
else None
)
snake_case_ : Any = self.normalize(
padded_inputs['''input_features'''] , attention_mask=lowercase_ )
if return_tensors is not None:
snake_case_ : Any = padded_inputs.convert_to_tensors(lowercase_ )
return padded_inputs
| 123 | 0 |
"""simple docstring"""
import warnings
from typing import List
from unittest.mock import Mock
import torch
from torch.utils.data import DataLoader, IterableDataset, TensorDataset
from accelerate.accelerator import Accelerator
from accelerate.utils.dataclasses import DistributedType
class _UpperCAmelCase ( lowercase_ ):
def __init__( self :Optional[Any] , __UpperCamelCase :Optional[int] ):
A = data
def __iter__( self :List[Any] ):
for element in self.data:
yield element
def A__ ( UpperCamelCase=True ):
A = Accelerator(even_batches=_lowerCamelCase )
assert accelerator.num_processes == 2, "this script expects that two GPUs are available"
return accelerator
def A__ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = False ):
if iterable:
A = DummyIterableDataset(torch.as_tensor(range(_lowerCamelCase ) ) )
else:
A = TensorDataset(torch.as_tensor(range(_lowerCamelCase ) ) )
A = DataLoader(_lowerCamelCase , batch_size=_lowerCamelCase )
A = accelerator.prepare(_lowerCamelCase )
return dl
def A__ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , ):
A = create_dataloader(accelerator=_lowerCamelCase , dataset_size=_lowerCamelCase , batch_size=_lowerCamelCase )
A = [len(batch[0] ) for batch in dl]
if accelerator.process_index == 0:
assert batch_sizes == process_0_expected_batch_sizes
elif accelerator.process_index == 1:
assert batch_sizes == process_1_expected_batch_sizes
def A__ ( ):
A = create_accelerator()
# without padding, we would expect a different number of batches
verify_dataloader_batch_sizes(
_lowerCamelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , )
# without padding, we would expect the same number of batches, but different sizes
verify_dataloader_batch_sizes(
_lowerCamelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , )
def A__ ( ):
A = create_accelerator(even_batches=_lowerCamelCase )
verify_dataloader_batch_sizes(
_lowerCamelCase , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , )
verify_dataloader_batch_sizes(
_lowerCamelCase , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , )
def A__ ( ):
A = create_accelerator(even_batches=_lowerCamelCase )
A = torch.nn.Linear(1 , 1 )
A = accelerator.prepare(_lowerCamelCase )
A = create_dataloader(_lowerCamelCase , dataset_size=3 , batch_size=1 )
A = []
with accelerator.join_uneven_inputs([ddp_model] ):
for batch_idx, batch in enumerate(_lowerCamelCase ):
A = ddp_model(batch[0].float() )
A = output.sum()
loss.backward()
batch_idxs.append(_lowerCamelCase )
accelerator.wait_for_everyone()
if accelerator.process_index == 0:
assert batch_idxs == [0, 1]
elif accelerator.process_index == 1:
assert batch_idxs == [0]
def A__ ( UpperCamelCase ):
with warnings.catch_warnings(record=_lowerCamelCase ) as w:
with accelerator.join_uneven_inputs([Mock()] ):
pass
assert issubclass(w[-1].category , _lowerCamelCase )
assert "only supported for multi-GPU" in str(w[-1].message )
def A__ ( ):
A = True
A = False
A = create_accelerator(even_batches=_lowerCamelCase )
A = torch.nn.Linear(1 , 1 )
A = accelerator.prepare(_lowerCamelCase )
A = create_dataloader(_lowerCamelCase , dataset_size=3 , batch_size=1 )
A = create_dataloader(_lowerCamelCase , dataset_size=3 , batch_size=1 )
with accelerator.join_uneven_inputs([ddp_model] , even_batches=_lowerCamelCase ):
A = train_dl.batch_sampler.even_batches
A = valid_dl.batch_sampler.even_batches
assert train_dl_overridden_value == overridden_even_batches
assert valid_dl_overridden_value == overridden_even_batches
assert train_dl.batch_sampler.even_batches == default_even_batches
assert valid_dl.batch_sampler.even_batches == default_even_batches
def A__ ( ):
A = True
A = False
A = create_accelerator(even_batches=_lowerCamelCase )
A = torch.nn.Linear(1 , 1 )
A = accelerator.prepare(_lowerCamelCase )
create_dataloader(_lowerCamelCase , dataset_size=3 , batch_size=1 , iterable=_lowerCamelCase )
A = create_dataloader(_lowerCamelCase , dataset_size=3 , batch_size=1 )
with warnings.catch_warnings():
warnings.filterwarnings("ignore" )
try:
with accelerator.join_uneven_inputs([ddp_model] , even_batches=_lowerCamelCase ):
A = batch_dl.batch_sampler.even_batches
except AttributeError:
# ensure attribute error is not raised when processing iterable dl
raise AssertionError
assert batch_dl_overridden_value == overridden_even_batches
assert batch_dl.batch_sampler.even_batches == default_even_batches
def A__ ( ):
A = create_accelerator()
A = torch.nn.Linear(1 , 1 )
A = accelerator.prepare(_lowerCamelCase )
create_dataloader(_lowerCamelCase , dataset_size=3 , batch_size=1 , iterable=_lowerCamelCase )
with warnings.catch_warnings(record=_lowerCamelCase ) as w:
with accelerator.join_uneven_inputs([ddp_model] , even_batches=_lowerCamelCase ):
pass
assert issubclass(w[-1].category , _lowerCamelCase )
assert "only supported for map-style datasets" in str(w[-1].message )
def A__ ( ):
A = create_accelerator()
accelerator.print("Test that even_batches variable ensures uniform batches across processes" )
test_default_ensures_even_batch_sizes()
accelerator.print("Run tests with even_batches disabled" )
test_can_disable_even_batches()
accelerator.print("Test joining uneven inputs" )
test_can_join_uneven_inputs()
accelerator.print("Test overriding even_batches when joining uneven inputs" )
test_join_can_override_even_batches()
accelerator.print("Test overriding even_batches for mixed dataloader types" )
test_join_can_override_for_mixed_type_dataloaders()
accelerator.print("Test overriding even_batches raises a warning for iterable dataloaders" )
test_join_raises_warning_for_iterable_when_overriding_even_batches()
accelerator.print("Test join with non DDP distributed raises warning" )
A = accelerator.state.distributed_type
A = DistributedType.FSDP
test_join_raises_warning_for_non_ddp_distributed(_lowerCamelCase )
A = original_state
if __name__ == "__main__":
main()
| 700 |
"""simple docstring"""
import json
import os
from dataclasses import dataclass
from functools import partial
from typing import Callable
import flax.linen as nn
import jax
import jax.numpy as jnp
import joblib
import optax
import wandb
from flax import jax_utils, struct, traverse_util
from flax.serialization import from_bytes, to_bytes
from flax.training import train_state
from flax.training.common_utils import shard
from tqdm.auto import tqdm
from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering
from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule
class _UpperCAmelCase ( lowercase_ ):
UpperCamelCase = 42
UpperCamelCase = jnp.floataa
UpperCamelCase = True
def lowerCamelCase ( self :Optional[int] ):
super().setup()
A = nn.Dense(5 , dtype=self.dtype )
def __call__( self :Tuple , *__UpperCamelCase :str , **__UpperCamelCase :List[Any] ):
A = super().__call__(*__UpperCamelCase , **__UpperCamelCase )
A = self.cls(outputs[2] )
return outputs[:2] + (cls_out,)
class _UpperCAmelCase ( lowercase_ ):
UpperCamelCase = FlaxBigBirdForNaturalQuestionsModule
def A__ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ):
def cross_entropy(UpperCamelCase , UpperCamelCase , UpperCamelCase=None ):
A = logits.shape[-1]
A = (labels[..., None] == jnp.arange(UpperCamelCase )[None]).astype("f4" )
A = jax.nn.log_softmax(UpperCamelCase , axis=-1 )
A = -jnp.sum(labels * logits , axis=-1 )
if reduction is not None:
A = reduction(UpperCamelCase )
return loss
A = partial(UpperCamelCase , reduction=jnp.mean )
A = cross_entropy(UpperCamelCase , UpperCamelCase )
A = cross_entropy(UpperCamelCase , UpperCamelCase )
A = cross_entropy(UpperCamelCase , UpperCamelCase )
return (start_loss + end_loss + pooled_loss) / 3
@dataclass
class _UpperCAmelCase :
UpperCamelCase = "google/bigbird-roberta-base"
UpperCamelCase = 3_0_0_0
UpperCamelCase = 1_0_5_0_0
UpperCamelCase = 1_2_8
UpperCamelCase = 3
UpperCamelCase = 1
UpperCamelCase = 5
# tx_args
UpperCamelCase = 3e-5
UpperCamelCase = 0.0
UpperCamelCase = 2_0_0_0_0
UpperCamelCase = 0.0095
UpperCamelCase = "bigbird-roberta-natural-questions"
UpperCamelCase = "training-expt"
UpperCamelCase = "data/nq-training.jsonl"
UpperCamelCase = "data/nq-validation.jsonl"
def lowerCamelCase ( self :Optional[Any] ):
os.makedirs(self.base_dir , exist_ok=__UpperCamelCase )
A = os.path.join(self.base_dir , self.save_dir )
A = self.batch_size_per_device * jax.device_count()
@dataclass
class _UpperCAmelCase :
UpperCamelCase = 42
UpperCamelCase = 4_0_9_6 # no dynamic padding on TPUs
def __call__( self :List[Any] , __UpperCamelCase :Union[str, Any] ):
A = self.collate_fn(__UpperCamelCase )
A = jax.tree_util.tree_map(__UpperCamelCase , __UpperCamelCase )
return batch
def lowerCamelCase ( self :Tuple , __UpperCamelCase :Tuple ):
A, A = self.fetch_inputs(features["input_ids"] )
A = {
"input_ids": jnp.array(__UpperCamelCase , dtype=jnp.intaa ),
"attention_mask": jnp.array(__UpperCamelCase , dtype=jnp.intaa ),
"start_labels": jnp.array(features["start_token"] , dtype=jnp.intaa ),
"end_labels": jnp.array(features["end_token"] , dtype=jnp.intaa ),
"pooled_labels": jnp.array(features["category"] , dtype=jnp.intaa ),
}
return batch
def lowerCamelCase ( self :int , __UpperCamelCase :list ):
A = [self._fetch_inputs(__UpperCamelCase ) for ids in input_ids]
return zip(*__UpperCamelCase )
def lowerCamelCase ( self :Union[str, Any] , __UpperCamelCase :list ):
A = [1 for _ in range(len(__UpperCamelCase ) )]
while len(__UpperCamelCase ) < self.max_length:
input_ids.append(self.pad_id )
attention_mask.append(0 )
return input_ids, attention_mask
def A__ ( UpperCamelCase , UpperCamelCase , UpperCamelCase=None ):
if seed is not None:
A = dataset.shuffle(seed=UpperCamelCase )
for i in range(len(UpperCamelCase ) // batch_size ):
A = dataset[i * batch_size : (i + 1) * batch_size]
yield dict(UpperCamelCase )
@partial(jax.pmap , axis_name="batch" )
def A__ ( UpperCamelCase , UpperCamelCase , **UpperCamelCase ):
def loss_fn(UpperCamelCase ):
A = model_inputs.pop("start_labels" )
A = model_inputs.pop("end_labels" )
A = model_inputs.pop("pooled_labels" )
A = state.apply_fn(**UpperCamelCase , params=UpperCamelCase , dropout_rng=UpperCamelCase , train=UpperCamelCase )
A, A, A = outputs
return state.loss_fn(
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , )
A, A = jax.random.split(UpperCamelCase )
A = jax.value_and_grad(UpperCamelCase )
A, A = grad_fn(state.params )
A = jax.lax.pmean({"loss": loss} , axis_name="batch" )
A = jax.lax.pmean(UpperCamelCase , "batch" )
A = state.apply_gradients(grads=UpperCamelCase )
return state, metrics, new_drp_rng
@partial(jax.pmap , axis_name="batch" )
def A__ ( UpperCamelCase , **UpperCamelCase ):
A = model_inputs.pop("start_labels" )
A = model_inputs.pop("end_labels" )
A = model_inputs.pop("pooled_labels" )
A = state.apply_fn(**UpperCamelCase , params=state.params , train=UpperCamelCase )
A, A, A = outputs
A = state.loss_fn(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase )
A = jax.lax.pmean({"loss": loss} , axis_name="batch" )
return metrics
class _UpperCAmelCase ( train_state.TrainState ):
UpperCamelCase = struct.field(pytree_node=lowercase_ )
@dataclass
class _UpperCAmelCase :
UpperCamelCase = 42
UpperCamelCase = 42
UpperCamelCase = 42
UpperCamelCase = 42
UpperCamelCase = 42
UpperCamelCase = 42
UpperCamelCase = None
def lowerCamelCase ( self :List[Any] , __UpperCamelCase :Optional[int] , __UpperCamelCase :List[str] , __UpperCamelCase :Any , __UpperCamelCase :int=None ):
A = model.params
A = TrainState.create(
apply_fn=model.__call__ , params=__UpperCamelCase , tx=__UpperCamelCase , loss_fn=__UpperCamelCase , )
if ckpt_dir is not None:
A, A, A, A, A = restore_checkpoint(__UpperCamelCase , __UpperCamelCase )
A = {
"lr": args.lr,
"init_lr": args.init_lr,
"warmup_steps": args.warmup_steps,
"num_train_steps": num_train_steps,
"weight_decay": args.weight_decay,
}
A, A = build_tx(**__UpperCamelCase )
A = train_state.TrainState(
step=__UpperCamelCase , apply_fn=model.__call__ , params=__UpperCamelCase , tx=__UpperCamelCase , opt_state=__UpperCamelCase , )
A = args
A = data_collator
A = lr
A = params
A = jax_utils.replicate(__UpperCamelCase )
return state
def lowerCamelCase ( self :List[str] , __UpperCamelCase :List[Any] , __UpperCamelCase :List[Any] , __UpperCamelCase :Optional[int] ):
A = self.args
A = len(__UpperCamelCase ) // args.batch_size
A = jax.random.PRNGKey(0 )
A = jax.random.split(__UpperCamelCase , jax.device_count() )
for epoch in range(args.max_epochs ):
A = jnp.array(0 , dtype=jnp.floataa )
A = get_batched_dataset(__UpperCamelCase , args.batch_size , seed=__UpperCamelCase )
A = 0
for batch in tqdm(__UpperCamelCase , total=__UpperCamelCase , desc=f"Running EPOCH-{epoch}" ):
A = self.data_collator(__UpperCamelCase )
A, A, A = self.train_step_fn(__UpperCamelCase , __UpperCamelCase , **__UpperCamelCase )
running_loss += jax_utils.unreplicate(metrics["loss"] )
i += 1
if i % args.logging_steps == 0:
A = jax_utils.unreplicate(state.step )
A = running_loss.item() / i
A = self.scheduler_fn(state_step - 1 )
A = self.evaluate(__UpperCamelCase , __UpperCamelCase )
A = {
"step": state_step.item(),
"eval_loss": eval_loss.item(),
"tr_loss": tr_loss,
"lr": lr.item(),
}
tqdm.write(str(__UpperCamelCase ) )
self.logger.log(__UpperCamelCase , commit=__UpperCamelCase )
if i % args.save_steps == 0:
self.save_checkpoint(args.save_dir + f"-e{epoch}-s{i}" , state=__UpperCamelCase )
def lowerCamelCase ( self :int , __UpperCamelCase :Optional[Any] , __UpperCamelCase :List[Any] ):
A = get_batched_dataset(__UpperCamelCase , self.args.batch_size )
A = len(__UpperCamelCase ) // self.args.batch_size
A = jnp.array(0 , dtype=jnp.floataa )
A = 0
for batch in tqdm(__UpperCamelCase , total=__UpperCamelCase , desc="Evaluating ... " ):
A = self.data_collator(__UpperCamelCase )
A = self.val_step_fn(__UpperCamelCase , **__UpperCamelCase )
running_loss += jax_utils.unreplicate(metrics["loss"] )
i += 1
return running_loss / i
def lowerCamelCase ( self :List[str] , __UpperCamelCase :List[str] , __UpperCamelCase :Optional[int] ):
A = jax_utils.unreplicate(__UpperCamelCase )
print(f"SAVING CHECKPOINT IN {save_dir}" , end=" ... " )
self.model_save_fn(__UpperCamelCase , params=state.params )
with open(os.path.join(__UpperCamelCase , "opt_state.msgpack" ) , "wb" ) as f:
f.write(to_bytes(state.opt_state ) )
joblib.dump(self.args , os.path.join(__UpperCamelCase , "args.joblib" ) )
joblib.dump(self.data_collator , os.path.join(__UpperCamelCase , "data_collator.joblib" ) )
with open(os.path.join(__UpperCamelCase , "training_state.json" ) , "w" ) as f:
json.dump({"step": state.step.item()} , __UpperCamelCase )
print("DONE" )
def A__ ( UpperCamelCase , UpperCamelCase ):
print(F"RESTORING CHECKPOINT FROM {save_dir}" , end=" ... " )
with open(os.path.join(UpperCamelCase , "flax_model.msgpack" ) , "rb" ) as f:
A = from_bytes(state.params , f.read() )
with open(os.path.join(UpperCamelCase , "opt_state.msgpack" ) , "rb" ) as f:
A = from_bytes(state.opt_state , f.read() )
A = joblib.load(os.path.join(UpperCamelCase , "args.joblib" ) )
A = joblib.load(os.path.join(UpperCamelCase , "data_collator.joblib" ) )
with open(os.path.join(UpperCamelCase , "training_state.json" ) , "r" ) as f:
A = json.load(UpperCamelCase )
A = training_state["step"]
print("DONE" )
return params, opt_state, step, args, data_collator
def A__ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ):
A = num_train_steps - warmup_steps
A = optax.linear_schedule(init_value=UpperCamelCase , end_value=UpperCamelCase , transition_steps=UpperCamelCase )
A = optax.linear_schedule(init_value=UpperCamelCase , end_value=1E-7 , transition_steps=UpperCamelCase )
A = optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] )
return lr
def A__ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ):
def weight_decay_mask(UpperCamelCase ):
A = traverse_util.flatten_dict(UpperCamelCase )
A = {k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()}
return traverse_util.unflatten_dict(UpperCamelCase )
A = scheduler_fn(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase )
A = optax.adamw(learning_rate=UpperCamelCase , weight_decay=UpperCamelCase , mask=UpperCamelCase )
return tx, lr
| 524 | 0 |
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
from ..utils import cached_file
# docstyle-ignore
UpperCamelCase_ = '\nHuman: <<task>>\n\nAssistant: '
UpperCamelCase_ = 'huggingface-tools/default-prompts'
UpperCamelCase_ = {'chat': 'chat_prompt_template.txt', 'run': 'run_prompt_template.txt'}
def _lowerCamelCase ( lowerCamelCase_: Optional[Any] , lowerCamelCase_: Any , lowerCamelCase_: Optional[Any]="run" ):
'''simple docstring'''
if prompt_or_repo_id is None:
A : Union[str, Any] = DEFAULT_PROMPTS_REPO
# prompt is considered a repo ID when it does not contain any kind of space
if re.search('''\\s''' , lowerCamelCase_ ) is not None:
return prompt_or_repo_id
A : Any = cached_file(
lowerCamelCase_ , PROMPT_FILES[mode] , repo_type='''dataset''' , user_agent={'''agent''': agent_name} )
with open(lowerCamelCase_ , '''r''' , encoding='''utf-8''' ) as f:
return f.read()
| 256 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_torch_available,
is_vision_available,
)
_lowerCamelCase : Optional[Any] = {
'configuration_mobilevit': ['MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MobileViTConfig', 'MobileViTOnnxConfig'],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase : Tuple = ['MobileViTFeatureExtractor']
_lowerCamelCase : Union[str, Any] = ['MobileViTImageProcessor']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase : List[Any] = [
'MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST',
'MobileViTForImageClassification',
'MobileViTForSemanticSegmentation',
'MobileViTModel',
'MobileViTPreTrainedModel',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase : Any = [
'TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST',
'TFMobileViTForImageClassification',
'TFMobileViTForSemanticSegmentation',
'TFMobileViTModel',
'TFMobileViTPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_mobilevit import MobileViTFeatureExtractor
from .image_processing_mobilevit import MobileViTImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mobilevit import (
MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
MobileViTForImageClassification,
MobileViTForSemanticSegmentation,
MobileViTModel,
MobileViTPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_mobilevit import (
TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFMobileViTForImageClassification,
TFMobileViTForSemanticSegmentation,
TFMobileViTModel,
TFMobileViTPreTrainedModel,
)
else:
import sys
_lowerCamelCase : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 121 | 0 |
'''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 : List[Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : Tuple="attention" ):
__snake_case : List[str] = params[F"""{prefix}/layers_{i}/{layer_name}/key/kernel"""]
__snake_case : Optional[int] = params[F"""{prefix}/layers_{i}/{layer_name}/out/kernel"""]
__snake_case : Dict = params[F"""{prefix}/layers_{i}/{layer_name}/query/kernel"""]
__snake_case : List[str] = params[F"""{prefix}/layers_{i}/{layer_name}/value/kernel"""]
return k, o, q, v
def UpperCAmelCase__( __UpperCAmelCase : int , __UpperCAmelCase : Any , __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[int]=False ):
if split_mlp_wi:
__snake_case : int = params[F"""{prefix}/layers_{i}/mlp/wi_0/kernel"""]
__snake_case : List[str] = params[F"""{prefix}/layers_{i}/mlp/wi_1/kernel"""]
__snake_case : Tuple = (wi_a, wi_a)
else:
__snake_case : List[Any] = params[F"""{prefix}/layers_{i}/mlp/wi/kernel"""]
__snake_case : Tuple = params[F"""{prefix}/layers_{i}/mlp/wo/kernel"""]
return wi, wo
def UpperCAmelCase__( __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Any , __UpperCAmelCase : List[Any] , __UpperCAmelCase : List[str] ):
return params[F"""{prefix}/layers_{i}/{layer_name}/scale"""]
def UpperCAmelCase__( __UpperCAmelCase : Union[str, Any] , *, __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[Any] ):
__snake_case : int = traverse_util.flatten_dict(variables['target'] )
__snake_case : List[str] = {'/'.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 : List[Any] = 'encoder/layers_0/mlp/wi_0/kernel' in old
print('Split MLP:' , __UpperCAmelCase )
__snake_case : str = collections.OrderedDict()
# Shared embeddings.
__snake_case : Optional[int] = old['token_embedder/embedding']
# Encoder.
for i in range(__UpperCAmelCase ):
# Block i, layer 0 (Self Attention).
__snake_case : Union[str, Any] = tax_layer_norm_lookup(__UpperCAmelCase , __UpperCAmelCase , 'encoder' , 'pre_attention_layer_norm' )
__snake_case , __snake_case , __snake_case , __snake_case : List[str] = tax_attention_lookup(__UpperCAmelCase , __UpperCAmelCase , 'encoder' , 'attention' )
__snake_case : Any = layer_norm
__snake_case : Union[str, Any] = k.T
__snake_case : Tuple = o.T
__snake_case : Optional[int] = q.T
__snake_case : List[Any] = v.T
# Block i, layer 1 (MLP).
__snake_case : Optional[Any] = tax_layer_norm_lookup(__UpperCAmelCase , __UpperCAmelCase , 'encoder' , 'pre_mlp_layer_norm' )
__snake_case , __snake_case : Any = tax_mlp_lookup(__UpperCAmelCase , __UpperCAmelCase , 'encoder' , __UpperCAmelCase )
__snake_case : int = layer_norm
if split_mlp_wi:
__snake_case : int = wi[0].T
__snake_case : Optional[int] = wi[1].T
else:
__snake_case : List[str] = wi.T
__snake_case : Dict = wo.T
__snake_case : List[Any] = old[
'encoder/relpos_bias/rel_embedding'
].T
__snake_case : str = old['encoder/encoder_norm/scale']
if not is_encoder_only:
# Decoder.
for i in range(__UpperCAmelCase ):
# Block i, layer 0 (Self Attention).
__snake_case : Dict = tax_layer_norm_lookup(__UpperCAmelCase , __UpperCAmelCase , 'decoder' , 'pre_self_attention_layer_norm' )
__snake_case , __snake_case , __snake_case , __snake_case : int = tax_attention_lookup(__UpperCAmelCase , __UpperCAmelCase , 'decoder' , 'self_attention' )
__snake_case : List[Any] = layer_norm
__snake_case : Tuple = k.T
__snake_case : int = o.T
__snake_case : List[str] = q.T
__snake_case : Optional[Any] = v.T
# Block i, layer 1 (Cross Attention).
__snake_case : Optional[Any] = tax_layer_norm_lookup(__UpperCAmelCase , __UpperCAmelCase , 'decoder' , 'pre_cross_attention_layer_norm' )
__snake_case , __snake_case , __snake_case , __snake_case : Optional[int] = tax_attention_lookup(__UpperCAmelCase , __UpperCAmelCase , 'decoder' , 'encoder_decoder_attention' )
__snake_case : Tuple = layer_norm
__snake_case : List[Any] = k.T
__snake_case : List[Any] = o.T
__snake_case : Dict = q.T
__snake_case : List[str] = v.T
# Block i, layer 2 (MLP).
__snake_case : Union[str, Any] = tax_layer_norm_lookup(__UpperCAmelCase , __UpperCAmelCase , 'decoder' , 'pre_mlp_layer_norm' )
__snake_case , __snake_case : Tuple = tax_mlp_lookup(__UpperCAmelCase , __UpperCAmelCase , 'decoder' , __UpperCAmelCase )
__snake_case : Optional[int] = layer_norm
if split_mlp_wi:
__snake_case : Tuple = wi[0].T
__snake_case : Dict = wi[1].T
else:
__snake_case : List[Any] = wi.T
__snake_case : List[str] = wo.T
__snake_case : List[str] = old['decoder/decoder_norm/scale']
__snake_case : Any = 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 : List[Any] = old['decoder/logits_dense/kernel'].T
return new
def UpperCAmelCase__( __UpperCAmelCase : int , __UpperCAmelCase : Any ):
__snake_case : List[Any] = 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 : List[str] = state_dict['shared.weight']
if not is_encoder_only:
if "decoder.embed_tokens.weight" not in state_dict:
__snake_case : Dict = 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 : List[Any] = state_dict['shared.weight']
return state_dict
def UpperCAmelCase__( __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Dict , __UpperCAmelCase : int , __UpperCAmelCase : Optional[Any] ):
__snake_case : Union[str, Any] = checkpoints.load_tax_checkpoint(__UpperCAmelCase )
__snake_case : Union[str, Any] = convert_tax_to_pytorch(__UpperCAmelCase , num_layers=config.num_layers , is_encoder_only=__UpperCAmelCase )
__snake_case : List[str] = make_state_dict(__UpperCAmelCase , __UpperCAmelCase )
model.load_state_dict(__UpperCAmelCase , strict=__UpperCAmelCase )
def UpperCAmelCase__( __UpperCAmelCase : str , __UpperCAmelCase : int , __UpperCAmelCase : Tuple , __UpperCAmelCase : Union[str, Any] = False ):
__snake_case : Dict = 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 : List[str] = TaEncoderModel(__UpperCAmelCase )
else:
__snake_case : Tuple = 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__":
__magic_name__ = 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
)
__magic_name__ = parser.parse_args()
convert_tax_checkpoint_to_pytorch(
args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only
)
| 717 |
import gc
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer
from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import 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):
"""simple docstring"""
__UpperCAmelCase = ShapEPipeline
__UpperCAmelCase = ["prompt"]
__UpperCAmelCase = ["prompt"]
__UpperCAmelCase = [
"num_images_per_prompt",
"num_inference_steps",
"generator",
"latents",
"guidance_scale",
"frame_size",
"output_type",
"return_dict",
]
__UpperCAmelCase = False
@property
def lowercase_ ( self ):
return 32
@property
def lowercase_ ( self ):
return 32
@property
def lowercase_ ( self ):
return self.time_input_dim * 4
@property
def lowercase_ ( self ):
return 8
@property
def lowercase_ ( self ):
__snake_case : Optional[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )
return tokenizer
@property
def lowercase_ ( self ):
torch.manual_seed(0 )
__snake_case : Union[str, Any] = 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(_UpperCAmelCase )
@property
def lowercase_ ( self ):
torch.manual_seed(0 )
__snake_case : Any = {
'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',
'encoder_hid_proj_type': None,
'added_emb_type': None,
}
__snake_case : Dict = PriorTransformer(**_UpperCAmelCase )
return model
@property
def lowercase_ ( self ):
torch.manual_seed(0 )
__snake_case : Tuple = {
'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 : Union[str, Any] = ShapERenderer(**_UpperCAmelCase )
return model
def lowercase_ ( self ):
__snake_case : Tuple = self.dummy_prior
__snake_case : Dict = self.dummy_text_encoder
__snake_case : Optional[int] = self.dummy_tokenizer
__snake_case : str = self.dummy_renderer
__snake_case : Tuple = HeunDiscreteScheduler(
beta_schedule='exp' , num_train_timesteps=1_024 , prediction_type='sample' , use_karras_sigmas=_UpperCAmelCase , clip_sample=_UpperCAmelCase , clip_sample_range=1.0 , )
__snake_case : Optional[int] = {
'prior': prior,
'text_encoder': text_encoder,
'tokenizer': tokenizer,
'renderer': renderer,
'scheduler': scheduler,
}
return components
def lowercase_ ( self , _UpperCAmelCase , _UpperCAmelCase=0 ):
if str(_UpperCAmelCase ).startswith('mps' ):
__snake_case : Union[str, Any] = torch.manual_seed(_UpperCAmelCase )
else:
__snake_case : int = torch.Generator(device=_UpperCAmelCase ).manual_seed(_UpperCAmelCase )
__snake_case : Tuple = {
'prompt': 'horse',
'generator': generator,
'num_inference_steps': 1,
'frame_size': 32,
'output_type': 'np',
}
return inputs
def lowercase_ ( self ):
__snake_case : Optional[int] = 'cpu'
__snake_case : Tuple = self.get_dummy_components()
__snake_case : Tuple = self.pipeline_class(**_UpperCAmelCase )
__snake_case : Any = pipe.to(_UpperCAmelCase )
pipe.set_progress_bar_config(disable=_UpperCAmelCase )
__snake_case : Any = pipe(**self.get_dummy_inputs(_UpperCAmelCase ) )
__snake_case : Union[str, Any] = output.images[0]
__snake_case : Tuple = image[0, -3:, -3:, -1]
assert image.shape == (20, 32, 32, 3)
__snake_case : Dict = 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 lowercase_ ( self ):
# NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
self._test_inference_batch_consistent(batch_sizes=[1, 2] )
def lowercase_ ( self ):
__snake_case : List[str] = torch_device == 'cpu'
__snake_case : int = True
self._test_inference_batch_single_identical(
batch_size=2 , test_max_difference=_UpperCAmelCase , relax_max_difference=_UpperCAmelCase , )
def lowercase_ ( self ):
__snake_case : Dict = self.get_dummy_components()
__snake_case : Any = self.pipeline_class(**_UpperCAmelCase )
__snake_case : Tuple = pipe.to(_UpperCAmelCase )
pipe.set_progress_bar_config(disable=_UpperCAmelCase )
__snake_case : int = 1
__snake_case : Optional[int] = 2
__snake_case : List[Any] = self.get_dummy_inputs(_UpperCAmelCase )
for key in inputs.keys():
if key in self.batch_params:
__snake_case : Union[str, Any] = batch_size * [inputs[key]]
__snake_case : Any = pipe(**_UpperCAmelCase , num_images_per_prompt=_UpperCAmelCase )[0]
assert images.shape[0] == batch_size * num_images_per_prompt
@slow
@require_torch_gpu
class __SCREAMING_SNAKE_CASE ( unittest.TestCase):
"""simple docstring"""
def lowercase_ ( self ):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def lowercase_ ( self ):
__snake_case : str = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/shap_e/test_shap_e_np_out.npy' )
__snake_case : Any = ShapEPipeline.from_pretrained('openai/shap-e' )
__snake_case : List[str] = pipe.to(_UpperCAmelCase )
pipe.set_progress_bar_config(disable=_UpperCAmelCase )
__snake_case : Optional[Any] = torch.Generator(device=_UpperCAmelCase ).manual_seed(0 )
__snake_case : Optional[Any] = pipe(
'a shark' , generator=_UpperCAmelCase , guidance_scale=15.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0]
assert images.shape == (20, 64, 64, 3)
assert_mean_pixel_difference(_UpperCAmelCase , _UpperCAmelCase )
| 679 | 0 |
import gc
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
EulerAncestralDiscreteScheduler,
LMSDiscreteScheduler,
PNDMScheduler,
StableDiffusionPanoramaPipeline,
UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin
enable_full_determinism()
@skip_mps
class __magic_name__ (snake_case_ ,snake_case_ ,unittest.TestCase ):
'''simple docstring'''
__lowercase : Tuple = StableDiffusionPanoramaPipeline
__lowercase : int = TEXT_TO_IMAGE_PARAMS
__lowercase : Any = TEXT_TO_IMAGE_BATCH_PARAMS
__lowercase : Union[str, Any] = TEXT_TO_IMAGE_IMAGE_PARAMS
__lowercase : Dict = TEXT_TO_IMAGE_IMAGE_PARAMS
def SCREAMING_SNAKE_CASE__ ( self:Tuple ):
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 , )
snake_case__ = DDIMScheduler()
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 , )
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=10_00 , )
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 SCREAMING_SNAKE_CASE__ ( self:Optional[Any] , _a:str , _a:Optional[Any]=0 ):
snake_case__ = torch.manual_seed(_a )
snake_case__ = {
'''prompt''': '''a photo of the dolomites''',
'''generator''': generator,
# Setting height and width to None to prevent OOMs on CPU.
'''height''': None,
'''width''': None,
'''num_inference_steps''': 1,
'''guidance_scale''': 6.0,
'''output_type''': '''numpy''',
}
return inputs
def SCREAMING_SNAKE_CASE__ ( self:List[str] ):
snake_case__ = '''cpu''' # ensure determinism for the device-dependent torch.Generator
snake_case__ = self.get_dummy_components()
snake_case__ = StableDiffusionPanoramaPipeline(**_a )
snake_case__ = sd_pipe.to(_a )
sd_pipe.set_progress_bar_config(disable=_a )
snake_case__ = self.get_dummy_inputs(_a )
snake_case__ = sd_pipe(**_a ).images
snake_case__ = image[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
snake_case__ = np.array([0.6186, 0.5374, 0.4915, 0.4135, 0.4114, 0.4563, 0.5128, 0.4977, 0.4757] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def SCREAMING_SNAKE_CASE__ ( self:Optional[int] ):
super().test_inference_batch_consistent(batch_sizes=[1, 2] )
def SCREAMING_SNAKE_CASE__ ( self:List[str] ):
super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.25e-3 )
def SCREAMING_SNAKE_CASE__ ( self:int ):
snake_case__ = '''cpu''' # ensure determinism for the device-dependent torch.Generator
snake_case__ = self.get_dummy_components()
snake_case__ = StableDiffusionPanoramaPipeline(**_a )
snake_case__ = sd_pipe.to(_a )
sd_pipe.set_progress_bar_config(disable=_a )
snake_case__ = self.get_dummy_inputs(_a )
snake_case__ = '''french fries'''
snake_case__ = sd_pipe(**_a , negative_prompt=_a )
snake_case__ = output.images
snake_case__ = image[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
snake_case__ = np.array([0.6187, 0.5375, 0.4915, 0.4136, 0.4114, 0.4563, 0.5128, 0.4976, 0.4757] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def SCREAMING_SNAKE_CASE__ ( self:Optional[int] ):
snake_case__ = '''cpu''' # ensure determinism for the device-dependent torch.Generator
snake_case__ = self.get_dummy_components()
snake_case__ = StableDiffusionPanoramaPipeline(**_a )
snake_case__ = sd_pipe.to(_a )
sd_pipe.set_progress_bar_config(disable=_a )
snake_case__ = self.get_dummy_inputs(_a )
snake_case__ = sd_pipe(**_a , view_batch_size=2 )
snake_case__ = output.images
snake_case__ = image[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
snake_case__ = np.array([0.6187, 0.5375, 0.4915, 0.4136, 0.4114, 0.4563, 0.5128, 0.4976, 0.4757] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def SCREAMING_SNAKE_CASE__ ( self:str ):
snake_case__ = '''cpu''' # ensure determinism for the device-dependent torch.Generator
snake_case__ = self.get_dummy_components()
snake_case__ = EulerAncestralDiscreteScheduler(
beta_start=0.00085 , beta_end=0.012 , beta_schedule='''scaled_linear''' )
snake_case__ = StableDiffusionPanoramaPipeline(**_a )
snake_case__ = sd_pipe.to(_a )
sd_pipe.set_progress_bar_config(disable=_a )
snake_case__ = self.get_dummy_inputs(_a )
snake_case__ = sd_pipe(**_a ).images
snake_case__ = image[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
snake_case__ = np.array([0.4024, 0.6510, 0.4901, 0.5378, 0.5813, 0.5622, 0.4795, 0.4467, 0.4952] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def SCREAMING_SNAKE_CASE__ ( self:Optional[int] ):
snake_case__ = '''cpu''' # ensure determinism for the device-dependent torch.Generator
snake_case__ = self.get_dummy_components()
snake_case__ = PNDMScheduler(
beta_start=0.00085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , skip_prk_steps=_a )
snake_case__ = StableDiffusionPanoramaPipeline(**_a )
snake_case__ = sd_pipe.to(_a )
sd_pipe.set_progress_bar_config(disable=_a )
snake_case__ = self.get_dummy_inputs(_a )
snake_case__ = sd_pipe(**_a ).images
snake_case__ = image[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
snake_case__ = np.array([0.6391, 0.6291, 0.4861, 0.5134, 0.5552, 0.4578, 0.5032, 0.5023, 0.4539] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
@slow
@require_torch_gpu
class __magic_name__ (unittest.TestCase ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE__ ( self:Optional[int] ):
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def SCREAMING_SNAKE_CASE__ ( self:Dict , _a:Any=0 ):
snake_case__ = torch.manual_seed(_a )
snake_case__ = {
'''prompt''': '''a photo of the dolomites''',
'''generator''': generator,
'''num_inference_steps''': 3,
'''guidance_scale''': 7.5,
'''output_type''': '''numpy''',
}
return inputs
def SCREAMING_SNAKE_CASE__ ( self:str ):
snake_case__ = '''stabilityai/stable-diffusion-2-base'''
snake_case__ = DDIMScheduler.from_pretrained(_a , subfolder='''scheduler''' )
snake_case__ = StableDiffusionPanoramaPipeline.from_pretrained(_a , scheduler=_a , safety_checker=_a )
pipe.to(_a )
pipe.set_progress_bar_config(disable=_a )
pipe.enable_attention_slicing()
snake_case__ = self.get_inputs()
snake_case__ = pipe(**_a ).images
snake_case__ = image[0, -3:, -3:, -1].flatten()
assert image.shape == (1, 5_12, 20_48, 3)
snake_case__ = np.array(
[
0.36968392,
0.27025372,
0.32446766,
0.28379387,
0.36363274,
0.30733347,
0.27100027,
0.27054125,
0.25536096,
] )
assert np.abs(expected_slice - image_slice ).max() < 1e-2
def SCREAMING_SNAKE_CASE__ ( self:Dict ):
snake_case__ = StableDiffusionPanoramaPipeline.from_pretrained(
'''stabilityai/stable-diffusion-2-base''' , safety_checker=_a )
snake_case__ = LMSDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.to(_a )
pipe.set_progress_bar_config(disable=_a )
pipe.enable_attention_slicing()
snake_case__ = self.get_inputs()
snake_case__ = pipe(**_a ).images
snake_case__ = image[0, -3:, -3:, -1].flatten()
assert image.shape == (1, 5_12, 20_48, 3)
snake_case__ = np.array(
[
[
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
]
] )
assert np.abs(expected_slice - image_slice ).max() < 1e-3
def SCREAMING_SNAKE_CASE__ ( self:int ):
snake_case__ = 0
def callback_fn(_a:int , _a:int , _a:torch.FloatTensor ) -> None:
snake_case__ = True
nonlocal number_of_steps
number_of_steps += 1
if step == 1:
snake_case__ = latents.detach().cpu().numpy()
assert latents.shape == (1, 4, 64, 2_56)
snake_case__ = latents[0, -3:, -3:, -1]
snake_case__ = np.array(
[
0.18681869,
0.33907816,
0.5361276,
0.14432865,
-0.02856611,
-0.73941123,
0.23397987,
0.47322682,
-0.37823164,
] )
assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2
elif step == 2:
snake_case__ = latents.detach().cpu().numpy()
assert latents.shape == (1, 4, 64, 2_56)
snake_case__ = latents[0, -3:, -3:, -1]
snake_case__ = np.array(
[
0.18539645,
0.33987248,
0.5378559,
0.14437142,
-0.02455261,
-0.7338317,
0.23990755,
0.47356272,
-0.3786505,
] )
assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2
snake_case__ = False
snake_case__ = '''stabilityai/stable-diffusion-2-base'''
snake_case__ = DDIMScheduler.from_pretrained(_a , subfolder='''scheduler''' )
snake_case__ = StableDiffusionPanoramaPipeline.from_pretrained(_a , scheduler=_a , safety_checker=_a )
snake_case__ = pipe.to(_a )
pipe.set_progress_bar_config(disable=_a )
pipe.enable_attention_slicing()
snake_case__ = self.get_inputs()
pipe(**_a , callback=_a , callback_steps=1 )
assert callback_fn.has_been_called
assert number_of_steps == 3
def SCREAMING_SNAKE_CASE__ ( self:Tuple ):
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated()
torch.cuda.reset_peak_memory_stats()
snake_case__ = '''stabilityai/stable-diffusion-2-base'''
snake_case__ = DDIMScheduler.from_pretrained(_a , subfolder='''scheduler''' )
snake_case__ = StableDiffusionPanoramaPipeline.from_pretrained(_a , scheduler=_a , safety_checker=_a )
snake_case__ = pipe.to(_a )
pipe.set_progress_bar_config(disable=_a )
pipe.enable_attention_slicing(1 )
pipe.enable_sequential_cpu_offload()
snake_case__ = self.get_inputs()
snake_case__ = pipe(**_a )
snake_case__ = torch.cuda.max_memory_allocated()
# make sure that less than 5.2 GB is allocated
assert mem_bytes < 5.5 * 10**9
| 33 |
from copy import deepcopy
class __magic_name__ :
'''simple docstring'''
def __init__( self:int , _a:list[int] | None = None , _a:int | None = None ):
if arr is None and size is not None:
snake_case__ = size
snake_case__ = [0] * size
elif arr is not None:
self.init(_a )
else:
raise ValueError('''Either arr or size must be specified''' )
def SCREAMING_SNAKE_CASE__ ( self:Any , _a:list[int] ):
snake_case__ = len(_a )
snake_case__ = deepcopy(_a )
for i in range(1 , self.size ):
snake_case__ = self.next_(_a )
if j < self.size:
self.tree[j] += self.tree[i]
def SCREAMING_SNAKE_CASE__ ( self:Any ):
snake_case__ = self.tree[:]
for i in range(self.size - 1 , 0 , -1 ):
snake_case__ = self.next_(_a )
if j < self.size:
arr[j] -= arr[i]
return arr
@staticmethod
def SCREAMING_SNAKE_CASE__ ( _a:int ):
return index + (index & (-index))
@staticmethod
def SCREAMING_SNAKE_CASE__ ( _a:int ):
return index - (index & (-index))
def SCREAMING_SNAKE_CASE__ ( self:List[Any] , _a:int , _a:int ):
if index == 0:
self.tree[0] += value
return
while index < self.size:
self.tree[index] += value
snake_case__ = self.next_(_a )
def SCREAMING_SNAKE_CASE__ ( self:Dict , _a:int , _a:int ):
self.add(_a , value - self.get(_a ) )
def SCREAMING_SNAKE_CASE__ ( self:Optional[Any] , _a:int ):
if right == 0:
return 0
snake_case__ = self.tree[0]
right -= 1 # make right inclusive
while right > 0:
result += self.tree[right]
snake_case__ = self.prev(_a )
return result
def SCREAMING_SNAKE_CASE__ ( self:Dict , _a:int , _a:int ):
return self.prefix(_a ) - self.prefix(_a )
def SCREAMING_SNAKE_CASE__ ( self:str , _a:int ):
return self.query(_a , index + 1 )
def SCREAMING_SNAKE_CASE__ ( self:str , _a:int ):
value -= self.tree[0]
if value < 0:
return -1
snake_case__ = 1 # Largest power of 2 <= size
while j * 2 < self.size:
j *= 2
snake_case__ = 0
while j > 0:
if i + j < self.size and self.tree[i + j] <= value:
value -= self.tree[i + j]
i += j
j //= 2
return i
if __name__ == "__main__":
import doctest
doctest.testmod()
| 33 | 1 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_torch_available,
)
__snake_case : Dict = {
'configuration_vision_encoder_decoder': ['VisionEncoderDecoderConfig', 'VisionEncoderDecoderOnnxConfig']
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case : Any = ['VisionEncoderDecoderModel']
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case : List[str] = ['TFVisionEncoderDecoderModel']
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case : str = ['FlaxVisionEncoderDecoderModel']
if TYPE_CHECKING:
from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel
else:
import sys
__snake_case : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 615 |
"""simple docstring"""
import itertools
import random
import unittest
import numpy as np
from transformers import is_speech_available
from transformers.testing_utils import require_torch, require_torchaudio
from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin
if is_speech_available():
from transformers import SpeechaTextFeatureExtractor
__snake_case : Union[str, Any] = random.Random()
def _lowercase ( __snake_case ,__snake_case=1.0 ,__snake_case=None ,__snake_case=None ) -> List[Any]:
if rng is None:
__lowerCAmelCase : Dict = global_rng
__lowerCAmelCase : Tuple = []
for batch_idx in range(shape[0] ):
values.append([] )
for _ in range(shape[1] ):
values[-1].append(rng.random() * scale )
return values
@require_torch
@require_torchaudio
class A__ ( unittest.TestCase ):
'''simple docstring'''
def __init__( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: List[Any]=7 , _SCREAMING_SNAKE_CASE: int=400 , _SCREAMING_SNAKE_CASE: List[str]=2000 , _SCREAMING_SNAKE_CASE: Optional[Any]=24 , _SCREAMING_SNAKE_CASE: Dict=24 , _SCREAMING_SNAKE_CASE: Optional[int]=0.0 , _SCREAMING_SNAKE_CASE: Any=1_6000 , _SCREAMING_SNAKE_CASE: int=True , _SCREAMING_SNAKE_CASE: Union[str, Any]=True , ) -> List[Any]:
"""simple docstring"""
__lowerCAmelCase : Any = parent
__lowerCAmelCase : str = batch_size
__lowerCAmelCase : List[str] = min_seq_length
__lowerCAmelCase : Any = max_seq_length
__lowerCAmelCase : Dict = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
__lowerCAmelCase : Union[str, Any] = feature_size
__lowerCAmelCase : int = num_mel_bins
__lowerCAmelCase : Optional[Any] = padding_value
__lowerCAmelCase : List[Any] = sampling_rate
__lowerCAmelCase : Dict = return_attention_mask
__lowerCAmelCase : int = do_normalize
def _SCREAMING_SNAKE_CASE ( self: Any) -> Optional[int]:
"""simple docstring"""
return {
"feature_size": self.feature_size,
"num_mel_bins": self.num_mel_bins,
"padding_value": self.padding_value,
"sampling_rate": self.sampling_rate,
"return_attention_mask": self.return_attention_mask,
"do_normalize": self.do_normalize,
}
def _SCREAMING_SNAKE_CASE ( self: Tuple , _SCREAMING_SNAKE_CASE: Tuple=False , _SCREAMING_SNAKE_CASE: int=False) -> Optional[int]:
"""simple docstring"""
def _flatten(_SCREAMING_SNAKE_CASE: Optional[Any]):
return list(itertools.chain(*_SCREAMING_SNAKE_CASE))
if equal_length:
__lowerCAmelCase : Tuple = [floats_list((self.max_seq_length, self.feature_size)) for _ in range(self.batch_size)]
else:
# make sure that inputs increase in size
__lowerCAmelCase : List[Any] = [
floats_list((x, self.feature_size))
for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff)
]
if numpify:
__lowerCAmelCase : Any = [np.asarray(_SCREAMING_SNAKE_CASE) for x in speech_inputs]
return speech_inputs
@require_torch
@require_torchaudio
class A__ ( __SCREAMING_SNAKE_CASE , unittest.TestCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE = SpeechaTextFeatureExtractor if is_speech_available() else None
def _SCREAMING_SNAKE_CASE ( self: List[Any]) -> Tuple:
"""simple docstring"""
__lowerCAmelCase : Tuple = SpeechaTextFeatureExtractionTester(self)
def _SCREAMING_SNAKE_CASE ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Optional[Any]) -> str:
"""simple docstring"""
self.assertTrue(np.all(np.mean(_SCREAMING_SNAKE_CASE , axis=0) < 1e-3))
self.assertTrue(np.all(np.abs(np.var(_SCREAMING_SNAKE_CASE , axis=0) - 1) < 1e-3))
def _SCREAMING_SNAKE_CASE ( self: Union[str, Any]) -> int:
"""simple docstring"""
__lowerCAmelCase : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
# create three inputs of length 800, 1000, and 1200
__lowerCAmelCase : Tuple = [floats_list((1, x))[0] for x in range(800 , 1400 , 200)]
__lowerCAmelCase : Optional[int] = [np.asarray(_SCREAMING_SNAKE_CASE) for speech_input in speech_inputs]
# Test feature size
__lowerCAmelCase : Optional[int] = feature_extractor(_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , return_tensors="np").input_features
self.assertTrue(input_features.ndim == 3)
self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size)
# Test not batched input
__lowerCAmelCase : Optional[Any] = feature_extractor(speech_inputs[0] , return_tensors="np").input_features
__lowerCAmelCase : Any = feature_extractor(np_speech_inputs[0] , return_tensors="np").input_features
self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1e-3))
# Test batched
__lowerCAmelCase : Tuple = feature_extractor(_SCREAMING_SNAKE_CASE , return_tensors="np").input_features
__lowerCAmelCase : Tuple = feature_extractor(_SCREAMING_SNAKE_CASE , return_tensors="np").input_features
for enc_seq_a, enc_seq_a in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE):
self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1e-3))
# Test 2-D numpy arrays are batched.
__lowerCAmelCase : List[str] = [floats_list((1, x))[0] for x in (800, 800, 800)]
__lowerCAmelCase : Dict = np.asarray(_SCREAMING_SNAKE_CASE)
__lowerCAmelCase : Optional[int] = feature_extractor(_SCREAMING_SNAKE_CASE , return_tensors="np").input_features
__lowerCAmelCase : Optional[Any] = feature_extractor(_SCREAMING_SNAKE_CASE , return_tensors="np").input_features
for enc_seq_a, enc_seq_a in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE):
self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1e-3))
def _SCREAMING_SNAKE_CASE ( self: Union[str, Any]) -> List[Any]:
"""simple docstring"""
__lowerCAmelCase : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
__lowerCAmelCase : Tuple = [floats_list((1, x))[0] for x in range(800 , 1400 , 200)]
__lowerCAmelCase : Optional[Any] = ["longest", "max_length", "do_not_pad"]
__lowerCAmelCase : str = [None, 16, None]
for max_length, padding in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE):
__lowerCAmelCase : str = feature_extractor(
_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE)
__lowerCAmelCase : Optional[Any] = inputs.input_features
__lowerCAmelCase : Optional[Any] = inputs.attention_mask
__lowerCAmelCase : Tuple = [np.sum(_SCREAMING_SNAKE_CASE) for x in attention_mask]
self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]])
self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]])
self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]])
def _SCREAMING_SNAKE_CASE ( self: Any) -> Optional[Any]:
"""simple docstring"""
__lowerCAmelCase : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
__lowerCAmelCase : Any = [floats_list((1, x))[0] for x in range(800 , 1400 , 200)]
__lowerCAmelCase : Dict = ["longest", "max_length", "do_not_pad"]
__lowerCAmelCase : List[Any] = [None, 16, None]
for max_length, padding in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE):
__lowerCAmelCase : List[str] = feature_extractor(
_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , return_tensors="np" , return_attention_mask=_SCREAMING_SNAKE_CASE)
__lowerCAmelCase : List[str] = inputs.input_features
__lowerCAmelCase : Dict = inputs.attention_mask
__lowerCAmelCase : Dict = [np.sum(_SCREAMING_SNAKE_CASE) for x in attention_mask]
self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]])
self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1e-6)
self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]])
self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1e-6)
self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]])
def _SCREAMING_SNAKE_CASE ( self: str) -> Any:
"""simple docstring"""
__lowerCAmelCase : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
__lowerCAmelCase : str = [floats_list((1, x))[0] for x in range(800 , 1400 , 200)]
__lowerCAmelCase : str = feature_extractor(
_SCREAMING_SNAKE_CASE , padding="max_length" , max_length=4 , truncation=_SCREAMING_SNAKE_CASE , return_tensors="np" , return_attention_mask=_SCREAMING_SNAKE_CASE , )
__lowerCAmelCase : List[str] = inputs.input_features
__lowerCAmelCase : Dict = inputs.attention_mask
__lowerCAmelCase : Any = np.sum(attention_mask == 1 , axis=1)
self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]])
self._check_zero_mean_unit_variance(input_features[1])
self._check_zero_mean_unit_variance(input_features[2])
def _SCREAMING_SNAKE_CASE ( self: int) -> List[str]:
"""simple docstring"""
__lowerCAmelCase : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
__lowerCAmelCase : List[Any] = [floats_list((1, x))[0] for x in range(800 , 1400 , 200)]
__lowerCAmelCase : Any = feature_extractor(
_SCREAMING_SNAKE_CASE , padding="longest" , max_length=4 , truncation=_SCREAMING_SNAKE_CASE , return_tensors="np" , return_attention_mask=_SCREAMING_SNAKE_CASE , )
__lowerCAmelCase : List[str] = inputs.input_features
__lowerCAmelCase : Optional[Any] = inputs.attention_mask
__lowerCAmelCase : Optional[Any] = np.sum(attention_mask == 1 , axis=1)
self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]])
self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]])
self._check_zero_mean_unit_variance(input_features[2])
# make sure that if max_length < longest -> then pad to max_length
self.assertEqual(input_features.shape , (3, 4, 24))
__lowerCAmelCase : List[str] = [floats_list((1, x))[0] for x in range(800 , 1400 , 200)]
__lowerCAmelCase : List[str] = feature_extractor(
_SCREAMING_SNAKE_CASE , padding="longest" , max_length=16 , truncation=_SCREAMING_SNAKE_CASE , return_tensors="np" , return_attention_mask=_SCREAMING_SNAKE_CASE , )
__lowerCAmelCase : Optional[Any] = inputs.input_features
__lowerCAmelCase : Optional[int] = inputs.attention_mask
__lowerCAmelCase : str = np.sum(attention_mask == 1 , axis=1)
self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]])
self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]])
self._check_zero_mean_unit_variance(input_features[2])
# make sure that if max_length < longest -> then pad to max_length
self.assertEqual(input_features.shape , (3, 6, 24))
def _SCREAMING_SNAKE_CASE ( self: Any) -> Dict:
"""simple docstring"""
import torch
__lowerCAmelCase : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
__lowerCAmelCase : List[str] = np.random.rand(100 , 32).astype(np.floataa)
__lowerCAmelCase : List[Any] = np_speech_inputs.tolist()
for inputs in [py_speech_inputs, np_speech_inputs]:
__lowerCAmelCase : Any = feature_extractor.pad([{"input_features": inputs}] , return_tensors="np")
self.assertTrue(np_processed.input_features.dtype == np.floataa)
__lowerCAmelCase : List[Any] = feature_extractor.pad([{"input_features": inputs}] , return_tensors="pt")
self.assertTrue(pt_processed.input_features.dtype == torch.floataa)
def _SCREAMING_SNAKE_CASE ( self: str , _SCREAMING_SNAKE_CASE: List[Any]) -> Optional[Any]:
"""simple docstring"""
from datasets import load_dataset
__lowerCAmelCase : Any = load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation")
# automatic decoding with librispeech
__lowerCAmelCase : List[Any] = ds.sort("id").select(range(_SCREAMING_SNAKE_CASE))[:num_samples]["audio"]
return [x["array"] for x in speech_samples]
def _SCREAMING_SNAKE_CASE ( self: List[str]) -> Any:
"""simple docstring"""
__lowerCAmelCase : str = np.array([
-1.5745, -1.7713, -1.7020, -1.6069, -1.2250, -1.1105, -0.9072, -0.8241,
-1.2310, -0.8098, -0.3320, -0.4101, -0.7985, -0.4996, -0.8213, -0.9128,
-1.0420, -1.1286, -1.0440, -0.7999, -0.8405, -1.2275, -1.5443, -1.4625,
])
# fmt: on
__lowerCAmelCase : str = self._load_datasamples(1)
__lowerCAmelCase : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
__lowerCAmelCase : List[str] = feature_extractor(_SCREAMING_SNAKE_CASE , return_tensors="pt").input_features
self.assertEquals(input_features.shape , (1, 584, 24))
self.assertTrue(np.allclose(input_features[0, 0, :30] , _SCREAMING_SNAKE_CASE , atol=1e-4))
| 615 | 1 |
from __future__ import annotations
import unittest
from transformers import is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
if is_tf_available():
import tensorflow as tf
from transformers import AutoTokenizer, TFAutoModelForSeqaSeqLM
@require_tf
@require_sentencepiece
@require_tokenizers
class snake_case_ ( unittest.TestCase ):
'''simple docstring'''
@slow
def __UpperCAmelCase ( self ) -> Tuple:
UpperCAmelCase__ =TFAutoModelForSeqaSeqLM.from_pretrained("google/mt5-small" )
UpperCAmelCase__ =AutoTokenizer.from_pretrained("google/mt5-small" )
UpperCAmelCase__ =tokenizer("Hello there", return_tensors="tf" ).input_ids
UpperCAmelCase__ =tokenizer("Hi I am", return_tensors="tf" ).input_ids
UpperCAmelCase__ =model(A_, labels=A_ ).loss
UpperCAmelCase__ =-tf.math.reduce_mean(A_ ).numpy()
UpperCAmelCase__ =-21.22_81_68
self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 2E-4 )
| 625 |
from typing import List, Optional
import numpy as np
from ...processing_utils import ProcessorMixin
from ...utils import to_numpy
class snake_case_ ( a ):
'''simple docstring'''
__UpperCamelCase = 'EncodecFeatureExtractor'
__UpperCamelCase = ('T5Tokenizer', 'T5TokenizerFast')
def __init__( self, A_, A_ ) -> Optional[int]:
super().__init__(A_, A_ )
UpperCAmelCase__ =self.feature_extractor
UpperCAmelCase__ =False
def __UpperCAmelCase ( self, A_=None, A_=None, A_=True ) -> Union[str, Any]:
return self.tokenizer.get_decoder_prompt_ids(task=A_, language=A_, no_timestamps=A_ )
def __call__( self, *A_, **A_ ) -> Any:
# For backward compatibility
if self._in_target_context_manager:
return self.current_processor(*A_, **A_ )
UpperCAmelCase__ =kwargs.pop("audio", A_ )
UpperCAmelCase__ =kwargs.pop("sampling_rate", A_ )
UpperCAmelCase__ =kwargs.pop("text", A_ )
if len(A_ ) > 0:
UpperCAmelCase__ =args[0]
UpperCAmelCase__ =args[1:]
if audio is None and text is None:
raise ValueError("You need to specify either an `audio` or `text` input to process." )
if text is not None:
UpperCAmelCase__ =self.tokenizer(A_, **A_ )
if audio is not None:
UpperCAmelCase__ =self.feature_extractor(A_, *A_, sampling_rate=A_, **A_ )
if audio is None:
return inputs
elif text is None:
return audio_inputs
else:
UpperCAmelCase__ =audio_inputs["input_values"]
if "padding_mask" in audio_inputs:
UpperCAmelCase__ =audio_inputs["padding_mask"]
return inputs
def __UpperCAmelCase ( self, *A_, **A_ ) -> Dict:
UpperCAmelCase__ =kwargs.pop("audio", A_ )
UpperCAmelCase__ =kwargs.pop("padding_mask", A_ )
if len(A_ ) > 0:
UpperCAmelCase__ =args[0]
UpperCAmelCase__ =args[1:]
if audio_values is not None:
return self._decode_audio(A_, padding_mask=A_ )
else:
return self.tokenizer.batch_decode(*A_, **A_ )
def __UpperCAmelCase ( self, *A_, **A_ ) -> int:
return self.tokenizer.decode(*A_, **A_ )
def __UpperCAmelCase ( self, A_, A_ = None ) -> List[np.ndarray]:
UpperCAmelCase__ =to_numpy(A_ )
UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ =audio_values.shape
if padding_mask is None:
return list(A_ )
UpperCAmelCase__ =to_numpy(A_ )
# match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding**
# token (so that the generated audio values are **not** treated as padded tokens)
UpperCAmelCase__ =seq_len - padding_mask.shape[-1]
UpperCAmelCase__ =1 - self.feature_extractor.padding_value
UpperCAmelCase__ =np.pad(A_, ((0, 0), (0, difference)), "constant", constant_values=A_ )
UpperCAmelCase__ =audio_values.tolist()
for i in range(A_ ):
UpperCAmelCase__ =np.asarray(audio_values[i] )[
padding_mask[i][None, :] != self.feature_extractor.padding_value
]
UpperCAmelCase__ =sliced_audio.reshape(A_, -1 )
return audio_values
| 625 | 1 |
'''simple docstring'''
from typing import List, Optional, Tuple, Union
import torch
from ...models import UNetaDModel
from ...schedulers import ScoreSdeVeScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class _snake_case ( lowerCAmelCase_ ):
"""simple docstring"""
_UpperCamelCase : UNetaDModel
_UpperCamelCase : ScoreSdeVeScheduler
def __init__( self : Union[str, Any] , UpperCamelCase_ : UNetaDModel , UpperCamelCase_ : ScoreSdeVeScheduler ):
super().__init__()
self.register_modules(unet=UpperCamelCase_ , scheduler=UpperCamelCase_ )
@torch.no_grad()
def __call__( self : Union[str, Any] , UpperCamelCase_ : int = 1 , UpperCamelCase_ : int = 2000 , UpperCamelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCamelCase_ : Optional[str] = "pil" , UpperCamelCase_ : bool = True , **UpperCamelCase_ : Dict , ):
lowerCAmelCase_ : Union[str, Any] =self.unet.config.sample_size
lowerCAmelCase_ : Dict =(batch_size, 3, img_size, img_size)
lowerCAmelCase_ : Dict =self.unet
lowerCAmelCase_ : Optional[int] =randn_tensor(UpperCamelCase_ , generator=UpperCamelCase_ ) * self.scheduler.init_noise_sigma
lowerCAmelCase_ : Any =sample.to(self.device )
self.scheduler.set_timesteps(UpperCamelCase_ )
self.scheduler.set_sigmas(UpperCamelCase_ )
for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ):
lowerCAmelCase_ : Optional[Any] =self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device )
# correction step
for _ in range(self.scheduler.config.correct_steps ):
lowerCAmelCase_ : int =self.unet(UpperCamelCase_ , UpperCamelCase_ ).sample
lowerCAmelCase_ : List[str] =self.scheduler.step_correct(UpperCamelCase_ , UpperCamelCase_ , generator=UpperCamelCase_ ).prev_sample
# prediction step
lowerCAmelCase_ : Any =model(UpperCamelCase_ , UpperCamelCase_ ).sample
lowerCAmelCase_ : Tuple =self.scheduler.step_pred(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , generator=UpperCamelCase_ )
lowerCAmelCase_ : Tuple =output.prev_sample, output.prev_sample_mean
lowerCAmelCase_ : Tuple =sample_mean.clamp(0 , 1 )
lowerCAmelCase_ : int =sample.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
lowerCAmelCase_ : Optional[Any] =self.numpy_to_pil(UpperCamelCase_ )
if not return_dict:
return (sample,)
return ImagePipelineOutput(images=UpperCamelCase_ )
| 708 |
'''simple docstring'''
from typing import List, Optional, Tuple, Union
import torch
from ...models import UNetaDModel
from ...schedulers import ScoreSdeVeScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class _snake_case ( lowerCAmelCase_ ):
"""simple docstring"""
_UpperCamelCase : UNetaDModel
_UpperCamelCase : ScoreSdeVeScheduler
def __init__( self : Union[str, Any] , UpperCamelCase_ : UNetaDModel , UpperCamelCase_ : ScoreSdeVeScheduler ):
super().__init__()
self.register_modules(unet=UpperCamelCase_ , scheduler=UpperCamelCase_ )
@torch.no_grad()
def __call__( self : Union[str, Any] , UpperCamelCase_ : int = 1 , UpperCamelCase_ : int = 2000 , UpperCamelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCamelCase_ : Optional[str] = "pil" , UpperCamelCase_ : bool = True , **UpperCamelCase_ : Dict , ):
lowerCAmelCase_ : Union[str, Any] =self.unet.config.sample_size
lowerCAmelCase_ : Dict =(batch_size, 3, img_size, img_size)
lowerCAmelCase_ : Dict =self.unet
lowerCAmelCase_ : Optional[int] =randn_tensor(UpperCamelCase_ , generator=UpperCamelCase_ ) * self.scheduler.init_noise_sigma
lowerCAmelCase_ : Any =sample.to(self.device )
self.scheduler.set_timesteps(UpperCamelCase_ )
self.scheduler.set_sigmas(UpperCamelCase_ )
for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ):
lowerCAmelCase_ : Optional[Any] =self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device )
# correction step
for _ in range(self.scheduler.config.correct_steps ):
lowerCAmelCase_ : int =self.unet(UpperCamelCase_ , UpperCamelCase_ ).sample
lowerCAmelCase_ : List[str] =self.scheduler.step_correct(UpperCamelCase_ , UpperCamelCase_ , generator=UpperCamelCase_ ).prev_sample
# prediction step
lowerCAmelCase_ : Any =model(UpperCamelCase_ , UpperCamelCase_ ).sample
lowerCAmelCase_ : Tuple =self.scheduler.step_pred(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , generator=UpperCamelCase_ )
lowerCAmelCase_ , lowerCAmelCase_ : Tuple =output.prev_sample, output.prev_sample_mean
lowerCAmelCase_ : Tuple =sample_mean.clamp(0 , 1 )
lowerCAmelCase_ : int =sample.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
lowerCAmelCase_ : Optional[Any] =self.numpy_to_pil(UpperCamelCase_ )
if not return_dict:
return (sample,)
return ImagePipelineOutput(images=UpperCamelCase_ )
| 305 | 0 |
import tempfile
import unittest
import numpy as np
import transformers
from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow
from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask
if is_flax_available():
import jax
import jax.numpy as jnp
from transformers.modeling_flax_pytorch_utils import (
convert_pytorch_state_dict_to_flax,
load_flax_weights_in_pytorch_model,
)
from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel
if is_torch_available():
import torch
class lowerCamelCase__ :
"""simple docstring"""
def __init__( self : Optional[int] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any]=14 , __lowerCAmelCase : Union[str, Any]=7 , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : int=True , __lowerCAmelCase : Union[str, Any]=False , __lowerCAmelCase : str=True , __lowerCAmelCase : str=99 , __lowerCAmelCase : List[Any]=32 , __lowerCAmelCase : int=4 , __lowerCAmelCase : Optional[int]=4 , __lowerCAmelCase : Optional[Any]=4 , __lowerCAmelCase : List[Any]=37 , __lowerCAmelCase : int="gelu" , __lowerCAmelCase : List[str]=0.1 , __lowerCAmelCase : Union[str, Any]=0.1 , __lowerCAmelCase : List[Any]=5_12 , __lowerCAmelCase : Dict=0.02 , ) -> int:
_A = parent
_A = batch_size
_A = seq_length
_A = is_training
_A = use_input_mask
_A = use_token_type_ids
_A = use_labels
_A = vocab_size
_A = hidden_size
_A = rotary_dim
_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 = initializer_range
_A = None
_A = vocab_size - 1
_A = vocab_size - 1
_A = vocab_size - 1
def snake_case_ ( self : Optional[Any] ) -> List[str]:
_A = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
_A = None
if self.use_input_mask:
_A = random_attention_mask([self.batch_size, self.seq_length] )
_A = GPTJConfig(
vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=lowerCAmelCase__ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , )
return (config, input_ids, input_mask)
def snake_case_ ( self : List[str] ) -> str:
_A = self.prepare_config_and_inputs()
_A = config_and_inputs
_A = {"""input_ids""": input_ids, """attention_mask""": attention_mask}
return config, inputs_dict
def snake_case_ ( self : Tuple , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : int ) -> Optional[int]:
_A = 20
_A = model_class_name(lowerCAmelCase__ )
_A = model.init_cache(input_ids.shape[0] , lowerCAmelCase__ )
_A = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype='''i4''' )
_A = jnp.broadcast_to(
jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) )
_A = model(
input_ids[:, :-1] , attention_mask=lowerCAmelCase__ , past_key_values=lowerCAmelCase__ , position_ids=lowerCAmelCase__ , )
_A = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='''i4''' )
_A = model(
input_ids[:, -1:] , attention_mask=lowerCAmelCase__ , past_key_values=outputs_cache.past_key_values , position_ids=lowerCAmelCase__ , )
_A = model(lowerCAmelCase__ )
_A = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) )
self.parent.assertTrue(diff < 1E-3 , msg=f'''Max diff is {diff}''' )
def snake_case_ ( self : int , __lowerCAmelCase : str , __lowerCAmelCase : Any , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple ) -> List[Any]:
_A = 20
_A = model_class_name(lowerCAmelCase__ )
_A = jnp.concatenate(
[attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , )
_A = model.init_cache(input_ids.shape[0] , lowerCAmelCase__ )
_A = jnp.broadcast_to(
jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) )
_A = model(
input_ids[:, :-1] , attention_mask=lowerCAmelCase__ , past_key_values=lowerCAmelCase__ , position_ids=lowerCAmelCase__ , )
_A = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='''i4''' )
_A = model(
input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=lowerCAmelCase__ , position_ids=lowerCAmelCase__ , )
_A = model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ )
_A = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) )
self.parent.assertTrue(diff < 1E-3 , msg=f'''Max diff is {diff}''' )
@require_flax
class lowerCamelCase__ ( _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase):
"""simple docstring"""
a__ : List[Any] = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else ()
a__ : List[str] = (FlaxGPTJForCausalLM,) if is_flax_available() else ()
def snake_case_ ( self : int ) -> Union[str, Any]:
_A = FlaxGPTJModelTester(self )
def snake_case_ ( self : Optional[int] ) -> List[str]:
for model_class_name in self.all_model_classes:
_A = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_use_cache_forward(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
def snake_case_ ( self : str ) -> Union[str, Any]:
for model_class_name in self.all_model_classes:
_A = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_use_cache_forward_with_attn_mask(
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
@tooslow
def snake_case_ ( self : Dict ) -> int:
_A = GPTaTokenizer.from_pretrained('''gpt2''' , pad_token='''<|endoftext|>''' , padding_side='''left''' )
_A = tokenizer(['''Hello this is a long string''', '''Hey'''] , return_tensors='''np''' , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ )
_A = FlaxGPTJForCausalLM.from_pretrained('''EleutherAI/gpt-j-6B''' )
_A = False
_A = model.config.eos_token_id
_A = jax.jit(model.generate )
_A = jit_generate(
inputs['''input_ids'''] , attention_mask=inputs['''attention_mask'''] , pad_token_id=tokenizer.pad_token_id ).sequences
_A = tokenizer.batch_decode(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ )
_A = [
"""Hello this is a long string of text.\n\nI'm trying to get the text of the""",
"""Hey, I'm a little late to the party. I'm going to""",
]
self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ )
@is_pt_flax_cross_test
def snake_case_ ( self : int ) -> Optional[int]:
_A = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
with self.subTest(model_class.__name__ ):
# prepare inputs
_A = self._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__ )
_A = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()}
# load corresponding PyTorch class
_A = model_class.__name__[4:] # Skip the "Flax" at the beginning
_A = getattr(lowerCAmelCase__ , lowerCAmelCase__ )
_A = pt_inputs["""input_ids"""].shape
_A = np.random.randint(0 , seq_length - 1 , size=(batch_size,) )
for batch_idx, start_index in enumerate(lowerCAmelCase__ ):
_A = 0
_A = 1
_A = 0
_A = 1
_A = pt_model_class(lowerCAmelCase__ ).eval()
_A = model_class(lowerCAmelCase__ , dtype=jnp.floataa )
_A = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , lowerCAmelCase__ )
_A = fx_state
with torch.no_grad():
_A = pt_model(**lowerCAmelCase__ ).to_tuple()
_A = fx_model(**lowerCAmelCase__ ).to_tuple()
self.assertEqual(len(lowerCAmelCase__ ) , len(lowerCAmelCase__ ) , '''Output lengths differ between Flax and PyTorch''' )
for fx_output, pt_output in zip(lowerCAmelCase__ , lowerCAmelCase__ ):
self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 )
with tempfile.TemporaryDirectory() as tmpdirname:
pt_model.save_pretrained(lowerCAmelCase__ )
_A = model_class.from_pretrained(lowerCAmelCase__ , from_pt=lowerCAmelCase__ )
_A = fx_model_loaded(**lowerCAmelCase__ ).to_tuple()
self.assertEqual(
len(lowerCAmelCase__ ) , len(lowerCAmelCase__ ) , '''Output lengths differ between Flax and PyTorch''' )
for fx_output_loaded, pt_output in zip(lowerCAmelCase__ , lowerCAmelCase__ ):
self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4E-2 )
@is_pt_flax_cross_test
def snake_case_ ( self : Tuple ) -> Tuple:
_A = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
with self.subTest(model_class.__name__ ):
# prepare inputs
_A = self._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__ )
_A = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()}
# load corresponding PyTorch class
_A = model_class.__name__[4:] # Skip the "Flax" at the beginning
_A = getattr(lowerCAmelCase__ , lowerCAmelCase__ )
_A = pt_model_class(lowerCAmelCase__ ).eval()
_A = model_class(lowerCAmelCase__ , dtype=jnp.floataa )
_A = load_flax_weights_in_pytorch_model(lowerCAmelCase__ , fx_model.params )
_A = pt_inputs["""input_ids"""].shape
_A = np.random.randint(0 , seq_length - 1 , size=(batch_size,) )
for batch_idx, start_index in enumerate(lowerCAmelCase__ ):
_A = 0
_A = 1
_A = 0
_A = 1
# make sure weights are tied in PyTorch
pt_model.tie_weights()
with torch.no_grad():
_A = pt_model(**lowerCAmelCase__ ).to_tuple()
_A = fx_model(**lowerCAmelCase__ ).to_tuple()
self.assertEqual(len(lowerCAmelCase__ ) , len(lowerCAmelCase__ ) , '''Output lengths differ between Flax and PyTorch''' )
for fx_output, pt_output in zip(lowerCAmelCase__ , lowerCAmelCase__ ):
self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 )
with tempfile.TemporaryDirectory() as tmpdirname:
fx_model.save_pretrained(lowerCAmelCase__ )
_A = pt_model_class.from_pretrained(lowerCAmelCase__ , from_flax=lowerCAmelCase__ )
with torch.no_grad():
_A = pt_model_loaded(**lowerCAmelCase__ ).to_tuple()
self.assertEqual(
len(lowerCAmelCase__ ) , len(lowerCAmelCase__ ) , '''Output lengths differ between Flax and PyTorch''' )
for fx_output, pt_output in zip(lowerCAmelCase__ , lowerCAmelCase__ ):
self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 )
@tooslow
def snake_case_ ( self : List[Any] ) -> int:
for model_class_name in self.all_model_classes:
_A = model_class_name.from_pretrained('''EleutherAI/gpt-j-6B''' )
_A = model(np.ones((1, 1) ) )
self.assertIsNotNone(lowerCAmelCase__ )
| 2 |
import argparse
import json
import subprocess
def UpperCamelCase ( _A, _A ):
"""simple docstring"""
__magic_name__ : Union[str, Any] = []
__magic_name__ : Optional[int] = (
f'curl -H "Accept: application/vnd.github+json" -H "Authorization: Bearer {token}"'
""" https://api.github.com/repos/huggingface/transformers/actions/runners"""
)
__magic_name__ : Any = subprocess.run(_A, shell=_A, stdout=subprocess.PIPE )
__magic_name__ : int = output.stdout.decode("""utf-8""" )
__magic_name__ : Optional[int] = json.loads(_A )
__magic_name__ : Tuple = status["""runners"""]
for runner in runners:
if runner["name"] in target_runners:
if runner["status"] == "offline":
offline_runners.append(_A )
# save the result so we can report them on Slack
with open("""offline_runners.txt""", """w""" ) as fp:
fp.write(json.dumps(_A ) )
if len(_A ) > 0:
__magic_name__ : Optional[Any] = """\n""".join([x["""name"""] for x in offline_runners] )
raise ValueError(f'The following runners are offline:\n{failed}' )
if __name__ == "__main__":
def UpperCamelCase ( _A ):
"""simple docstring"""
return values.split(""",""" )
__magic_name__: List[str] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--target_runners",
default=None,
type=list_str,
required=True,
help="Comma-separated list of runners to check status.",
)
parser.add_argument(
"--token", default=None, type=str, required=True, help="A token that has actions:read permission."
)
__magic_name__: Dict = parser.parse_args()
get_runner_status(args.target_runners, args.token)
| 324 | 0 |
print((lambda quine: quine % quine)("""print((lambda quine: quine %% quine)(%r))"""))
| 700 |
import argparse
import os
import shutil
import torch
from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer
def UpperCAmelCase ( _snake_case ):
lowerCAmelCase = args.pruning_method
lowerCAmelCase = args.threshold
lowerCAmelCase = args.model_name_or_path.rstrip('''/''' )
lowerCAmelCase = args.target_model_path
print(F"""Load fine-pruned model from {model_name_or_path}""" )
lowerCAmelCase = torch.load(os.path.join(_snake_case , '''pytorch_model.bin''' ) )
lowerCAmelCase = {}
for name, tensor in model.items():
if "embeddings" in name or "LayerNorm" in name or "pooler" in name:
lowerCAmelCase = tensor
print(F"""Copied layer {name}""" )
elif "classifier" in name or "qa_output" in name:
lowerCAmelCase = tensor
print(F"""Copied layer {name}""" )
elif "bias" in name:
lowerCAmelCase = tensor
print(F"""Copied layer {name}""" )
else:
if pruning_method == "magnitude":
lowerCAmelCase = MagnitudeBinarizer.apply(inputs=_snake_case , threshold=_snake_case )
lowerCAmelCase = tensor * mask
print(F"""Pruned layer {name}""" )
elif pruning_method == "topK":
if "mask_scores" in name:
continue
lowerCAmelCase = name[:-6]
lowerCAmelCase = model[F"""{prefix_}mask_scores"""]
lowerCAmelCase = TopKBinarizer.apply(_snake_case , _snake_case )
lowerCAmelCase = tensor * mask
print(F"""Pruned layer {name}""" )
elif pruning_method == "sigmoied_threshold":
if "mask_scores" in name:
continue
lowerCAmelCase = name[:-6]
lowerCAmelCase = model[F"""{prefix_}mask_scores"""]
lowerCAmelCase = ThresholdBinarizer.apply(_snake_case , _snake_case , _snake_case )
lowerCAmelCase = tensor * mask
print(F"""Pruned layer {name}""" )
elif pruning_method == "l0":
if "mask_scores" in name:
continue
lowerCAmelCase = name[:-6]
lowerCAmelCase = model[F"""{prefix_}mask_scores"""]
lowerCAmelCase , lowerCAmelCase = -0.1, 1.1
lowerCAmelCase = torch.sigmoid(_snake_case )
lowerCAmelCase = s * (r - l) + l
lowerCAmelCase = s_bar.clamp(min=0.0 , max=1.0 )
lowerCAmelCase = tensor * mask
print(F"""Pruned layer {name}""" )
else:
raise ValueError('''Unknown pruning method''' )
if target_model_path is None:
lowerCAmelCase = os.path.join(
os.path.dirname(_snake_case ) , F"""bertarized_{os.path.basename(_snake_case )}""" )
if not os.path.isdir(_snake_case ):
shutil.copytree(_snake_case , _snake_case )
print(F"""\nCreated folder {target_model_path}""" )
torch.save(_snake_case , os.path.join(_snake_case , '''pytorch_model.bin''' ) )
print('''\nPruned model saved! See you later!''' )
if __name__ == "__main__":
UpperCAmelCase_ =argparse.ArgumentParser()
parser.add_argument(
"""--pruning_method""",
choices=["""l0""", """magnitude""", """topK""", """sigmoied_threshold"""],
type=str,
required=True,
help=(
"""Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning,"""
""" sigmoied_threshold = Soft movement pruning)"""
),
)
parser.add_argument(
"""--threshold""",
type=float,
required=False,
help=(
"""For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model."""
"""For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared."""
"""Not needed for `l0`"""
),
)
parser.add_argument(
"""--model_name_or_path""",
type=str,
required=True,
help="""Folder containing the model that was previously fine-pruned""",
)
parser.add_argument(
"""--target_model_path""",
default=None,
type=str,
required=False,
help="""Folder containing the model that was previously fine-pruned""",
)
UpperCAmelCase_ =parser.parse_args()
main(args)
| 33 | 0 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_sentencepiece_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
if is_sentencepiece_available():
from ..ta.tokenization_ta import TaTokenizer
else:
from ...utils.dummy_sentencepiece_objects import TaTokenizer
_UpperCamelCase = TaTokenizer
if is_tokenizers_available():
from ..ta.tokenization_ta_fast import TaTokenizerFast
else:
from ...utils.dummy_tokenizers_objects import TaTokenizerFast
_UpperCamelCase = TaTokenizerFast
_UpperCamelCase = {"""configuration_mt5""": ["""MT5Config""", """MT5OnnxConfig"""]}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCamelCase = [
"""MT5EncoderModel""",
"""MT5ForConditionalGeneration""",
"""MT5ForQuestionAnswering""",
"""MT5Model""",
"""MT5PreTrainedModel""",
"""MT5Stack""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCamelCase = ["""TFMT5EncoderModel""", """TFMT5ForConditionalGeneration""", """TFMT5Model"""]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCamelCase = ["""FlaxMT5EncoderModel""", """FlaxMT5ForConditionalGeneration""", """FlaxMT5Model"""]
if TYPE_CHECKING:
from .configuration_mta import MTaConfig, MTaOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mta import (
MTaEncoderModel,
MTaForConditionalGeneration,
MTaForQuestionAnswering,
MTaModel,
MTaPreTrainedModel,
MTaStack,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_mta import TFMTaEncoderModel, TFMTaForConditionalGeneration, TFMTaModel
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_mta import FlaxMTaEncoderModel, FlaxMTaForConditionalGeneration, FlaxMTaModel
else:
import sys
_UpperCamelCase = _LazyModule(
__name__,
globals()['__file__'],
_import_structure,
extra_objects={'MT5Tokenizer': MTaTokenizer, 'MT5TokenizerFast': MTaTokenizerFast},
module_spec=__spec__,
)
| 459 |
import numpy as np
def a_ ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ):
lowerCAmelCase__ = int(np.ceil((x_end - xa) / h ) )
lowerCAmelCase__ = np.zeros((n + 1,) )
lowerCAmelCase__ = ya
lowerCAmelCase__ = xa
for k in range(__lowerCAmelCase ):
lowerCAmelCase__ = f(__lowerCAmelCase , y[k] )
lowerCAmelCase__ = f(x + 0.5 * h , y[k] + 0.5 * h * ka )
lowerCAmelCase__ = f(x + 0.5 * h , y[k] + 0.5 * h * ka )
lowerCAmelCase__ = f(x + h , y[k] + h * ka )
lowerCAmelCase__ = y[k] + (1 / 6) * h * (ka + 2 * ka + 2 * ka + ka)
x += h
return y
if __name__ == "__main__":
import doctest
doctest.testmod()
| 615 | 0 |
import os
import unittest
from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer
from ...test_tokenization_common import TokenizerTesterMixin
class _lowerCAmelCase ( __a , unittest.TestCase ):
_lowercase =PhobertTokenizer
_lowercase =False
def __a ( self ) -> List[Any]:
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
lowerCAmelCase_ = ["T@@", "i", "I", "R@@", "r", "e@@"]
lowerCAmelCase_ = dict(zip(_UpperCamelCase , range(len(_UpperCamelCase ) ) ) )
lowerCAmelCase_ = ["#version: 0.2", "l à</w>"]
lowerCAmelCase_ = {"unk_token": "<unk>"}
lowerCAmelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
lowerCAmelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] )
with open(self.vocab_file , "w" , encoding="utf-8" ) as fp:
for token in vocab_tokens:
fp.write(f"""{token} {vocab_tokens[token]}\n""" )
with open(self.merges_file , "w" , encoding="utf-8" ) as fp:
fp.write("\n".join(_UpperCamelCase ) )
def __a ( self , **_UpperCamelCase ) -> str:
kwargs.update(self.special_tokens_map )
return PhobertTokenizer.from_pretrained(self.tmpdirname , **_UpperCamelCase )
def __a ( self , _UpperCamelCase ) -> List[Any]:
lowerCAmelCase_ = "Tôi là VinAI Research"
lowerCAmelCase_ = "T<unk> i <unk> <unk> <unk> <unk> <unk> <unk> I Re<unk> e<unk> <unk> <unk> <unk>"
return input_text, output_text
def __a ( self ) -> Any:
lowerCAmelCase_ = PhobertTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map )
lowerCAmelCase_ = "Tôi là VinAI Research"
lowerCAmelCase_ = "T@@ ô@@ i l@@ à V@@ i@@ n@@ A@@ I R@@ e@@ s@@ e@@ a@@ r@@ c@@ h".split()
lowerCAmelCase_ = tokenizer.tokenize(_UpperCamelCase )
print(_UpperCamelCase )
self.assertListEqual(_UpperCamelCase , _UpperCamelCase )
lowerCAmelCase_ = tokens + [tokenizer.unk_token]
lowerCAmelCase_ = [4, 3, 5, 3, 3, 3, 3, 3, 3, 6, 7, 9, 3, 9, 3, 3, 3, 3, 3]
self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCamelCase ) , _UpperCamelCase )
| 279 |
import json
import multiprocessing as mp
import re
from collections import defaultdict
from functools import partial
from typing import Dict, List, Optional, Set, Tuple, Type
from datasets import Dataset
from datasketch import MinHash, MinHashLSH
from dpu_utils.utils.iterators import ThreadedIterator
from tqdm import tqdm
_A = re.compile("[^A-Za-z_0-9]")
# parameters used in DuplicationIndex
_A = 10
_A = 2_56
def lowerCamelCase__ ( __lowerCAmelCase : List[str] ):
"""simple docstring"""
if len(__lowerCAmelCase ) < MIN_NUM_TOKENS:
return None
lowerCAmelCase_ = MinHash(num_perm=__lowerCAmelCase )
for token in set(__lowerCAmelCase ):
min_hash.update(token.encode() )
return min_hash
def lowerCamelCase__ ( __lowerCAmelCase : str ):
"""simple docstring"""
return {t for t in NON_ALPHA.split(__lowerCAmelCase ) if len(t.strip() ) > 0}
class _lowerCAmelCase :
def __init__( self , *,
_UpperCamelCase = 0.85 , ) -> Dict:
lowerCAmelCase_ = duplication_jaccard_threshold
lowerCAmelCase_ = NUM_PERM
lowerCAmelCase_ = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm )
lowerCAmelCase_ = defaultdict(_UpperCamelCase )
def __a ( self , _UpperCamelCase , _UpperCamelCase ) -> None:
lowerCAmelCase_ = self._index.query(_UpperCamelCase )
if code_key in self._index.keys:
print(f"""Duplicate key {code_key}""" )
return
self._index.insert(_UpperCamelCase , _UpperCamelCase )
if len(_UpperCamelCase ) > 0:
for base_duplicate in close_duplicates:
if base_duplicate in self._duplicate_clusters:
self._duplicate_clusters[base_duplicate].add(_UpperCamelCase )
break
else:
self._duplicate_clusters[close_duplicates[0]].add(_UpperCamelCase )
def __a ( self ) -> List[List[Dict]]:
lowerCAmelCase_ = []
for base, duplicates in self._duplicate_clusters.items():
lowerCAmelCase_ = [base] + list(_UpperCamelCase )
# reformat the cluster to be a list of dict
lowerCAmelCase_ = [{"base_index": el[0], "repo_name": el[1], "path": el[2]} for el in cluster]
duplicate_clusters.append(_UpperCamelCase )
return duplicate_clusters
def __a ( self , _UpperCamelCase ) -> None:
lowerCAmelCase_ = self.get_duplicate_clusters()
with open(_UpperCamelCase , "w" ) as f:
json.dump(_UpperCamelCase , _UpperCamelCase )
def lowerCamelCase__ ( __lowerCAmelCase : Tuple ):
"""simple docstring"""
lowerCAmelCase_ , lowerCAmelCase_ = element
lowerCAmelCase_ = get_min_hash([t for t in NON_ALPHA.split(data["content"] ) if len(t.strip() ) > 0] )
if min_hash is not None:
return (index, data["repo_name"], data["path"]), min_hash
def lowerCamelCase__ ( __lowerCAmelCase : Type[Dataset] ):
"""simple docstring"""
with mp.Pool() as pool:
for data in pool.imap_unordered(
_compute_min_hash , ThreadedIterator(__lowerCAmelCase , max_queue_size=10000 ) , chunksize=100 , ):
if data is not None:
yield data
def lowerCamelCase__ ( __lowerCAmelCase : Type[Dataset] , __lowerCAmelCase : float ):
"""simple docstring"""
lowerCAmelCase_ = DuplicationIndex(duplication_jaccard_threshold=__lowerCAmelCase )
for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(__lowerCAmelCase ) ) , max_queue_size=100 ) ):
di.add(__lowerCAmelCase , __lowerCAmelCase )
# Returns a List[Cluster] where Cluster is List[str] with the filenames.
return di.get_duplicate_clusters()
def lowerCamelCase__ ( __lowerCAmelCase : str , __lowerCAmelCase : str ):
"""simple docstring"""
lowerCAmelCase_ = get_tokens(__lowerCAmelCase )
lowerCAmelCase_ = get_tokens(__lowerCAmelCase )
return len(tokensa & tokensa ) / len(tokensa | tokensa )
_A = None
def lowerCamelCase__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : int ):
"""simple docstring"""
lowerCAmelCase_ = []
for elementa in cluster:
lowerCAmelCase_ = _shared_dataset[elementa["base_index"]]["content"]
for elementa in extremes:
lowerCAmelCase_ = _shared_dataset[elementa["base_index"]]["content"]
if jaccard_similarity(__lowerCAmelCase , __lowerCAmelCase ) >= jaccard_threshold:
elementa["copies"] += 1
break
else:
lowerCAmelCase_ = 1
extremes.append(__lowerCAmelCase )
return extremes
def lowerCamelCase__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : List[str] , __lowerCAmelCase : Union[str, Any] ):
"""simple docstring"""
global _shared_dataset
lowerCAmelCase_ = dataset
lowerCAmelCase_ = []
lowerCAmelCase_ = partial(_find_cluster_extremes_shared , jaccard_threshold=__lowerCAmelCase )
with mp.Pool() as pool:
for extremes in tqdm(
pool.imap_unordered(
__lowerCAmelCase , __lowerCAmelCase , ) , total=len(__lowerCAmelCase ) , ):
extremes_list.append(__lowerCAmelCase )
return extremes_list
def lowerCamelCase__ ( __lowerCAmelCase : Type[Dataset] , __lowerCAmelCase : float = 0.85 ):
"""simple docstring"""
lowerCAmelCase_ = make_duplicate_clusters(__lowerCAmelCase , __lowerCAmelCase )
lowerCAmelCase_ = {x["base_index"] for cluster in duplicate_clusters for x in cluster}
lowerCAmelCase_ = {}
lowerCAmelCase_ = find_extremes(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
for extremes in extremes_clusters:
for element in extremes:
lowerCAmelCase_ = element
lowerCAmelCase_ = duplicate_indices - set(extreme_dict.keys() )
lowerCAmelCase_ = dataset.filter(lambda __lowerCAmelCase , __lowerCAmelCase : idx not in remove_indices , with_indices=__lowerCAmelCase )
# update duplicate_clusters
for cluster in duplicate_clusters:
for element in cluster:
lowerCAmelCase_ = element["base_index"] in extreme_dict
if element["is_extreme"]:
lowerCAmelCase_ = extreme_dict[element["base_index"]]["copies"]
print(F"""Original dataset size: {len(__lowerCAmelCase )}""" )
print(F"""Number of duplicate clusters: {len(__lowerCAmelCase )}""" )
print(F"""Files in duplicate cluster: {len(__lowerCAmelCase )}""" )
print(F"""Unique files in duplicate cluster: {len(__lowerCAmelCase )}""" )
print(F"""Filtered dataset size: {len(__lowerCAmelCase )}""" )
return ds_filter, duplicate_clusters
| 279 | 1 |
def snake_case ( lowerCamelCase ):
'''simple docstring'''
for i in range(len(lowerCamelCase ) - 1 , 0 , -1 ):
__lowercase = False
for j in range(lowerCamelCase , 0 , -1 ):
if unsorted[j] < unsorted[j - 1]:
__lowercase , __lowercase = unsorted[j - 1], unsorted[j]
__lowercase = True
for j in range(lowerCamelCase ):
if unsorted[j] > unsorted[j + 1]:
__lowercase , __lowercase = unsorted[j + 1], unsorted[j]
__lowercase = True
if not swapped:
break
return unsorted
if __name__ == "__main__":
import doctest
doctest.testmod()
__UpperCamelCase : List[Any] = input("""Enter numbers separated by a comma:\n""").strip()
__UpperCamelCase : int = [int(item) for item in user_input.split(""",""")]
print(F'''{cocktail_shaker_sort(unsorted) = }''')
| 80 |
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 4000000 ) -> int:
_a : Optional[Any] =[]
_a , _a : Union[str, Any] =0, 1
while b <= n:
if b % 2 == 0:
even_fibs.append(_UpperCAmelCase )
_a , _a : Optional[Any] =b, a + b
return sum(_UpperCAmelCase )
if __name__ == "__main__":
print(F"{solution() = }")
| 694 | 0 |
'''simple docstring'''
import numpy as np
def __lowercase ( __SCREAMING_SNAKE_CASE ) -> np.ndarray:
"""simple docstring"""
return 1 / (1 + np.exp(-vector ))
def __lowercase ( __SCREAMING_SNAKE_CASE ) -> np.ndarray:
"""simple docstring"""
return vector * sigmoid(SCREAMING_SNAKE_CASE_ )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 702 |
'''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
SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE_ = {'vocab_file': 'sentencepiece.model'}
SCREAMING_SNAKE_CASE_ = {
'vocab_file': {
'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model',
},
}
SCREAMING_SNAKE_CASE_ = {
'google/rembert': 2_56,
}
class lowerCAmelCase_ ( snake_case__ ):
"""simple docstring"""
a_ :Tuple =VOCAB_FILES_NAMES
a_ :Tuple =PRETRAINED_VOCAB_FILES_MAP
a_ :Optional[int] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple=False , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : int="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Optional[Any]="[UNK]" , SCREAMING_SNAKE_CASE__ : Any="[SEP]" , SCREAMING_SNAKE_CASE__ : Dict="[PAD]" , SCREAMING_SNAKE_CASE__ : Dict="[CLS]" , SCREAMING_SNAKE_CASE__ : Dict="[MASK]" , **SCREAMING_SNAKE_CASE__ : List[str] , ):
'''simple docstring'''
super().__init__(
do_lower_case=SCREAMING_SNAKE_CASE__ , remove_space=SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
__a = do_lower_case
__a = remove_space
__a = keep_accents
__a = vocab_file
__a = spm.SentencePieceProcessor()
self.sp_model.Load(SCREAMING_SNAKE_CASE__ )
@property
def __a ( self : List[str] ):
'''simple docstring'''
return len(self.sp_model )
def __a ( self : str ):
'''simple docstring'''
__a = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self : List[Any] ):
'''simple docstring'''
__a = self.__dict__.copy()
__a = None
return state
def __setstate__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] ):
'''simple docstring'''
__a = d
__a = spm.SentencePieceProcessor()
self.sp_model.Load(self.vocab_file )
def __a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str]=False ):
'''simple docstring'''
__a = self.sp_model.EncodeAsPieces(SCREAMING_SNAKE_CASE__ )
return pieces
def __a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int ):
'''simple docstring'''
return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ )
def __a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ):
'''simple docstring'''
return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ )
def __a ( self : List[str] , SCREAMING_SNAKE_CASE__ : str ):
'''simple docstring'''
__a = self.sp_model.decode_pieces(SCREAMING_SNAKE_CASE__ )
return out_string
def __a ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ):
'''simple docstring'''
__a = [self.sep_token_id]
__a = [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 : Any , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : 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(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1]
return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1]
def __a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ):
'''simple docstring'''
__a = [self.sep_token_id]
__a = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def __a ( self : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ):
'''simple docstring'''
if not os.path.isdir(SCREAMING_SNAKE_CASE__ ):
logger.error("""Vocabulary path ({}) should be a directory""".format(SCREAMING_SNAKE_CASE__ ) )
return
__a = os.path.join(
SCREAMING_SNAKE_CASE__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ):
copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ )
return (out_vocab_file,)
| 201 | 0 |
"""simple docstring"""
import gc
import random
import tempfile
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import require_torch_gpu
class _lowerCAmelCase ( unittest.TestCase ):
def A ( self ) -> Dict:
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
@property
def A ( self ) -> int:
_SCREAMING_SNAKE_CASE : Any = 1
_SCREAMING_SNAKE_CASE : str = 3
_SCREAMING_SNAKE_CASE : Optional[int] = (3_2, 3_2)
_SCREAMING_SNAKE_CASE : Optional[Any] = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(lowerCAmelCase_ )
return image
@property
def A ( self ) -> Optional[int]:
torch.manual_seed(0 )
_SCREAMING_SNAKE_CASE : List[Any] = UNetaDConditionModel(
block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=3_2 , )
return model
@property
def A ( self ) -> List[Any]:
torch.manual_seed(0 )
_SCREAMING_SNAKE_CASE : List[Any] = AutoencoderKL(
block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , )
return model
@property
def A ( self ) -> Any:
torch.manual_seed(0 )
_SCREAMING_SNAKE_CASE : str = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , )
return CLIPTextModel(lowerCAmelCase_ )
@property
def A ( self ) -> Any:
def extract(*lowerCAmelCase_ , **lowerCAmelCase_ ):
class _lowerCAmelCase :
def __init__( self ) -> Any:
_SCREAMING_SNAKE_CASE : Union[str, Any] = torch.ones([0] )
def A ( self , lowerCAmelCase_ ) -> int:
self.pixel_values.to(lowerCAmelCase_ )
return self
return Out()
return extract
def A ( self ) -> Union[str, Any]:
_SCREAMING_SNAKE_CASE : Dict = 'cpu' # ensure determinism for the device-dependent torch.Generator
_SCREAMING_SNAKE_CASE : str = self.dummy_cond_unet
_SCREAMING_SNAKE_CASE : Dict = DDIMScheduler(
beta_start=0.00_085 , beta_end=0.012 , beta_schedule='scaled_linear' , clip_sample=lowerCAmelCase_ , set_alpha_to_one=lowerCAmelCase_ , )
_SCREAMING_SNAKE_CASE : Optional[Any] = self.dummy_vae
_SCREAMING_SNAKE_CASE : Tuple = self.dummy_text_encoder
_SCREAMING_SNAKE_CASE : Any = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )
# make sure here that pndm scheduler skips prk
_SCREAMING_SNAKE_CASE : Optional[Any] = StableDiffusionPipeline(
unet=lowerCAmelCase_ , scheduler=lowerCAmelCase_ , vae=lowerCAmelCase_ , text_encoder=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ , safety_checker=lowerCAmelCase_ , feature_extractor=self.dummy_extractor , )
_SCREAMING_SNAKE_CASE : Optional[int] = sd_pipe.to(lowerCAmelCase_ )
sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Union[str, Any] = 'A painting of a squirrel eating a burger'
_SCREAMING_SNAKE_CASE : List[str] = torch.Generator(device=lowerCAmelCase_ ).manual_seed(0 )
_SCREAMING_SNAKE_CASE : Union[str, Any] = sd_pipe([prompt] , generator=lowerCAmelCase_ , guidance_scale=6.0 , num_inference_steps=2 , output_type='np' )
_SCREAMING_SNAKE_CASE : List[Any] = output.images
_SCREAMING_SNAKE_CASE : List[Any] = torch.Generator(device=lowerCAmelCase_ ).manual_seed(0 )
_SCREAMING_SNAKE_CASE : Any = sd_pipe(
[prompt] , generator=lowerCAmelCase_ , guidance_scale=6.0 , num_inference_steps=2 , output_type='np' , return_dict=lowerCAmelCase_ , )[0]
_SCREAMING_SNAKE_CASE : List[Any] = image[0, -3:, -3:, -1]
_SCREAMING_SNAKE_CASE : Tuple = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 6_4, 6_4, 3)
_SCREAMING_SNAKE_CASE : str = np.array([0.5_756, 0.6_118, 0.5_005, 0.5_041, 0.5_471, 0.4_726, 0.4_976, 0.4_865, 0.4_864] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
def A ( self ) -> Union[str, Any]:
_SCREAMING_SNAKE_CASE : List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator
_SCREAMING_SNAKE_CASE : int = self.dummy_cond_unet
_SCREAMING_SNAKE_CASE : str = PNDMScheduler(skip_prk_steps=lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Dict = self.dummy_vae
_SCREAMING_SNAKE_CASE : Optional[Any] = self.dummy_text_encoder
_SCREAMING_SNAKE_CASE : Optional[int] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )
# make sure here that pndm scheduler skips prk
_SCREAMING_SNAKE_CASE : List[Any] = StableDiffusionPipeline(
unet=lowerCAmelCase_ , scheduler=lowerCAmelCase_ , vae=lowerCAmelCase_ , text_encoder=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ , safety_checker=lowerCAmelCase_ , feature_extractor=self.dummy_extractor , )
_SCREAMING_SNAKE_CASE : str = sd_pipe.to(lowerCAmelCase_ )
sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : List[str] = 'A painting of a squirrel eating a burger'
_SCREAMING_SNAKE_CASE : List[str] = torch.Generator(device=lowerCAmelCase_ ).manual_seed(0 )
_SCREAMING_SNAKE_CASE : str = sd_pipe([prompt] , generator=lowerCAmelCase_ , guidance_scale=6.0 , num_inference_steps=2 , output_type='np' )
_SCREAMING_SNAKE_CASE : Any = output.images
_SCREAMING_SNAKE_CASE : Any = torch.Generator(device=lowerCAmelCase_ ).manual_seed(0 )
_SCREAMING_SNAKE_CASE : Any = sd_pipe(
[prompt] , generator=lowerCAmelCase_ , guidance_scale=6.0 , num_inference_steps=2 , output_type='np' , return_dict=lowerCAmelCase_ , )[0]
_SCREAMING_SNAKE_CASE : int = image[0, -3:, -3:, -1]
_SCREAMING_SNAKE_CASE : str = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 6_4, 6_4, 3)
_SCREAMING_SNAKE_CASE : Dict = np.array([0.5_125, 0.5_716, 0.4_828, 0.5_060, 0.5_650, 0.4_768, 0.5_185, 0.4_895, 0.4_993] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
def A ( self ) -> int:
_SCREAMING_SNAKE_CASE : List[Any] = StableDiffusionPipeline.from_pretrained(
'hf-internal-testing/tiny-stable-diffusion-lms-pipe' , safety_checker=lowerCAmelCase_ )
assert isinstance(lowerCAmelCase_ , lowerCAmelCase_ )
assert isinstance(pipe.scheduler , lowerCAmelCase_ )
assert pipe.safety_checker is None
_SCREAMING_SNAKE_CASE : Optional[Any] = pipe('example prompt' , num_inference_steps=2 ).images[0]
assert image is not None
# check that there's no error when saving a pipeline with one of the models being None
with tempfile.TemporaryDirectory() as tmpdirname:
pipe.save_pretrained(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Optional[int] = StableDiffusionPipeline.from_pretrained(lowerCAmelCase_ )
# sanity check that the pipeline still works
assert pipe.safety_checker is None
_SCREAMING_SNAKE_CASE : Optional[Any] = pipe('example prompt' , num_inference_steps=2 ).images[0]
assert image is not None
@unittest.skipIf(torch_device != 'cuda' , 'This test requires a GPU' )
def A ( self ) -> int:
_SCREAMING_SNAKE_CASE : Any = self.dummy_cond_unet
_SCREAMING_SNAKE_CASE : List[str] = PNDMScheduler(skip_prk_steps=lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : str = self.dummy_vae
_SCREAMING_SNAKE_CASE : Tuple = self.dummy_text_encoder
_SCREAMING_SNAKE_CASE : Any = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )
# put models in fp16
_SCREAMING_SNAKE_CASE : Optional[int] = unet.half()
_SCREAMING_SNAKE_CASE : List[str] = vae.half()
_SCREAMING_SNAKE_CASE : List[str] = bert.half()
# make sure here that pndm scheduler skips prk
_SCREAMING_SNAKE_CASE : Optional[Any] = StableDiffusionPipeline(
unet=lowerCAmelCase_ , scheduler=lowerCAmelCase_ , vae=lowerCAmelCase_ , text_encoder=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ , safety_checker=lowerCAmelCase_ , feature_extractor=self.dummy_extractor , )
_SCREAMING_SNAKE_CASE : Any = sd_pipe.to(lowerCAmelCase_ )
sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Union[str, Any] = 'A painting of a squirrel eating a burger'
_SCREAMING_SNAKE_CASE : Union[str, Any] = sd_pipe([prompt] , num_inference_steps=2 , output_type='np' ).images
assert image.shape == (1, 6_4, 6_4, 3)
@nightly
@require_torch_gpu
class _lowerCAmelCase ( unittest.TestCase ):
def A ( self ) -> List[Any]:
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def A ( self ) -> List[str]:
_SCREAMING_SNAKE_CASE : Optional[Any] = StableDiffusionPipeline.from_pretrained('runwayml/stable-diffusion-v1-5' , safety_checker=lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Tuple = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config )
_SCREAMING_SNAKE_CASE : List[str] = sd_pipe.to(lowerCAmelCase_ )
sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Optional[Any] = (
'portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle'
' coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with'
' anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and'
' children from bahnhof zoo, detailed '
)
_SCREAMING_SNAKE_CASE : List[Any] = 4_0_0_3_6_6_0_3_4_6
_SCREAMING_SNAKE_CASE : List[Any] = 7
# without safety guidance (sld_guidance_scale = 0)
_SCREAMING_SNAKE_CASE : str = torch.manual_seed(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Union[str, Any] = sd_pipe(
[prompt] , generator=lowerCAmelCase_ , guidance_scale=lowerCAmelCase_ , num_inference_steps=5_0 , output_type='np' , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , )
_SCREAMING_SNAKE_CASE : Union[str, Any] = output.images
_SCREAMING_SNAKE_CASE : List[str] = image[0, -3:, -3:, -1]
_SCREAMING_SNAKE_CASE : str = [0.2_278, 0.2_231, 0.2_249, 0.2_333, 0.2_303, 0.1_885, 0.2_273, 0.2_144, 0.2_176]
assert image.shape == (1, 5_1_2, 5_1_2, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
# without safety guidance (strong configuration)
_SCREAMING_SNAKE_CASE : Tuple = torch.manual_seed(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : List[str] = sd_pipe(
[prompt] , generator=lowerCAmelCase_ , guidance_scale=lowerCAmelCase_ , num_inference_steps=5_0 , output_type='np' , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , )
_SCREAMING_SNAKE_CASE : List[str] = output.images
_SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1]
_SCREAMING_SNAKE_CASE : Union[str, Any] = [0.2_383, 0.2_276, 0.236, 0.2_192, 0.2_186, 0.2_053, 0.1_971, 0.1_901, 0.1_719]
assert image.shape == (1, 5_1_2, 5_1_2, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def A ( self ) -> Optional[int]:
_SCREAMING_SNAKE_CASE : Dict = StableDiffusionPipeline.from_pretrained('runwayml/stable-diffusion-v1-5' , safety_checker=lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Optional[Any] = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config )
_SCREAMING_SNAKE_CASE : Optional[Any] = sd_pipe.to(lowerCAmelCase_ )
sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : int = 'padme amidala taking a bath artwork, safe for work, no nudity'
_SCREAMING_SNAKE_CASE : str = 2_7_3_4_9_7_1_7_5_5
_SCREAMING_SNAKE_CASE : Dict = 7
_SCREAMING_SNAKE_CASE : List[str] = torch.manual_seed(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Tuple = sd_pipe(
[prompt] , generator=lowerCAmelCase_ , guidance_scale=lowerCAmelCase_ , num_inference_steps=5_0 , output_type='np' , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , )
_SCREAMING_SNAKE_CASE : str = output.images
_SCREAMING_SNAKE_CASE : int = image[0, -3:, -3:, -1]
_SCREAMING_SNAKE_CASE : Union[str, Any] = [0.3_502, 0.3_622, 0.3_396, 0.3_642, 0.3_478, 0.3_318, 0.35, 0.3_348, 0.3_297]
assert image.shape == (1, 5_1_2, 5_1_2, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
_SCREAMING_SNAKE_CASE : Optional[Any] = torch.manual_seed(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Any = sd_pipe(
[prompt] , generator=lowerCAmelCase_ , guidance_scale=lowerCAmelCase_ , num_inference_steps=5_0 , output_type='np' , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , )
_SCREAMING_SNAKE_CASE : Optional[Any] = output.images
_SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1]
_SCREAMING_SNAKE_CASE : Optional[Any] = [0.5_531, 0.5_206, 0.4_895, 0.5_156, 0.5_182, 0.4_751, 0.4_802, 0.4_803, 0.4_443]
assert image.shape == (1, 5_1_2, 5_1_2, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def A ( self ) -> List[str]:
_SCREAMING_SNAKE_CASE : Optional[Any] = StableDiffusionPipeline.from_pretrained('runwayml/stable-diffusion-v1-5' )
_SCREAMING_SNAKE_CASE : List[Any] = sd_pipe.to(lowerCAmelCase_ )
sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : List[Any] = (
'the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.'
' leyendecker'
)
_SCREAMING_SNAKE_CASE : List[Any] = 1_0_4_4_3_5_5_2_3_4
_SCREAMING_SNAKE_CASE : Optional[int] = 1_2
_SCREAMING_SNAKE_CASE : int = torch.manual_seed(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Optional[Any] = sd_pipe(
[prompt] , generator=lowerCAmelCase_ , guidance_scale=lowerCAmelCase_ , num_inference_steps=5_0 , output_type='np' , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , )
_SCREAMING_SNAKE_CASE : Dict = output.images
_SCREAMING_SNAKE_CASE : Union[str, Any] = image[0, -3:, -3:, -1]
_SCREAMING_SNAKE_CASE : str = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] )
assert image.shape == (1, 5_1_2, 5_1_2, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-7
_SCREAMING_SNAKE_CASE : Any = torch.manual_seed(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : List[Any] = sd_pipe(
[prompt] , generator=lowerCAmelCase_ , guidance_scale=lowerCAmelCase_ , num_inference_steps=5_0 , output_type='np' , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , )
_SCREAMING_SNAKE_CASE : List[str] = output.images
_SCREAMING_SNAKE_CASE : int = image[0, -3:, -3:, -1]
_SCREAMING_SNAKE_CASE : Optional[int] = np.array([0.5_818, 0.6_285, 0.6_835, 0.6_019, 0.625, 0.6_754, 0.6_096, 0.6_334, 0.6_561] )
assert image.shape == (1, 5_1_2, 5_1_2, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
| 621 |
"""simple docstring"""
import gc
import unittest
from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline
from diffusers.utils import is_flax_available, slow
from diffusers.utils.testing_utils import require_flax
if is_flax_available():
import jax
import jax.numpy as jnp
from flax.jax_utils import replicate
from flax.training.common_utils import shard
@slow
@require_flax
class _lowerCAmelCase ( unittest.TestCase ):
def A ( self ) -> Any:
# clean up the VRAM after each test
super().tearDown()
gc.collect()
def A ( self ) -> int:
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = FlaxStableDiffusionPipeline.from_pretrained(
'stabilityai/stable-diffusion-2' , revision='bf16' , dtype=jnp.bfloataa , )
_SCREAMING_SNAKE_CASE : Union[str, Any] = 'A painting of a squirrel eating a burger'
_SCREAMING_SNAKE_CASE : Optional[Any] = jax.device_count()
_SCREAMING_SNAKE_CASE : List[Any] = num_samples * [prompt]
_SCREAMING_SNAKE_CASE : Any = sd_pipe.prepare_inputs(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : List[Any] = replicate(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Union[str, Any] = shard(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Any = jax.random.PRNGKey(0 )
_SCREAMING_SNAKE_CASE : Optional[int] = jax.random.split(lowerCAmelCase_ , jax.device_count() )
_SCREAMING_SNAKE_CASE : Optional[Any] = sd_pipe(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , num_inference_steps=2_5 , jit=lowerCAmelCase_ )[0]
assert images.shape == (jax.device_count(), 1, 7_6_8, 7_6_8, 3)
_SCREAMING_SNAKE_CASE : int = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
_SCREAMING_SNAKE_CASE : Optional[Any] = images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]
_SCREAMING_SNAKE_CASE : Tuple = jnp.asarray(jax.device_get(image_slice.flatten() ) )
_SCREAMING_SNAKE_CASE : List[Any] = jnp.array([0.4_238, 0.4_414, 0.4_395, 0.4_453, 0.4_629, 0.4_590, 0.4_531, 0.45_508, 0.4_512] )
print(F"""output_slice: {output_slice}""" )
assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
def A ( self ) -> Optional[int]:
_SCREAMING_SNAKE_CASE : str = 'stabilityai/stable-diffusion-2'
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = FlaxDPMSolverMultistepScheduler.from_pretrained(lowerCAmelCase_ , subfolder='scheduler' )
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = FlaxStableDiffusionPipeline.from_pretrained(
lowerCAmelCase_ , scheduler=lowerCAmelCase_ , revision='bf16' , dtype=jnp.bfloataa , )
_SCREAMING_SNAKE_CASE : Any = scheduler_params
_SCREAMING_SNAKE_CASE : int = 'A painting of a squirrel eating a burger'
_SCREAMING_SNAKE_CASE : Tuple = jax.device_count()
_SCREAMING_SNAKE_CASE : Union[str, Any] = num_samples * [prompt]
_SCREAMING_SNAKE_CASE : Any = sd_pipe.prepare_inputs(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Dict = replicate(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Any = shard(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Any = jax.random.PRNGKey(0 )
_SCREAMING_SNAKE_CASE : Optional[Any] = jax.random.split(lowerCAmelCase_ , jax.device_count() )
_SCREAMING_SNAKE_CASE : int = sd_pipe(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , num_inference_steps=2_5 , jit=lowerCAmelCase_ )[0]
assert images.shape == (jax.device_count(), 1, 7_6_8, 7_6_8, 3)
_SCREAMING_SNAKE_CASE : str = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
_SCREAMING_SNAKE_CASE : str = images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]
_SCREAMING_SNAKE_CASE : int = jnp.asarray(jax.device_get(image_slice.flatten() ) )
_SCREAMING_SNAKE_CASE : Optional[int] = jnp.array([0.4_336, 0.42_969, 0.4_453, 0.4_199, 0.4_297, 0.4_531, 0.4_434, 0.4_434, 0.4_297] )
print(F"""output_slice: {output_slice}""" )
assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
| 621 | 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
UpperCamelCase : int = 16
UpperCamelCase : Optional[int] = 32
def __snake_case ( UpperCamelCase__ , UpperCamelCase__ = 16 , UpperCamelCase__ = "bert-base-cased" ) -> Optional[int]:
"""simple docstring"""
A = AutoTokenizer.from_pretrained(UpperCamelCase__ )
A = load_dataset('glue' , 'mrpc' )
def tokenize_function(UpperCamelCase__ ):
# max_length=None => use the model max length (it's actually the default)
A = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=UpperCamelCase__ , max_length=UpperCamelCase__ )
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
A = 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
A = tokenized_datasets.rename_column('label' , 'labels' )
def collate_fn(UpperCamelCase__ ):
# On TPU it's best to pad everything to the same length or training will be very slow.
if accelerator.distributed_type == DistributedType.TPU:
return tokenizer.pad(UpperCamelCase__ , padding='max_length' , max_length=128 , return_tensors='pt' )
return tokenizer.pad(UpperCamelCase__ , padding='longest' , return_tensors='pt' )
# Instantiate dataloaders.
A = DataLoader(
tokenized_datasets['train'] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=UpperCamelCase__ )
A = DataLoader(
tokenized_datasets['validation'] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=UpperCamelCase__ )
return train_dataloader, eval_dataloader
def __snake_case ( UpperCamelCase__ , UpperCamelCase__ ) -> Optional[Any]:
"""simple docstring"""
A = Accelerator()
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
A = config['lr']
A = int(config['num_epochs'] )
A = int(config['seed'] )
A = int(config['batch_size'] )
A = args.model_name_or_path
set_seed(UpperCamelCase__ )
A , A = get_dataloaders(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
A = AutoModelForSequenceClassification.from_pretrained(UpperCamelCase__ , return_dict=UpperCamelCase__ )
# Instantiate optimizer
A = (
AdamW
if accelerator.state.deepspeed_plugin is None
or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config
else DummyOptim
)
A = optimizer_cls(params=model.parameters() , lr=UpperCamelCase__ )
if accelerator.state.deepspeed_plugin is not None:
A = accelerator.state.deepspeed_plugin.deepspeed_config[
'gradient_accumulation_steps'
]
else:
A = 1
A = (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
):
A = get_linear_schedule_with_warmup(
optimizer=UpperCamelCase__ , num_warmup_steps=0 , num_training_steps=UpperCamelCase__ , )
else:
A = 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.
A , A , A , A , A = accelerator.prepare(
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )
# We need to keep track of how many total steps we have iterated over
A = 0
# We also need to keep track of the stating epoch so files are named properly
A = 0
# Now we train the model
A = evaluate.load('glue' , 'mrpc' )
A = 0
A = {}
for epoch in range(UpperCamelCase__ , UpperCamelCase__ ):
model.train()
for step, batch in enumerate(UpperCamelCase__ ):
A = model(**UpperCamelCase__ )
A = outputs.loss
A = loss / gradient_accumulation_steps
accelerator.backward(UpperCamelCase__ )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
overall_step += 1
model.eval()
A = 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():
A = model(**UpperCamelCase__ )
A = outputs.logits.argmax(dim=-1 )
# It is slightly faster to call this once, than multiple times
A , A = 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:
A = predictions[: len(eval_dataloader.dataset ) - samples_seen]
A = references[: len(eval_dataloader.dataset ) - samples_seen]
else:
samples_seen += references.shape[0]
metric.add_batch(
predictions=UpperCamelCase__ , references=UpperCamelCase__ , )
A = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f'epoch {epoch}:' , UpperCamelCase__ )
A = eval_metric['accuracy']
if best_performance < eval_metric["accuracy"]:
A = eval_metric['accuracy']
if args.performance_lower_bound is not None:
assert (
args.performance_lower_bound <= best_performance
), f'Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}'
accelerator.wait_for_everyone()
if accelerator.is_main_process:
with open(os.path.join(args.output_dir , 'all_results.json' ) , 'w' ) as f:
json.dump(UpperCamelCase__ , UpperCamelCase__ )
def __snake_case ( ) -> Optional[int]:
"""simple docstring"""
A = 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(
'--performance_lower_bound' , type=UpperCamelCase__ , default=UpperCamelCase__ , help='Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.' , )
parser.add_argument(
'--num_epochs' , type=UpperCamelCase__ , default=3 , help='Number of train epochs.' , )
A = parser.parse_args()
A = {'lr': 2E-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16}
training_function(UpperCamelCase__ , UpperCamelCase__ )
if __name__ == "__main__":
main()
| 91 |
"""simple docstring"""
from math import sqrt
def __snake_case ( UpperCamelCase__ ) -> int:
"""simple docstring"""
A = 0
for i in range(1 , int(sqrt(UpperCamelCase__ ) + 1 ) ):
if n % i == 0 and i != sqrt(UpperCamelCase__ ):
total += i + n // i
elif i == sqrt(UpperCamelCase__ ):
total += i
return total - n
def __snake_case ( UpperCamelCase__ = 10000 ) -> int:
"""simple docstring"""
A = sum(
i
for i in range(1 , UpperCamelCase__ )
if sum_of_divisors(sum_of_divisors(UpperCamelCase__ ) ) == i and sum_of_divisors(UpperCamelCase__ ) != i )
return total
if __name__ == "__main__":
print(solution(int(str(input()).strip())))
| 91 | 1 |
from collections import deque
from .hash_table import HashTable
class UpperCAmelCase_ ( __lowerCamelCase ):
def __init__( self , *_lowerCAmelCase , **_lowerCAmelCase ):
super().__init__(*_lowerCAmelCase , **_lowerCAmelCase )
def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase ):
UpperCAmelCase__ : List[Any] = deque([] ) if self.values[key] is None else self.values[key]
self.values[key].appendleft(_lowerCAmelCase )
UpperCAmelCase__ : List[str] = self.values[key]
def __UpperCAmelCase ( self ):
return (
sum(self.charge_factor - len(_lowerCAmelCase ) for slot in self.values )
/ self.size_table
* self.charge_factor
)
def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase=None ):
if not (
len(self.values[key] ) == self.charge_factor and self.values.count(_lowerCAmelCase ) == 0
):
return key
return super()._collision_resolution(_lowerCAmelCase , _lowerCAmelCase )
| 79 |
'''simple docstring'''
from __future__ import annotations
def a_ ( __snake_case : int ) -> list[int]:
"""simple docstring"""
lowerCamelCase_ =[True] * limit
lowerCamelCase_ =False
lowerCamelCase_ =False
lowerCamelCase_ =True
for i in range(3 , int(limit**0.5 + 1 ) , 2 ):
lowerCamelCase_ =i * 2
while index < limit:
lowerCamelCase_ =False
lowerCamelCase_ =index + i
lowerCamelCase_ =[2]
for i in range(3 , __snake_case , 2 ):
if is_prime[i]:
primes.append(__snake_case )
return primes
def a_ ( __snake_case : int = 100_0000 ) -> int:
"""simple docstring"""
lowerCamelCase_ =prime_sieve(__snake_case )
lowerCamelCase_ =0
lowerCamelCase_ =0
for i in range(len(__snake_case ) ):
for j in range(i + length , len(__snake_case ) ):
lowerCamelCase_ =sum(primes[i:j] )
if sol >= ceiling:
break
if sol in primes:
lowerCamelCase_ =j - i
lowerCamelCase_ =sol
return largest
if __name__ == "__main__":
print(F"""{solution() = }""")
| 676 | 0 |
'''simple docstring'''
def __UpperCAmelCase ( a_: str = 1_000_000 ):
_UpperCAmelCase : Optional[int] = limit + 1
_UpperCAmelCase : List[Any] = [0] * limit
for first_term in range(1, SCREAMING_SNAKE_CASE_ ):
for n in range(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ):
_UpperCAmelCase : str = first_term + n / first_term
if common_difference % 4: # d must be divisble by 4
continue
else:
common_difference /= 4
if (
first_term > common_difference
and first_term < 4 * common_difference
): # since x,y,z are positive integers
frequency[n] += 1 # so z>0 and a>d ,also 4d<a
_UpperCAmelCase : List[str] = sum(1 for x in frequency[1:limit] if x == 10 )
return count
if __name__ == "__main__":
print(f'{solution() = }')
| 715 |
'''simple docstring'''
import sys
from typing import Tuple
import numpy as np
import torch
from PIL import Image
from torch import nn
from transformers.image_utils import PILImageResampling
from utils import img_tensorize
class A__ :
"""simple docstring"""
def __init__( self : List[str] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Any=sys.maxsize ) -> Tuple:
"""simple docstring"""
_UpperCAmelCase : List[Any] = "bilinear"
_UpperCAmelCase : Union[str, Any] = max_size
_UpperCAmelCase : Tuple = short_edge_length
def __call__( self : List[str] , lowerCAmelCase__ : List[str] ) -> Optional[Any]:
"""simple docstring"""
_UpperCAmelCase : Union[str, Any] = []
for img in imgs:
_UpperCAmelCase , _UpperCAmelCase : List[Any] = img.shape[:2]
# later: provide list and randomly choose index for resize
_UpperCAmelCase : List[Any] = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1 )
if size == 0:
return img
_UpperCAmelCase : List[Any] = size * 1.0 / min(lowerCAmelCase__ , lowerCAmelCase__ )
if h < w:
_UpperCAmelCase , _UpperCAmelCase : str = size, scale * w
else:
_UpperCAmelCase , _UpperCAmelCase : Optional[Any] = scale * h, size
if max(lowerCAmelCase__ , lowerCAmelCase__ ) > self.max_size:
_UpperCAmelCase : List[Any] = self.max_size * 1.0 / max(lowerCAmelCase__ , lowerCAmelCase__ )
_UpperCAmelCase : Any = newh * scale
_UpperCAmelCase : str = neww * scale
_UpperCAmelCase : Union[str, Any] = int(neww + 0.5 )
_UpperCAmelCase : Optional[int] = int(newh + 0.5 )
if img.dtype == np.uinta:
_UpperCAmelCase : Optional[Any] = Image.fromarray(lowerCAmelCase__ )
_UpperCAmelCase : Any = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR )
_UpperCAmelCase : Optional[Any] = np.asarray(lowerCAmelCase__ )
else:
_UpperCAmelCase : Tuple = img.permute(2 , 0 , 1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw
_UpperCAmelCase : str = nn.functional.interpolate(
lowerCAmelCase__ , (newh, neww) , mode=self.interp_method , align_corners=lowerCAmelCase__ ).squeeze(0 )
img_augs.append(lowerCAmelCase__ )
return img_augs
class A__ :
"""simple docstring"""
def __init__( self : str , lowerCAmelCase__ : Optional[int] ) -> Tuple:
"""simple docstring"""
_UpperCAmelCase : Union[str, Any] = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST )
_UpperCAmelCase : str = cfg.INPUT.FORMAT
_UpperCAmelCase : List[Any] = cfg.SIZE_DIVISIBILITY
_UpperCAmelCase : int = cfg.PAD_VALUE
_UpperCAmelCase : Optional[int] = cfg.INPUT.MAX_SIZE_TEST
_UpperCAmelCase : Tuple = cfg.MODEL.DEVICE
_UpperCAmelCase : Union[str, Any] = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 )
_UpperCAmelCase : Optional[int] = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 )
_UpperCAmelCase : Any = lambda lowerCAmelCase__ : (x - self.pixel_mean) / self.pixel_std
def _lowerCAmelCase ( self : Any , lowerCAmelCase__ : List[str] ) -> Optional[int]:
"""simple docstring"""
_UpperCAmelCase : Dict = tuple(max(lowerCAmelCase__ ) for s in zip(*[img.shape for img in images] ) )
_UpperCAmelCase : str = [im.shape[-2:] for im in images]
_UpperCAmelCase : Any = [
nn.functional.pad(
lowerCAmelCase__ , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , )
for size, im in zip(lowerCAmelCase__ , lowerCAmelCase__ )
]
return torch.stack(lowerCAmelCase__ ), torch.tensor(lowerCAmelCase__ )
def __call__( self : Optional[int] , lowerCAmelCase__ : str , lowerCAmelCase__ : List[Any]=False ) -> str:
"""simple docstring"""
with torch.no_grad():
if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ):
_UpperCAmelCase : Any = [images]
if single_image:
assert len(lowerCAmelCase__ ) == 1
for i in range(len(lowerCAmelCase__ ) ):
if isinstance(images[i] , torch.Tensor ):
images.insert(lowerCAmelCase__ , images.pop(lowerCAmelCase__ ).to(self.device ).float() )
elif not isinstance(images[i] , torch.Tensor ):
images.insert(
lowerCAmelCase__ , torch.as_tensor(img_tensorize(images.pop(lowerCAmelCase__ ) , input_format=self.input_format ) )
.to(self.device )
.float() , )
# resize smallest edge
_UpperCAmelCase : Any = torch.tensor([im.shape[:2] for im in images] )
_UpperCAmelCase : str = self.aug(lowerCAmelCase__ )
# transpose images and convert to torch tensors
# images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images]
# now normalize before pad to avoid useless arithmetic
_UpperCAmelCase : int = [self.normalizer(lowerCAmelCase__ ) for x in images]
# now pad them to do the following operations
_UpperCAmelCase , _UpperCAmelCase : Optional[int] = self.pad(lowerCAmelCase__ )
# Normalize
if self.size_divisibility > 0:
raise NotImplementedError()
# pad
_UpperCAmelCase : int = torch.true_divide(lowerCAmelCase__ , lowerCAmelCase__ )
if single_image:
return images[0], sizes[0], scales_yx[0]
else:
return images, sizes, scales_yx
def __UpperCAmelCase ( a_: Union[str, Any], a_: Optional[int] ):
boxes[:, 0::2] *= scale_yx[:, 1]
boxes[:, 1::2] *= scale_yx[:, 0]
return boxes
def __UpperCAmelCase ( a_: Tuple, a_: Tuple[int, int] ):
assert torch.isfinite(a_ ).all(), "Box tensor contains infinite or NaN!"
_UpperCAmelCase , _UpperCAmelCase : Tuple = box_size
tensor[:, 0].clamp_(min=0, max=a_ )
tensor[:, 1].clamp_(min=0, max=a_ )
tensor[:, 2].clamp_(min=0, max=a_ )
tensor[:, 3].clamp_(min=0, max=a_ )
| 257 | 0 |
import argparse
import json
import requests
import timm
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification
def snake_case__ ( lowercase ):
lowerCAmelCase_: List[str] = SwinConfig()
lowerCAmelCase_: Optional[Any] = swin_name.split("_" )
lowerCAmelCase_: Optional[int] = name_split[1]
lowerCAmelCase_: List[Any] = int(name_split[4] )
lowerCAmelCase_: Any = int(name_split[3][-1] )
if model_size == "tiny":
lowerCAmelCase_: Optional[Any] = 96
lowerCAmelCase_: List[Any] = (2, 2, 6, 2)
lowerCAmelCase_: str = (3, 6, 12, 24)
elif model_size == "small":
lowerCAmelCase_: Dict = 96
lowerCAmelCase_: Any = (2, 2, 18, 2)
lowerCAmelCase_: str = (3, 6, 12, 24)
elif model_size == "base":
lowerCAmelCase_: List[str] = 128
lowerCAmelCase_: Dict = (2, 2, 18, 2)
lowerCAmelCase_: Optional[Any] = (4, 8, 16, 32)
else:
lowerCAmelCase_: Union[str, Any] = 192
lowerCAmelCase_: Tuple = (2, 2, 18, 2)
lowerCAmelCase_: Union[str, Any] = (6, 12, 24, 48)
if "in22k" in swin_name:
lowerCAmelCase_: int = 21841
else:
lowerCAmelCase_: Optional[Any] = 1000
lowerCAmelCase_: Dict = "huggingface/label-files"
lowerCAmelCase_: Optional[Any] = "imagenet-1k-id2label.json"
lowerCAmelCase_: Union[str, Any] = json.load(open(hf_hub_download(UpperCAmelCase__ , UpperCAmelCase__ , repo_type="dataset" ) , "r" ) )
lowerCAmelCase_: Union[str, Any] = {int(UpperCAmelCase__ ): v for k, v in idalabel.items()}
lowerCAmelCase_: Optional[Any] = idalabel
lowerCAmelCase_: Optional[Any] = {v: k for k, v in idalabel.items()}
lowerCAmelCase_: Union[str, Any] = img_size
lowerCAmelCase_: Any = num_classes
lowerCAmelCase_: Optional[int] = embed_dim
lowerCAmelCase_: Any = depths
lowerCAmelCase_: Tuple = num_heads
lowerCAmelCase_: Any = window_size
return config
def snake_case__ ( lowercase ):
if "patch_embed.proj" in name:
lowerCAmelCase_: Union[str, Any] = name.replace("patch_embed.proj" , "embeddings.patch_embeddings.projection" )
if "patch_embed.norm" in name:
lowerCAmelCase_: str = name.replace("patch_embed.norm" , "embeddings.norm" )
if "layers" in name:
lowerCAmelCase_: Any = "encoder." + name
if "attn.proj" in name:
lowerCAmelCase_: int = name.replace("attn.proj" , "attention.output.dense" )
if "attn" in name:
lowerCAmelCase_: int = name.replace("attn" , "attention.self" )
if "norm1" in name:
lowerCAmelCase_: Union[str, Any] = name.replace("norm1" , "layernorm_before" )
if "norm2" in name:
lowerCAmelCase_: List[str] = name.replace("norm2" , "layernorm_after" )
if "mlp.fc1" in name:
lowerCAmelCase_: Union[str, Any] = name.replace("mlp.fc1" , "intermediate.dense" )
if "mlp.fc2" in name:
lowerCAmelCase_: Optional[Any] = name.replace("mlp.fc2" , "output.dense" )
if name == "norm.weight":
lowerCAmelCase_: str = "layernorm.weight"
if name == "norm.bias":
lowerCAmelCase_: Optional[int] = "layernorm.bias"
if "head" in name:
lowerCAmelCase_: List[Any] = name.replace("head" , "classifier" )
else:
lowerCAmelCase_: Optional[int] = "swin." + name
return name
def snake_case__ ( lowercase , lowercase ):
for key in orig_state_dict.copy().keys():
lowerCAmelCase_: Any = orig_state_dict.pop(UpperCAmelCase__ )
if "mask" in key:
continue
elif "qkv" in key:
lowerCAmelCase_: Optional[Any] = key.split("." )
lowerCAmelCase_: Union[str, Any] = int(key_split[1] )
lowerCAmelCase_: List[str] = int(key_split[3] )
lowerCAmelCase_: int = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size
if "weight" in key:
lowerCAmelCase_: Any = val[:dim, :]
lowerCAmelCase_: Union[str, Any] = val[
dim : dim * 2, :
]
lowerCAmelCase_: Any = val[-dim:, :]
else:
lowerCAmelCase_: str = val[
:dim
]
lowerCAmelCase_: List[str] = val[
dim : dim * 2
]
lowerCAmelCase_: Dict = val[
-dim:
]
else:
lowerCAmelCase_: Optional[Any] = val
return orig_state_dict
def snake_case__ ( lowercase , lowercase ):
lowerCAmelCase_: Any = timm.create_model(UpperCAmelCase__ , pretrained=UpperCAmelCase__ )
timm_model.eval()
lowerCAmelCase_: Optional[Any] = get_swin_config(UpperCAmelCase__ )
lowerCAmelCase_: str = SwinForImageClassification(UpperCAmelCase__ )
model.eval()
lowerCAmelCase_: str = convert_state_dict(timm_model.state_dict() , UpperCAmelCase__ )
model.load_state_dict(UpperCAmelCase__ )
lowerCAmelCase_: Optional[int] = "http://images.cocodataset.org/val2017/000000039769.jpg"
lowerCAmelCase_: int = AutoImageProcessor.from_pretrained("microsoft/{}".format(swin_name.replace("_" , "-" ) ) )
lowerCAmelCase_: str = Image.open(requests.get(UpperCAmelCase__ , stream=UpperCAmelCase__ ).raw )
lowerCAmelCase_: int = image_processor(images=UpperCAmelCase__ , return_tensors="pt" )
lowerCAmelCase_: List[str] = timm_model(inputs["pixel_values"] )
lowerCAmelCase_: Dict = model(**UpperCAmelCase__ ).logits
assert torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 )
print(F'''Saving model {swin_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(UpperCAmelCase__ )
print(F'''Saving image processor to {pytorch_dump_folder_path}''' )
image_processor.save_pretrained(UpperCAmelCase__ )
if __name__ == "__main__":
a : Union[str, Any] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--swin_name""",
default="""swin_tiny_patch4_window7_224""",
type=str,
help="""Name of the Swin timm model you'd like to convert.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
)
a : List[Any] = parser.parse_args()
convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
| 613 |
import argparse
import intel_extension_for_pytorch as ipex
import torch
from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline
A_ : List[Any] =argparse.ArgumentParser("""Stable Diffusion script with intel optimization""", add_help=False)
parser.add_argument("""--dpm""", action="""store_true""", help="""Enable DPMSolver or not""")
parser.add_argument("""--steps""", default=None, type=int, help="""Num inference steps""")
A_ : List[Any] =parser.parse_args()
A_ : Tuple ="""cpu"""
A_ : List[Any] ="""a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brighly buildings"""
A_ : Union[str, Any] ="""path-to-your-trained-model"""
A_ : str =StableDiffusionPipeline.from_pretrained(model_id)
if args.dpm:
A_ : Dict =DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
A_ : List[Any] =pipe.to(device)
# to channels last
A_ : Optional[int] =pipe.unet.to(memory_format=torch.channels_last)
A_ : Optional[int] =pipe.vae.to(memory_format=torch.channels_last)
A_ : Optional[Any] =pipe.text_encoder.to(memory_format=torch.channels_last)
if pipe.requires_safety_checker:
A_ : Union[str, Any] =pipe.safety_checker.to(memory_format=torch.channels_last)
# optimize with ipex
A_ : Any =torch.randn(2, 4, 64, 64)
A_ : List[Any] =torch.rand(1) * 999
A_ : str =torch.randn(2, 77, 768)
A_ : Optional[int] =(sample, timestep, encoder_hidden_status)
try:
A_ : Dict =ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True, sample_input=input_example)
except Exception:
A_ : List[Any] =ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True)
A_ : int =ipex.optimize(pipe.vae.eval(), dtype=torch.bfloataa, inplace=True)
A_ : Tuple =ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloataa, inplace=True)
if pipe.requires_safety_checker:
A_ : Any =ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloataa, inplace=True)
# compute
A_ : Any =666
A_ : int =torch.Generator(device).manual_seed(seed)
A_ : Any ={"""generator""": generator}
if args.steps is not None:
A_ : List[str] =args.steps
with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloataa):
A_ : Any =pipe(prompt, **generate_kwargs).images[0]
# save image
image.save("""generated.png""")
| 483 | 0 |
'''simple docstring'''
import functools
import operator
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__snake_case : str = logging.get_logger(__name__)
__snake_case : Dict = {
"microsoft/unispeech-large-1500h-cv": (
"https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json"
),
# See all UniSpeech models at https://huggingface.co/models?filter=unispeech
}
class A ( UpperCAmelCase__ ):
__UpperCAmelCase : List[str] = "unispeech"
def __init__( self , snake_case_=3_2 , snake_case_=7_6_8 , snake_case_=1_2 , snake_case_=1_2 , snake_case_=3_0_7_2 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=0.1 , snake_case_=0.0 , snake_case_=0.0 , snake_case_=0.1 , snake_case_=0.1 , snake_case_=0.02 , snake_case_=1E-5 , snake_case_="group" , snake_case_="gelu" , snake_case_=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , snake_case_=(5, 2, 2, 2, 2, 2, 2) , snake_case_=(1_0, 3, 3, 3, 3, 2, 2) , snake_case_=False , snake_case_=1_2_8 , snake_case_=1_6 , snake_case_=False , snake_case_=True , snake_case_=0.05 , snake_case_=1_0 , snake_case_=2 , snake_case_=0.0 , snake_case_=1_0 , snake_case_=0 , snake_case_=3_2_0 , snake_case_=2 , snake_case_=0.1 , snake_case_=1_0_0 , snake_case_=2_5_6 , snake_case_=2_5_6 , snake_case_=0.1 , snake_case_="mean" , snake_case_=False , snake_case_=False , snake_case_=2_5_6 , snake_case_=8_0 , snake_case_=0 , snake_case_=1 , snake_case_=2 , snake_case_=0.5 , **snake_case_ , ) -> Any:
super().__init__(**lowerCamelCase__ , pad_token_id=lowerCamelCase__ , bos_token_id=lowerCamelCase__ , eos_token_id=lowerCamelCase__ )
_a = hidden_size
_a = feat_extract_norm
_a = feat_extract_activation
_a = list(lowerCamelCase__ )
_a = list(lowerCamelCase__ )
_a = list(lowerCamelCase__ )
_a = conv_bias
_a = num_conv_pos_embeddings
_a = num_conv_pos_embedding_groups
_a = len(self.conv_dim )
_a = num_hidden_layers
_a = intermediate_size
_a = hidden_act
_a = num_attention_heads
_a = hidden_dropout
_a = attention_dropout
_a = activation_dropout
_a = feat_proj_dropout
_a = final_dropout
_a = layerdrop
_a = layer_norm_eps
_a = initializer_range
_a = num_ctc_classes
_a = vocab_size
_a = do_stable_layer_norm
_a = use_weighted_layer_sum
_a = classifier_proj_size
if (
(len(self.conv_stride ) != self.num_feat_extract_layers)
or (len(self.conv_kernel ) != self.num_feat_extract_layers)
or (len(self.conv_dim ) != self.num_feat_extract_layers)
):
raise ValueError(
"Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
" `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
F''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,'''
F''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' )
# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
_a = apply_spec_augment
_a = mask_time_prob
_a = mask_time_length
_a = mask_time_min_masks
_a = mask_feature_prob
_a = mask_feature_length
_a = mask_feature_min_masks
# parameters for pretraining with codevector quantized representations
_a = num_codevectors_per_group
_a = num_codevector_groups
_a = contrastive_logits_temperature
_a = feat_quantizer_dropout
_a = num_negatives
_a = codevector_dim
_a = proj_codevector_dim
_a = diversity_loss_weight
# ctc loss
_a = ctc_loss_reduction
_a = ctc_zero_infinity
# pretraining loss
_a = replace_prob
@property
def __lowerCAmelCase ( self ) -> Union[str, Any]:
return functools.reduce(operator.mul , self.conv_stride , 1 )
| 718 |
'''simple docstring'''
import os
import unittest
from transformers import BatchEncoding
from transformers.models.bert.tokenization_bert import (
BasicTokenizer,
WordpieceTokenizer,
_is_control,
_is_punctuation,
_is_whitespace,
)
from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer
from transformers.testing_utils import require_torch, slow
from ...test_tokenization_common import TokenizerTesterMixin
class A ( a , unittest.TestCase ):
__UpperCAmelCase : List[Any] = ProphetNetTokenizer
__UpperCAmelCase : Optional[Any] = False
def __lowerCAmelCase ( self ) -> Tuple:
super().setUp()
_a = [
"[UNK]",
"[CLS]",
"[SEP]",
"[PAD]",
"[MASK]",
"want",
"##want",
"##ed",
"wa",
"un",
"runn",
"##ing",
",",
"low",
"lowest",
]
_a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) )
def __lowerCAmelCase ( self , snake_case_ ) -> Any:
_a = "UNwant\u00E9d,running"
_a = "unwanted, running"
return input_text, output_text
def __lowerCAmelCase ( self ) -> Any:
_a = self.tokenizer_class(self.vocab_file )
_a = tokenizer.tokenize("UNwant\u00E9d,running" )
self.assertListEqual(snake_case_ , ["un", "##want", "##ed", ",", "runn", "##ing"] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case_ ) , [9, 6, 7, 1_2, 1_0, 1_1] )
def __lowerCAmelCase ( self ) -> List[str]:
_a = BasicTokenizer()
self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] )
def __lowerCAmelCase ( self ) -> Any:
_a = BasicTokenizer(do_lower_case=snake_case_ )
self.assertListEqual(
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] )
self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] )
def __lowerCAmelCase ( self ) -> Union[str, Any]:
_a = BasicTokenizer(do_lower_case=snake_case_ , strip_accents=snake_case_ )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] )
self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] )
def __lowerCAmelCase ( self ) -> Tuple:
_a = BasicTokenizer(do_lower_case=snake_case_ , strip_accents=snake_case_ )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] )
self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] )
def __lowerCAmelCase ( self ) -> Any:
_a = BasicTokenizer(do_lower_case=snake_case_ )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] )
self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] )
def __lowerCAmelCase ( self ) -> List[Any]:
_a = BasicTokenizer(do_lower_case=snake_case_ )
self.assertListEqual(
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] )
def __lowerCAmelCase ( self ) -> int:
_a = BasicTokenizer(do_lower_case=snake_case_ , strip_accents=snake_case_ )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] )
def __lowerCAmelCase ( self ) -> Tuple:
_a = BasicTokenizer(do_lower_case=snake_case_ , strip_accents=snake_case_ )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] )
def __lowerCAmelCase ( self ) -> Union[str, Any]:
_a = BasicTokenizer(do_lower_case=snake_case_ , never_split=["[UNK]"] )
self.assertListEqual(
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] )
def __lowerCAmelCase ( self ) -> List[str]:
_a = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"]
_a = {}
for i, token in enumerate(snake_case_ ):
_a = i
_a = WordpieceTokenizer(vocab=snake_case_ , unk_token="[UNK]" )
self.assertListEqual(tokenizer.tokenize("" ) , [] )
self.assertListEqual(tokenizer.tokenize("unwanted running" ) , ["un", "##want", "##ed", "runn", "##ing"] )
self.assertListEqual(tokenizer.tokenize("unwantedX running" ) , ["[UNK]", "runn", "##ing"] )
@require_torch
def __lowerCAmelCase ( self ) -> Tuple:
_a = self.tokenizer_class.from_pretrained("microsoft/prophetnet-large-uncased" )
_a = ["A long paragraph for summarization.", "Another paragraph for summarization."]
_a = [1_0_3_7, 2_1_4_6, 2_0_4_2_3, 2_0_0_5, 7_6_8_0, 7_8_4_9, 3_9_8_9, 1_0_1_2, 1_0_2]
_a = tokenizer(snake_case_ , padding=snake_case_ , return_tensors="pt" )
self.assertIsInstance(snake_case_ , snake_case_ )
_a = list(batch.input_ids.numpy()[0] )
self.assertListEqual(snake_case_ , snake_case_ )
self.assertEqual((2, 9) , batch.input_ids.shape )
self.assertEqual((2, 9) , batch.attention_mask.shape )
def __lowerCAmelCase ( self ) -> List[Any]:
self.assertTrue(_is_whitespace(" " ) )
self.assertTrue(_is_whitespace("\t" ) )
self.assertTrue(_is_whitespace("\r" ) )
self.assertTrue(_is_whitespace("\n" ) )
self.assertTrue(_is_whitespace("\u00A0" ) )
self.assertFalse(_is_whitespace("A" ) )
self.assertFalse(_is_whitespace("-" ) )
def __lowerCAmelCase ( self ) -> Optional[Any]:
self.assertTrue(_is_control("\u0005" ) )
self.assertFalse(_is_control("A" ) )
self.assertFalse(_is_control(" " ) )
self.assertFalse(_is_control("\t" ) )
self.assertFalse(_is_control("\r" ) )
def __lowerCAmelCase ( self ) -> List[Any]:
self.assertTrue(_is_punctuation("-" ) )
self.assertTrue(_is_punctuation("$" ) )
self.assertTrue(_is_punctuation("`" ) )
self.assertTrue(_is_punctuation("." ) )
self.assertFalse(_is_punctuation("A" ) )
self.assertFalse(_is_punctuation(" " ) )
@slow
def __lowerCAmelCase ( self ) -> Optional[Any]:
_a = self.tokenizer_class.from_pretrained("microsoft/prophetnet-large-uncased" )
_a = tokenizer.encode("sequence builders" , add_special_tokens=snake_case_ )
_a = tokenizer.encode("multi-sequence build" , add_special_tokens=snake_case_ )
_a = tokenizer.build_inputs_with_special_tokens(snake_case_ )
_a = tokenizer.build_inputs_with_special_tokens(snake_case_ , snake_case_ )
assert encoded_sentence == text + [1_0_2]
assert encoded_pair == text + [1_0_2] + text_a + [1_0_2]
| 691 | 0 |
'''simple docstring'''
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
# @@protoc_insertion_point(imports)
UpperCAmelCase_ : Any = _symbol_database.Default()
UpperCAmelCase_ : Dict = _descriptor_pool.Default().AddSerializedFile(
B'\n\x19sentencepiece_model.proto\x12\rsentencepiece"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18. \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03'
)
UpperCAmelCase_ : int = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'sentencepiece_model_pb2', _globals)
if _descriptor._USE_C_DESCRIPTORS is False:
UpperCAmelCase_ : Optional[int] = None
UpperCAmelCase_ : Optional[Any] = B'H\003'
# (generated by protobuf compiler, but `_TRAINERSPEC` is not defined)
# _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None
# _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001"
# _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None
# _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001"
UpperCAmelCase_ : Optional[int] = 45
UpperCAmelCase_ : Any = 1581
UpperCAmelCase_ : List[Any] = 1517
UpperCAmelCase_ : str = 1570
UpperCAmelCase_ : str = 1584
UpperCAmelCase_ : Dict = 1793
UpperCAmelCase_ : List[str] = 1795
UpperCAmelCase_ : Tuple = 1916
UpperCAmelCase_ : str = 1864
UpperCAmelCase_ : Any = 1905
UpperCAmelCase_ : Any = 1919
UpperCAmelCase_ : Tuple = 2429
UpperCAmelCase_ : Union[str, Any] = 2208
UpperCAmelCase_ : Any = 2418
UpperCAmelCase_ : Optional[Any] = 2323
UpperCAmelCase_ : Any = 2407
# @@protoc_insertion_point(module_scope)
| 533 |
'''simple docstring'''
from __future__ import annotations
def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
"""simple docstring"""
if len(SCREAMING_SNAKE_CASE__ ) <= 1 or n <= 1:
return
insert_next(SCREAMING_SNAKE_CASE__ , n - 1 )
rec_insertion_sort(SCREAMING_SNAKE_CASE__ , n - 1 )
def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
"""simple docstring"""
if index >= len(SCREAMING_SNAKE_CASE__ ) or collection[index - 1] <= collection[index]:
return
# Swaps adjacent elements since they are not in ascending order
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = (
collection[index],
collection[index - 1],
)
insert_next(SCREAMING_SNAKE_CASE__ , index + 1 )
if __name__ == "__main__":
UpperCAmelCase_ : List[str] = input('Enter integers separated by spaces: ')
UpperCAmelCase_ : list[int] = [int(num) for num in numbers.split()]
rec_insertion_sort(number_list, len(number_list))
print(number_list)
| 533 | 1 |
'''simple docstring'''
import argparse
import json
from collections import OrderedDict
from functools import partial
from pathlib import Path
import timm
import torch
from huggingface_hub import hf_hub_download
from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor
from transformers.utils import logging
logging.set_verbosity_info()
A_ : Union[str, Any] = logging.get_logger()
def A_ ( snake_case , snake_case , snake_case , snake_case , snake_case = True ):
print(F'''Converting {name}...''' )
with torch.no_grad():
if hidden_sizes == 128:
if name[-1] == "S":
SCREAMING_SNAKE_CASE:Optional[int] = timm.create_model("levit_128s" , pretrained=snake_case )
else:
SCREAMING_SNAKE_CASE:List[str] = timm.create_model("levit_128" , pretrained=snake_case )
if hidden_sizes == 192:
SCREAMING_SNAKE_CASE:int = timm.create_model("levit_192" , pretrained=snake_case )
if hidden_sizes == 256:
SCREAMING_SNAKE_CASE:Dict = timm.create_model("levit_256" , pretrained=snake_case )
if hidden_sizes == 384:
SCREAMING_SNAKE_CASE:List[Any] = timm.create_model("levit_384" , pretrained=snake_case )
from_model.eval()
SCREAMING_SNAKE_CASE:int = LevitForImageClassificationWithTeacher(snake_case ).eval()
SCREAMING_SNAKE_CASE:str = OrderedDict()
SCREAMING_SNAKE_CASE:Dict = from_model.state_dict()
SCREAMING_SNAKE_CASE:Optional[int] = list(from_model.state_dict().keys() )
SCREAMING_SNAKE_CASE:List[str] = list(our_model.state_dict().keys() )
print(len(snake_case ) , len(snake_case ) )
for i in range(len(snake_case ) ):
SCREAMING_SNAKE_CASE:Dict = weights[og_keys[i]]
our_model.load_state_dict(snake_case )
SCREAMING_SNAKE_CASE:int = torch.randn((2, 3, 224, 224) )
SCREAMING_SNAKE_CASE:Tuple = from_model(snake_case )
SCREAMING_SNAKE_CASE:str = our_model(snake_case ).logits
assert torch.allclose(snake_case , snake_case ), "The model logits don't match the original one."
SCREAMING_SNAKE_CASE:int = name
print(snake_case )
if push_to_hub:
our_model.save_pretrained(save_directory / checkpoint_name )
SCREAMING_SNAKE_CASE:Optional[Any] = LevitImageProcessor()
image_processor.save_pretrained(save_directory / checkpoint_name )
print(F'''Pushed {checkpoint_name}''' )
def A_ ( snake_case , snake_case = None , snake_case = True ):
SCREAMING_SNAKE_CASE:List[Any] = """imagenet-1k-id2label.json"""
SCREAMING_SNAKE_CASE:str = 1000
SCREAMING_SNAKE_CASE:int = (1, num_labels)
SCREAMING_SNAKE_CASE:Tuple = """huggingface/label-files"""
SCREAMING_SNAKE_CASE:Dict = num_labels
SCREAMING_SNAKE_CASE:Dict = json.load(open(hf_hub_download(snake_case , snake_case , repo_type="dataset" ) , "r" ) )
SCREAMING_SNAKE_CASE:List[Any] = {int(snake_case ): v for k, v in idalabel.items()}
SCREAMING_SNAKE_CASE:Union[str, Any] = idalabel
SCREAMING_SNAKE_CASE:Any = {v: k for k, v in idalabel.items()}
SCREAMING_SNAKE_CASE:Union[str, Any] = partial(snake_case , num_labels=snake_case , idalabel=snake_case , labelaid=snake_case )
SCREAMING_SNAKE_CASE:int = {
"""levit-128S""": 128,
"""levit-128""": 128,
"""levit-192""": 192,
"""levit-256""": 256,
"""levit-384""": 384,
}
SCREAMING_SNAKE_CASE:Tuple = {
"""levit-128S""": ImageNetPreTrainedConfig(
hidden_sizes=[128, 256, 384] , num_attention_heads=[4, 6, 8] , depths=[2, 3, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ),
"""levit-128""": ImageNetPreTrainedConfig(
hidden_sizes=[128, 256, 384] , num_attention_heads=[4, 8, 12] , depths=[4, 4, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ),
"""levit-192""": ImageNetPreTrainedConfig(
hidden_sizes=[192, 288, 384] , num_attention_heads=[3, 5, 6] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ),
"""levit-256""": ImageNetPreTrainedConfig(
hidden_sizes=[256, 384, 512] , num_attention_heads=[4, 6, 8] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ),
"""levit-384""": ImageNetPreTrainedConfig(
hidden_sizes=[384, 512, 768] , num_attention_heads=[6, 9, 12] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0.1 , ),
}
if model_name:
convert_weight_and_push(
names_to_hidden_sizes[model_name] , snake_case , names_to_config[model_name] , snake_case , snake_case )
else:
for model_name, config in names_to_config.items():
convert_weight_and_push(names_to_hidden_sizes[model_name] , snake_case , snake_case , snake_case , snake_case )
return config, expected_shape
if __name__ == "__main__":
A_ : Optional[Any] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--model_name",
default=None,
type=str,
help="The name of the model you wish to convert, it must be one of the supported Levit* architecture,",
)
parser.add_argument(
"--pytorch_dump_folder_path",
default="levit-dump-folder/",
type=Path,
required=False,
help="Path to the output PyTorch model directory.",
)
parser.add_argument("--push_to_hub", action="store_true", help="Push model and image processor to the hub")
parser.add_argument(
"--no-push_to_hub",
dest="push_to_hub",
action="store_false",
help="Do not push model and image processor to the hub",
)
A_ : Optional[int] = parser.parse_args()
A_ : str = args.pytorch_dump_folder_path
pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
| 708 |
'''simple docstring'''
import warnings
from functools import wraps
from typing import Callable
def A_ ( snake_case ):
@wraps(snake_case )
def _inner_fn(*snake_case , **snake_case ):
warnings.warn(
(F'''\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.''') , snake_case , )
return fn(*snake_case , **snake_case )
return _inner_fn
| 465 | 0 |
'''simple docstring'''
from datasets.utils.patching import _PatchedModuleObj, patch_submodule
from . import _test_patching
def __lowercase () -> str:
"""simple docstring"""
import os as original_os
from os import path as original_path
from os import rename as original_rename
from os.path import dirname as original_dirname
from os.path import join as original_join
assert _test_patching.os is original_os
assert _test_patching.path is original_path
assert _test_patching.join is original_join
assert _test_patching.renamed_os is original_os
assert _test_patching.renamed_path is original_path
assert _test_patching.renamed_join is original_join
__lowerCamelCase : List[Any] = """__test_patch_submodule_mock__"""
with patch_submodule(_test_patching, """os.path.join""", _lowercase ):
# Every way to access os.path.join must be patched, and the rest must stay untouched
# check os.path.join
assert isinstance(_test_patching.os, _PatchedModuleObj )
assert isinstance(_test_patching.os.path, _PatchedModuleObj )
assert _test_patching.os.path.join is mock
# check path.join
assert isinstance(_test_patching.path, _PatchedModuleObj )
assert _test_patching.path.join is mock
# check join
assert _test_patching.join is mock
# check that the other attributes are untouched
assert _test_patching.os.rename is original_rename
assert _test_patching.path.dirname is original_dirname
assert _test_patching.os.path.dirname is original_dirname
# Even renamed modules or objects must be patched
# check renamed_os.path.join
assert isinstance(_test_patching.renamed_os, _PatchedModuleObj )
assert isinstance(_test_patching.renamed_os.path, _PatchedModuleObj )
assert _test_patching.renamed_os.path.join is mock
# check renamed_path.join
assert isinstance(_test_patching.renamed_path, _PatchedModuleObj )
assert _test_patching.renamed_path.join is mock
# check renamed_join
assert _test_patching.renamed_join is mock
# check that the other attributes are untouched
assert _test_patching.renamed_os.rename is original_rename
assert _test_patching.renamed_path.dirname is original_dirname
assert _test_patching.renamed_os.path.dirname is original_dirname
# check that everthing is back to normal when the patch is over
assert _test_patching.os is original_os
assert _test_patching.path is original_path
assert _test_patching.join is original_join
assert _test_patching.renamed_os is original_os
assert _test_patching.renamed_path is original_path
assert _test_patching.renamed_join is original_join
def __lowercase () -> str:
"""simple docstring"""
assert _test_patching.open is open
__lowerCamelCase : List[str] = """__test_patch_submodule_builtin_mock__"""
# _test_patching has "open" in its globals
assert _test_patching.open is open
with patch_submodule(_test_patching, """open""", _lowercase ):
assert _test_patching.open is mock
# check that everthing is back to normal when the patch is over
assert _test_patching.open is open
def __lowercase () -> Dict:
"""simple docstring"""
# pandas.read_csv is not present in _test_patching
__lowerCamelCase : List[str] = """__test_patch_submodule_missing_mock__"""
with patch_submodule(_test_patching, """pandas.read_csv""", _lowercase ):
pass
def __lowercase () -> Union[str, Any]:
"""simple docstring"""
# builtin should always be mocked even if they're not in the globals
# in case they're loaded at one point
__lowerCamelCase : Tuple = """__test_patch_submodule_missing_builtin_mock__"""
# _test_patching doesn't have "len" in its globals
assert getattr(_test_patching, """len""", _lowercase ) is None
with patch_submodule(_test_patching, """len""", _lowercase ):
assert _test_patching.len is mock
assert _test_patching.len is len
def __lowercase () -> List[str]:
"""simple docstring"""
__lowerCamelCase : Union[str, Any] = """__test_patch_submodule_start_and_stop_mock__"""
__lowerCamelCase : Dict = patch_submodule(_test_patching, """open""", _lowercase )
assert _test_patching.open is open
patch.start()
assert _test_patching.open is mock
patch.stop()
assert _test_patching.open is open
def __lowercase () -> List[Any]:
"""simple docstring"""
from os import rename as original_rename
from os.path import dirname as original_dirname
from os.path import join as original_join
__lowerCamelCase : Dict = """__test_patch_submodule_successive_join__"""
__lowerCamelCase : List[str] = """__test_patch_submodule_successive_dirname__"""
__lowerCamelCase : Dict = """__test_patch_submodule_successive_rename__"""
assert _test_patching.os.path.join is original_join
assert _test_patching.os.path.dirname is original_dirname
assert _test_patching.os.rename is original_rename
with patch_submodule(_test_patching, """os.path.join""", _lowercase ):
with patch_submodule(_test_patching, """os.rename""", _lowercase ):
with patch_submodule(_test_patching, """os.path.dirname""", _lowercase ):
assert _test_patching.os.path.join is mock_join
assert _test_patching.os.path.dirname is mock_dirname
assert _test_patching.os.rename is mock_rename
# try another order
with patch_submodule(_test_patching, """os.rename""", _lowercase ):
with patch_submodule(_test_patching, """os.path.join""", _lowercase ):
with patch_submodule(_test_patching, """os.path.dirname""", _lowercase ):
assert _test_patching.os.path.join is mock_join
assert _test_patching.os.path.dirname is mock_dirname
assert _test_patching.os.rename is mock_rename
assert _test_patching.os.path.join is original_join
assert _test_patching.os.path.dirname is original_dirname
assert _test_patching.os.rename is original_rename
def __lowercase () -> List[Any]:
"""simple docstring"""
__lowerCamelCase : List[Any] = """__test_patch_submodule_doesnt_exist_mock__"""
with patch_submodule(_test_patching, """__module_that_doesn_exist__.__attribute_that_doesn_exist__""", _lowercase ):
pass
with patch_submodule(_test_patching, """os.__attribute_that_doesn_exist__""", _lowercase ):
pass
| 150 |
'''simple docstring'''
import copy
import os
from typing import Union
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCAmelCase__ :List[str] = logging.get_logger(__name__)
UpperCAmelCase__ :Union[str, Any] = {
"""BAAI/AltCLIP""": """https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json""",
# See all AltCLIP models at https://huggingface.co/models?filter=altclip
}
class SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ):
snake_case__ : str = 'altclip_text_model'
def __init__( self : List[Any] , A__ : Optional[int]=250002 , A__ : Any=1024 , A__ : List[Any]=24 , A__ : Dict=16 , A__ : Union[str, Any]=4096 , A__ : Union[str, Any]="gelu" , A__ : str=0.1 , A__ : int=0.1 , A__ : str=514 , A__ : Optional[int]=1 , A__ : Optional[Any]=0.02 , A__ : int=0.02 , A__ : Optional[Any]=1e-0_5 , A__ : int=1 , A__ : Optional[Any]=0 , A__ : Dict=2 , A__ : Optional[int]="absolute" , A__ : Optional[int]=True , A__ : List[str]=768 , **A__ : List[str] , ):
"""simple docstring"""
super().__init__(pad_token_id=A__ , bos_token_id=A__ , eos_token_id=A__ , **A__ )
__lowerCamelCase : List[str] = vocab_size
__lowerCamelCase : Optional[Any] = hidden_size
__lowerCamelCase : List[str] = num_hidden_layers
__lowerCamelCase : Tuple = num_attention_heads
__lowerCamelCase : List[Any] = hidden_act
__lowerCamelCase : Union[str, Any] = intermediate_size
__lowerCamelCase : Dict = hidden_dropout_prob
__lowerCamelCase : Any = attention_probs_dropout_prob
__lowerCamelCase : List[str] = max_position_embeddings
__lowerCamelCase : Optional[Any] = type_vocab_size
__lowerCamelCase : int = initializer_range
__lowerCamelCase : Optional[int] = initializer_factor
__lowerCamelCase : List[Any] = layer_norm_eps
__lowerCamelCase : List[str] = position_embedding_type
__lowerCamelCase : str = use_cache
__lowerCamelCase : Optional[Any] = project_dim
class SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ):
snake_case__ : List[Any] = 'altclip_vision_model'
def __init__( self : Optional[int] , A__ : str=768 , A__ : str=3072 , A__ : str=512 , A__ : Optional[int]=12 , A__ : List[Any]=12 , A__ : Union[str, Any]=3 , A__ : Dict=224 , A__ : List[Any]=32 , A__ : List[Any]="quick_gelu" , A__ : Dict=1e-5 , A__ : List[str]=0.0 , A__ : Dict=0.02 , A__ : List[str]=1.0 , **A__ : Union[str, Any] , ):
"""simple docstring"""
super().__init__(**A__ )
__lowerCamelCase : Optional[int] = hidden_size
__lowerCamelCase : Optional[int] = intermediate_size
__lowerCamelCase : Optional[Any] = projection_dim
__lowerCamelCase : Union[str, Any] = num_hidden_layers
__lowerCamelCase : Optional[Any] = num_attention_heads
__lowerCamelCase : str = num_channels
__lowerCamelCase : Any = patch_size
__lowerCamelCase : Any = image_size
__lowerCamelCase : Any = initializer_range
__lowerCamelCase : List[str] = initializer_factor
__lowerCamelCase : List[str] = attention_dropout
__lowerCamelCase : Any = layer_norm_eps
__lowerCamelCase : Any = hidden_act
@classmethod
def a_ ( cls : str , A__ : Union[str, os.PathLike] , **A__ : List[str] ):
"""simple docstring"""
cls._set_token_in_kwargs(A__ )
__lowerCamelCase , __lowerCamelCase : str = cls.get_config_dict(A__ , **A__ )
# get the vision config dict if we are loading from AltCLIPConfig
if config_dict.get("""model_type""" ) == "altclip":
__lowerCamelCase : Optional[Any] = config_dict["""vision_config"""]
if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type:
logger.warning(
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors." )
return cls.from_dict(A__ , **A__ )
class SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ):
snake_case__ : int = 'altclip'
snake_case__ : Dict = True
def __init__( self : Optional[Any] , A__ : Optional[Any]=None , A__ : Union[str, Any]=None , A__ : Union[str, Any]=768 , A__ : Tuple=2.6592 , **A__ : List[Any] ):
"""simple docstring"""
__lowerCamelCase : str = kwargs.pop("""text_config_dict""" , A__ )
__lowerCamelCase : Dict = kwargs.pop("""vision_config_dict""" , A__ )
super().__init__(**A__ )
# Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
# `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
# cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
if text_config_dict is not None:
if text_config is None:
__lowerCamelCase : Any = {}
# This is the complete result when using `text_config_dict`.
__lowerCamelCase : Tuple = AltCLIPTextConfig(**A__ ).to_dict()
# Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
for key, value in _text_config_dict.items():
if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
# If specified in `text_config_dict`
if key in text_config_dict:
__lowerCamelCase : Optional[Any] = (
f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
f"The value `text_config_dict[\"{key}\"]` will be used instead."
)
# If inferred from default argument values (just to be super careful)
else:
__lowerCamelCase : int = (
f"`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The "
f"value `text_config[\"{key}\"]` will be overriden."
)
logger.warning(A__ )
# Update all values in `text_config` with the ones in `_text_config_dict`.
text_config.update(_text_config_dict )
if vision_config_dict is not None:
if vision_config is None:
__lowerCamelCase : Dict = {}
# This is the complete result when using `vision_config_dict`.
__lowerCamelCase : List[str] = AltCLIPVisionConfig(**A__ ).to_dict()
# convert keys to string instead of integer
if "id2label" in _vision_config_dict:
__lowerCamelCase : str = {
str(A__ ): value for key, value in _vision_config_dict["""id2label"""].items()
}
# Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
for key, value in _vision_config_dict.items():
if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
# If specified in `vision_config_dict`
if key in vision_config_dict:
__lowerCamelCase : List[Any] = (
f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
f"values. The value `vision_config_dict[\"{key}\"]` will be used instead."
)
# If inferred from default argument values (just to be super careful)
else:
__lowerCamelCase : Optional[Any] = (
f"`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. "
f"The value `vision_config[\"{key}\"]` will be overriden."
)
logger.warning(A__ )
# Update all values in `vision_config` with the ones in `_vision_config_dict`.
vision_config.update(_vision_config_dict )
if text_config is None:
__lowerCamelCase : List[Any] = {}
logger.info("""`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.""" )
if vision_config is None:
__lowerCamelCase : List[str] = {}
logger.info("""`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.""" )
__lowerCamelCase : Union[str, Any] = AltCLIPTextConfig(**A__ )
__lowerCamelCase : Optional[int] = AltCLIPVisionConfig(**A__ )
__lowerCamelCase : Optional[Any] = projection_dim
__lowerCamelCase : List[str] = logit_scale_init_value
__lowerCamelCase : Union[str, Any] = 1.0
@classmethod
def a_ ( cls : Optional[Any] , A__ : AltCLIPTextConfig , A__ : AltCLIPVisionConfig , **A__ : List[str] ):
"""simple docstring"""
return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **A__ )
def a_ ( self : Optional[int] ):
"""simple docstring"""
__lowerCamelCase : List[Any] = copy.deepcopy(self.__dict__ )
__lowerCamelCase : Optional[Any] = self.text_config.to_dict()
__lowerCamelCase : Tuple = self.vision_config.to_dict()
__lowerCamelCase : Tuple = self.__class__.model_type
return output
| 150 | 1 |
import numpy as np
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__( self : List[Any] ):
SCREAMING_SNAKE_CASE = (0, 0)
SCREAMING_SNAKE_CASE = None
SCREAMING_SNAKE_CASE = 0
SCREAMING_SNAKE_CASE = 0
SCREAMING_SNAKE_CASE = 0
def __eq__( self : List[str] , __lowerCamelCase : str ):
return self.position == cell.position
def _snake_case ( self : Optional[int] ):
print(self.position )
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__( self : Union[str, Any] , __lowerCamelCase : Tuple=(5, 5) ):
SCREAMING_SNAKE_CASE = np.zeros(__lowerCamelCase )
SCREAMING_SNAKE_CASE = world_size[0]
SCREAMING_SNAKE_CASE = world_size[1]
def _snake_case ( self : Optional[int] ):
print(self.w )
def _snake_case ( self : int , __lowerCamelCase : Tuple ):
SCREAMING_SNAKE_CASE = [
(-1, -1),
(-1, 0),
(-1, 1),
(0, -1),
(0, 1),
(1, -1),
(1, 0),
(1, 1),
]
SCREAMING_SNAKE_CASE = cell.position[0]
SCREAMING_SNAKE_CASE = cell.position[1]
SCREAMING_SNAKE_CASE = []
for n in neughbour_cord:
SCREAMING_SNAKE_CASE = current_x + n[0]
SCREAMING_SNAKE_CASE = current_y + n[1]
if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit:
SCREAMING_SNAKE_CASE = Cell()
SCREAMING_SNAKE_CASE = (x, y)
SCREAMING_SNAKE_CASE = cell
neighbours.append(__lowerCamelCase )
return neighbours
def __a ( A__ : Optional[int] , A__ : Union[str, Any] , A__ : int ):
SCREAMING_SNAKE_CASE = []
SCREAMING_SNAKE_CASE = []
_open.append(A__ )
while _open:
SCREAMING_SNAKE_CASE = np.argmin([n.f for n in _open] )
SCREAMING_SNAKE_CASE = _open[min_f]
_closed.append(_open.pop(A__ ) )
if current == goal:
break
for n in world.get_neigbours(A__ ):
for c in _closed:
if c == n:
continue
SCREAMING_SNAKE_CASE = current.g + 1
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = n.position
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = goal.position
SCREAMING_SNAKE_CASE = (ya - ya) ** 2 + (xa - xa) ** 2
SCREAMING_SNAKE_CASE = n.h + n.g
for c in _open:
if c == n and c.f < n.f:
continue
_open.append(A__ )
SCREAMING_SNAKE_CASE = []
while current.parent is not None:
path.append(current.position )
SCREAMING_SNAKE_CASE = current.parent
path.append(current.position )
return path[::-1]
if __name__ == "__main__":
__A : int = Gridworld()
# Start position and goal
__A : List[Any] = Cell()
__A : Optional[int] = (0, 0)
__A : List[Any] = Cell()
__A : Optional[Any] = (4, 4)
print(f'path from {start.position} to {goal.position}')
__A : Optional[int] = astar(world, start, goal)
# Just for visual reasons.
for i in s:
__A : Optional[int] = 1
print(world.w)
| 715 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available
__A : Any = {
'configuration_longt5': ['LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LongT5Config', 'LongT5OnnxConfig'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A : List[str] = [
'LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST',
'LongT5EncoderModel',
'LongT5ForConditionalGeneration',
'LongT5Model',
'LongT5PreTrainedModel',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A : List[Any] = [
'FlaxLongT5ForConditionalGeneration',
'FlaxLongT5Model',
'FlaxLongT5PreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_longta import LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP, LongTaConfig, LongTaOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_longta import (
LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST,
LongTaEncoderModel,
LongTaForConditionalGeneration,
LongTaModel,
LongTaPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_longta import (
FlaxLongTaForConditionalGeneration,
FlaxLongTaModel,
FlaxLongTaPreTrainedModel,
)
else:
import sys
__A : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 698 | 0 |
from __future__ import annotations
import math
_lowerCAmelCase = "2020.9.26"
_lowerCAmelCase = "xcodz-dot, cclaus, dhruvmanila"
def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ):
if not all(isinstance(__snake_case , (float, int) ) for val in locals().values() ):
_UpperCamelCase = f"""Input values must either be float or int: {list(locals().values() )}"""
raise TypeError(__snake_case )
_UpperCamelCase = ((x * distance) / (z + distance)) * scale
_UpperCamelCase = ((y * distance) / (z + distance)) * scale
return projected_x, projected_y
def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ):
if not isinstance(__snake_case , __snake_case ):
raise TypeError('''Axis must be a str''' )
_UpperCamelCase = locals()
del input_variables["axis"]
if not all(isinstance(__snake_case , (float, int) ) for val in input_variables.values() ):
_UpperCamelCase = (
'''Input values except axis must either be float or int: '''
f"""{list(input_variables.values() )}"""
)
raise TypeError(__snake_case )
_UpperCamelCase = (angle % 360) / 450 * 180 / math.pi
if axis == "z":
_UpperCamelCase = x * math.cos(__snake_case ) - y * math.sin(__snake_case )
_UpperCamelCase = y * math.cos(__snake_case ) + x * math.sin(__snake_case )
_UpperCamelCase = z
elif axis == "x":
_UpperCamelCase = y * math.cos(__snake_case ) - z * math.sin(__snake_case )
_UpperCamelCase = z * math.cos(__snake_case ) + y * math.sin(__snake_case )
_UpperCamelCase = x
elif axis == "y":
_UpperCamelCase = x * math.cos(__snake_case ) - z * math.sin(__snake_case )
_UpperCamelCase = z * math.cos(__snake_case ) + x * math.sin(__snake_case )
_UpperCamelCase = y
else:
raise ValueError('''not a valid axis, choose one of \'x\', \'y\', \'z\'''' )
return new_x, new_y, new_z
if __name__ == "__main__":
import doctest
doctest.testmod()
print(f'{convert_to_ad(1.0, 2.0, 3.0, 10.0, 10.0) = }')
print(f'{rotate(1.0, 2.0, 3.0, "y", 90.0) = }')
| 10 |
from __future__ import annotations
import math
import random
from collections.abc import Collection
from typing import overload
class _UpperCAmelCase :
'''simple docstring'''
def __init__( self : List[Any] , UpperCamelCase__ : Collection[float] | None = None ):
if components is None:
A = []
A = list(UpperCamelCase__ )
def __len__( self : List[Any] ):
return len(self.__components )
def __str__( self : str ):
return "(" + ",".join(map(UpperCamelCase__ , self.__components ) ) + ")"
def __add__( self : str , UpperCamelCase__ : Vector ):
A = len(self )
if size == len(UpperCamelCase__ ):
A = [self.__components[i] + other.component(UpperCamelCase__ ) for i in range(UpperCamelCase__ )]
return Vector(UpperCamelCase__ )
else:
raise Exception('must have the same size' )
def __sub__( self : Dict , UpperCamelCase__ : Vector ):
A = len(self )
if size == len(UpperCamelCase__ ):
A = [self.__components[i] - other.component(UpperCamelCase__ ) for i in range(UpperCamelCase__ )]
return Vector(UpperCamelCase__ )
else: # error case
raise Exception('must have the same size' )
@overload
def __mul__( self : Tuple , UpperCamelCase__ : float ):
...
@overload
def __mul__( self : Dict , UpperCamelCase__ : Vector ):
...
def __mul__( self : Union[str, Any] , UpperCamelCase__ : float | Vector ):
if isinstance(UpperCamelCase__ , (float, int) ):
A = [c * other for c in self.__components]
return Vector(UpperCamelCase__ )
elif isinstance(UpperCamelCase__ , UpperCamelCase__ ) and len(self ) == len(UpperCamelCase__ ):
A = len(self )
A = [self.__components[i] * other.component(UpperCamelCase__ ) for i in range(UpperCamelCase__ )]
return sum(UpperCamelCase__ )
else: # error case
raise Exception('invalid operand!' )
def UpperCamelCase ( self : Union[str, Any] ):
return Vector(self.__components )
def UpperCamelCase ( self : Optional[Any] , UpperCamelCase__ : int ):
if isinstance(UpperCamelCase__ , UpperCamelCase__ ) and -len(self.__components ) <= i < len(self.__components ):
return self.__components[i]
else:
raise Exception('index out of range' )
def UpperCamelCase ( self : Any , UpperCamelCase__ : int , UpperCamelCase__ : float ):
assert -len(self.__components ) <= pos < len(self.__components )
A = value
def UpperCamelCase ( self : str ):
if len(self.__components ) == 0:
raise Exception('Vector is empty' )
A = [c**2 for c in self.__components]
return math.sqrt(sum(UpperCamelCase__ ) )
def UpperCamelCase ( self : Any , UpperCamelCase__ : Vector , UpperCamelCase__ : bool = False ):
A = self * other
A = self.euclidean_length() * other.euclidean_length()
if deg:
return math.degrees(math.acos(num / den ) )
else:
return math.acos(num / den )
def __UpperCamelCase (lowerCAmelCase : int ) -> Vector:
assert isinstance(lowerCAmelCase, lowerCAmelCase )
return Vector([0] * dimension )
def __UpperCamelCase (lowerCAmelCase : int, lowerCAmelCase : int ) -> Vector:
assert isinstance(lowerCAmelCase, lowerCAmelCase ) and (isinstance(lowerCAmelCase, lowerCAmelCase ))
A = [0] * dimension
A = 1
return Vector(lowerCAmelCase )
def __UpperCamelCase (lowerCAmelCase : float, lowerCAmelCase : Vector, lowerCAmelCase : Vector ) -> Vector:
assert (
isinstance(lowerCAmelCase, lowerCAmelCase )
and isinstance(lowerCAmelCase, lowerCAmelCase )
and (isinstance(lowerCAmelCase, (int, float) ))
)
return x * scalar + y
def __UpperCamelCase (lowerCAmelCase : int, lowerCAmelCase : int, lowerCAmelCase : int ) -> Vector:
random.seed(lowerCAmelCase )
A = [random.randint(lowerCAmelCase, lowerCAmelCase ) for _ in range(lowerCAmelCase )]
return Vector(lowerCAmelCase )
class _UpperCAmelCase :
'''simple docstring'''
def __init__( self : List[str] , UpperCamelCase__ : list[list[float]] , UpperCamelCase__ : int , UpperCamelCase__ : int ):
A = matrix
A = w
A = h
def __str__( self : int ):
A = ''
for i in range(self.__height ):
ans += "|"
for j in range(self.__width ):
if j < self.__width - 1:
ans += str(self.__matrix[i][j] ) + ","
else:
ans += str(self.__matrix[i][j] ) + "|\n"
return ans
def __add__( self : Optional[Any] , UpperCamelCase__ : Matrix ):
if self.__width == other.width() and self.__height == other.height():
A = []
for i in range(self.__height ):
A = [
self.__matrix[i][j] + other.component(UpperCamelCase__ , UpperCamelCase__ )
for j in range(self.__width )
]
matrix.append(UpperCamelCase__ )
return Matrix(UpperCamelCase__ , self.__width , self.__height )
else:
raise Exception('matrix must have the same dimension!' )
def __sub__( self : Dict , UpperCamelCase__ : Matrix ):
if self.__width == other.width() and self.__height == other.height():
A = []
for i in range(self.__height ):
A = [
self.__matrix[i][j] - other.component(UpperCamelCase__ , UpperCamelCase__ )
for j in range(self.__width )
]
matrix.append(UpperCamelCase__ )
return Matrix(UpperCamelCase__ , self.__width , self.__height )
else:
raise Exception('matrices must have the same dimension!' )
@overload
def __mul__( self : int , UpperCamelCase__ : float ):
...
@overload
def __mul__( self : Union[str, Any] , UpperCamelCase__ : Vector ):
...
def __mul__( self : Tuple , UpperCamelCase__ : float | Vector ):
if isinstance(UpperCamelCase__ , UpperCamelCase__ ): # matrix-vector
if len(UpperCamelCase__ ) == self.__width:
A = zero_vector(self.__height )
for i in range(self.__height ):
A = [
self.__matrix[i][j] * other.component(UpperCamelCase__ )
for j in range(self.__width )
]
ans.change_component(UpperCamelCase__ , sum(UpperCamelCase__ ) )
return ans
else:
raise Exception(
'vector must have the same size as the '
'number of columns of the matrix!' )
elif isinstance(UpperCamelCase__ , (int, float) ): # matrix-scalar
A = [
[self.__matrix[i][j] * other for j in range(self.__width )]
for i in range(self.__height )
]
return Matrix(UpperCamelCase__ , self.__width , self.__height )
return None
def UpperCamelCase ( self : Optional[int] ):
return self.__height
def UpperCamelCase ( self : List[Any] ):
return self.__width
def UpperCamelCase ( self : List[str] , UpperCamelCase__ : int , UpperCamelCase__ : int ):
if 0 <= x < self.__height and 0 <= y < self.__width:
return self.__matrix[x][y]
else:
raise Exception('change_component: indices out of bounds' )
def UpperCamelCase ( self : str , UpperCamelCase__ : int , UpperCamelCase__ : int , UpperCamelCase__ : float ):
if 0 <= x < self.__height and 0 <= y < self.__width:
A = value
else:
raise Exception('change_component: indices out of bounds' )
def UpperCamelCase ( self : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : int ):
if self.__height != self.__width:
raise Exception('Matrix is not square' )
A = self.__matrix[:x] + self.__matrix[x + 1 :]
for i in range(len(UpperCamelCase__ ) ):
A = minor[i][:y] + minor[i][y + 1 :]
return Matrix(UpperCamelCase__ , self.__width - 1 , self.__height - 1 ).determinant()
def UpperCamelCase ( self : str , UpperCamelCase__ : int , UpperCamelCase__ : int ):
if self.__height != self.__width:
raise Exception('Matrix is not square' )
if 0 <= x < self.__height and 0 <= y < self.__width:
return (-1) ** (x + y) * self.minor(UpperCamelCase__ , UpperCamelCase__ )
else:
raise Exception('Indices out of bounds' )
def UpperCamelCase ( self : Tuple ):
if self.__height != self.__width:
raise Exception('Matrix is not square' )
if self.__height < 1:
raise Exception('Matrix has no element' )
elif self.__height == 1:
return self.__matrix[0][0]
elif self.__height == 2:
return (
self.__matrix[0][0] * self.__matrix[1][1]
- self.__matrix[0][1] * self.__matrix[1][0]
)
else:
A = [
self.__matrix[0][y] * self.cofactor(0 , UpperCamelCase__ ) for y in range(self.__width )
]
return sum(UpperCamelCase__ )
def __UpperCamelCase (lowerCAmelCase : int ) -> Matrix:
A = [[0] * n for _ in range(lowerCAmelCase )]
return Matrix(lowerCAmelCase, lowerCAmelCase, lowerCAmelCase )
def __UpperCamelCase (lowerCAmelCase : int, lowerCAmelCase : int, lowerCAmelCase : int, lowerCAmelCase : int ) -> Matrix:
random.seed(lowerCAmelCase )
A = [
[random.randint(lowerCAmelCase, lowerCAmelCase ) for _ in range(lowerCAmelCase )] for _ in range(lowerCAmelCase )
]
return Matrix(lowerCAmelCase, lowerCAmelCase, lowerCAmelCase )
| 699 | 0 |
import copy
from dataclasses import dataclass, field
from typing import ClassVar, Dict
from ..features import ClassLabel, Features, Value
from .base import TaskTemplate
@dataclass(frozen=_A )
class _lowercase ( _A ):
# `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization
_a : str = field(default='text-classification' , metadata={'include_in_asdict_even_if_is_default': True} )
_a : ClassVar[Features] = Features({'text': Value('string' )} )
_a : ClassVar[Features] = Features({'labels': ClassLabel} )
_a : str = "text"
_a : str = "labels"
def lowercase__ ( self , a ):
if self.label_column not in features:
raise ValueError(F"Column {self.label_column} is not present in features." )
if not isinstance(features[self.label_column] , a ):
raise ValueError(F"Column {self.label_column} is not a ClassLabel." )
snake_case__ : List[str] =copy.deepcopy(self )
snake_case__ : Any =self.label_schema.copy()
snake_case__ : Dict =features[self.label_column]
snake_case__ : str =label_schema
return task_template
@property
def lowercase__ ( self ):
return {
self.text_column: "text",
self.label_column: "labels",
}
| 448 |
import argparse
from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird
from transformers.utils import logging
logging.set_verbosity_info()
def A__ ( _a : int , _a : Any , _a : Union[str, Any] , _a : Tuple ):
'''simple docstring'''
snake_case__ : Any =BigBirdConfig.from_json_file(_a )
print(f"Building PyTorch model from configuration: {config}" )
if is_trivia_qa:
snake_case__ : str =BigBirdForQuestionAnswering(_a )
else:
snake_case__ : Optional[int] =BigBirdForPreTraining(_a )
# Load weights from tf checkpoint
load_tf_weights_in_big_bird(_a , _a , is_trivia_qa=_a )
# Save pytorch-model
print(f"Save PyTorch model to {pytorch_dump_path}" )
model.save_pretrained(_a )
if __name__ == "__main__":
__lowerCamelCase : Union[str, Any] = 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(
"""--big_bird_config_file""",
default=None,
type=str,
required=True,
help=(
"""The config json file corresponding to the pre-trained BERT 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."""
)
parser.add_argument(
"""--is_trivia_qa""", action="""store_true""", help="""Whether to convert a model with a trivia_qa head."""
)
__lowerCamelCase : Tuple = parser.parse_args()
convert_tf_checkpoint_to_pytorch(
args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa
)
| 448 | 1 |
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 : Any = logging.get_logger(__name__)
__a : str = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""}
# See all BART models at https://huggingface.co/models?filter=bart
__a : List[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_0_2_4,
"""facebook/bart-large""": 1_0_2_4,
"""facebook/bart-large-mnli""": 1_0_2_4,
"""facebook/bart-large-cnn""": 1_0_2_4,
"""facebook/bart-large-xsum""": 1_0_2_4,
"""yjernite/bart_eli5""": 1_0_2_4,
}
class __UpperCAmelCase ( snake_case__ ):
"""simple docstring"""
lowercase = VOCAB_FILES_NAMES
lowercase = PRETRAINED_VOCAB_FILES_MAP
lowercase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowercase = ["""input_ids""", """attention_mask"""]
lowercase = BartTokenizer
def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE="replace" , SCREAMING_SNAKE_CASE="<s>" , SCREAMING_SNAKE_CASE="</s>" , SCREAMING_SNAKE_CASE="</s>" , SCREAMING_SNAKE_CASE="<s>" , SCREAMING_SNAKE_CASE="<unk>" , SCREAMING_SNAKE_CASE="<pad>" , SCREAMING_SNAKE_CASE="<mask>" , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , **SCREAMING_SNAKE_CASE , ) -> Optional[Any]:
"""simple docstring"""
super().__init__(
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , tokenizer_file=SCREAMING_SNAKE_CASE , errors=SCREAMING_SNAKE_CASE , bos_token=SCREAMING_SNAKE_CASE , eos_token=SCREAMING_SNAKE_CASE , sep_token=SCREAMING_SNAKE_CASE , cls_token=SCREAMING_SNAKE_CASE , unk_token=SCREAMING_SNAKE_CASE , pad_token=SCREAMING_SNAKE_CASE , mask_token=SCREAMING_SNAKE_CASE , add_prefix_space=SCREAMING_SNAKE_CASE , trim_offsets=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , )
UpperCamelCase = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
if pre_tok_state.get("add_prefix_space" , SCREAMING_SNAKE_CASE ) != add_prefix_space:
UpperCamelCase = getattr(SCREAMING_SNAKE_CASE , pre_tok_state.pop("type" ) )
UpperCamelCase = add_prefix_space
UpperCamelCase = pre_tok_class(**SCREAMING_SNAKE_CASE )
UpperCamelCase = add_prefix_space
# the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
UpperCamelCase = "post_processor"
UpperCamelCase = getattr(self.backend_tokenizer , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
if tokenizer_component_instance:
UpperCamelCase = json.loads(tokenizer_component_instance.__getstate__() )
# The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
if "sep" in state:
UpperCamelCase = tuple(state["sep"] )
if "cls" in state:
UpperCamelCase = tuple(state["cls"] )
UpperCamelCase = False
if state.get("add_prefix_space" , SCREAMING_SNAKE_CASE ) != add_prefix_space:
UpperCamelCase = add_prefix_space
UpperCamelCase = True
if state.get("trim_offsets" , SCREAMING_SNAKE_CASE ) != trim_offsets:
UpperCamelCase = trim_offsets
UpperCamelCase = True
if changes_to_apply:
UpperCamelCase = getattr(SCREAMING_SNAKE_CASE , state.pop("type" ) )
UpperCamelCase = component_class(**SCREAMING_SNAKE_CASE )
setattr(self.backend_tokenizer , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
@property
def __lowerCAmelCase ( self ) -> str:
"""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 __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> List[Any]:
"""simple docstring"""
UpperCamelCase = AddedToken(SCREAMING_SNAKE_CASE , lstrip=SCREAMING_SNAKE_CASE , rstrip=SCREAMING_SNAKE_CASE ) if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else value
UpperCamelCase = value
def __lowerCAmelCase ( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> BatchEncoding:
"""simple docstring"""
UpperCamelCase = kwargs.get("is_split_into_words" , SCREAMING_SNAKE_CASE )
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
"to use it with pretokenized inputs." )
return super()._batch_encode_plus(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
def __lowerCAmelCase ( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> BatchEncoding:
"""simple docstring"""
UpperCamelCase = kwargs.get("is_split_into_words" , SCREAMING_SNAKE_CASE )
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
"to use it with pretokenized inputs." )
return super()._encode_plus(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None ) -> Tuple[str]:
"""simple docstring"""
UpperCamelCase = self._tokenizer.model.save(SCREAMING_SNAKE_CASE , name=SCREAMING_SNAKE_CASE )
return tuple(SCREAMING_SNAKE_CASE )
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None ) -> List[Any]:
"""simple docstring"""
UpperCamelCase = [self.bos_token_id] + token_ids_a + [self.eos_token_id]
if token_ids_a is None:
return output
return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None ) -> List[int]:
"""simple docstring"""
UpperCamelCase = [self.sep_token_id]
UpperCamelCase = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
| 606 |
from copy import deepcopy
from typing import Optional, Union
import numpy as np
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, is_tf_available, is_torch_available
if is_torch_available():
import torch
if is_tf_available():
import tensorflow as tf
class __UpperCAmelCase ( snake_case__ ):
"""simple docstring"""
lowercase = ["""image_processor"""]
lowercase = """SamImageProcessor"""
def __init__( self , SCREAMING_SNAKE_CASE ) -> int:
"""simple docstring"""
super().__init__(SCREAMING_SNAKE_CASE )
UpperCamelCase = self.image_processor
UpperCamelCase = -10
UpperCamelCase = self.image_processor.size["longest_edge"]
def __call__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE , ) -> BatchEncoding:
"""simple docstring"""
UpperCamelCase = self.image_processor(
SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , )
# pop arguments that are not used in the foward but used nevertheless
UpperCamelCase = encoding_image_processor["original_sizes"]
if hasattr(SCREAMING_SNAKE_CASE , "numpy" ): # Checks if Torch or TF tensor
UpperCamelCase = original_sizes.numpy()
UpperCamelCase , UpperCamelCase , UpperCamelCase = self._check_and_preprocess_points(
input_points=SCREAMING_SNAKE_CASE , input_labels=SCREAMING_SNAKE_CASE , input_boxes=SCREAMING_SNAKE_CASE , )
UpperCamelCase = self._normalize_and_convert(
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , input_points=SCREAMING_SNAKE_CASE , input_labels=SCREAMING_SNAKE_CASE , input_boxes=SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , )
return encoding_image_processor
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE="pt" , ) -> int:
"""simple docstring"""
if input_points is not None:
if len(SCREAMING_SNAKE_CASE ) != len(SCREAMING_SNAKE_CASE ):
UpperCamelCase = [
self._normalize_coordinates(self.target_size , SCREAMING_SNAKE_CASE , original_sizes[0] ) for point in input_points
]
else:
UpperCamelCase = [
self._normalize_coordinates(self.target_size , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
for point, original_size in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
]
# check that all arrays have the same shape
if not all(point.shape == input_points[0].shape for point in input_points ):
if input_labels is not None:
UpperCamelCase , UpperCamelCase = self._pad_points_and_labels(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
UpperCamelCase = np.array(SCREAMING_SNAKE_CASE )
if input_labels is not None:
UpperCamelCase = np.array(SCREAMING_SNAKE_CASE )
if input_boxes is not None:
if len(SCREAMING_SNAKE_CASE ) != len(SCREAMING_SNAKE_CASE ):
UpperCamelCase = [
self._normalize_coordinates(self.target_size , SCREAMING_SNAKE_CASE , original_sizes[0] , is_bounding_box=SCREAMING_SNAKE_CASE )
for box in input_boxes
]
else:
UpperCamelCase = [
self._normalize_coordinates(self.target_size , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , is_bounding_box=SCREAMING_SNAKE_CASE )
for box, original_size in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
]
UpperCamelCase = np.array(SCREAMING_SNAKE_CASE )
if input_boxes is not None:
if return_tensors == "pt":
UpperCamelCase = torch.from_numpy(SCREAMING_SNAKE_CASE )
# boxes batch size of 1 by default
UpperCamelCase = input_boxes.unsqueeze(1 ) if len(input_boxes.shape ) != 3 else input_boxes
elif return_tensors == "tf":
UpperCamelCase = tf.convert_to_tensor(SCREAMING_SNAKE_CASE )
# boxes batch size of 1 by default
UpperCamelCase = tf.expand_dims(SCREAMING_SNAKE_CASE , 1 ) if len(input_boxes.shape ) != 3 else input_boxes
encoding_image_processor.update({"input_boxes": input_boxes} )
if input_points is not None:
if return_tensors == "pt":
UpperCamelCase = torch.from_numpy(SCREAMING_SNAKE_CASE )
# point batch size of 1 by default
UpperCamelCase = input_points.unsqueeze(1 ) if len(input_points.shape ) != 4 else input_points
elif return_tensors == "tf":
UpperCamelCase = tf.convert_to_tensor(SCREAMING_SNAKE_CASE )
# point batch size of 1 by default
UpperCamelCase = tf.expand_dims(SCREAMING_SNAKE_CASE , 1 ) if len(input_points.shape ) != 4 else input_points
encoding_image_processor.update({"input_points": input_points} )
if input_labels is not None:
if return_tensors == "pt":
UpperCamelCase = torch.from_numpy(SCREAMING_SNAKE_CASE )
# point batch size of 1 by default
UpperCamelCase = input_labels.unsqueeze(1 ) if len(input_labels.shape ) != 3 else input_labels
elif return_tensors == "tf":
UpperCamelCase = tf.convert_to_tensor(SCREAMING_SNAKE_CASE )
# point batch size of 1 by default
UpperCamelCase = tf.expand_dims(SCREAMING_SNAKE_CASE , 1 ) if len(input_labels.shape ) != 3 else input_labels
encoding_image_processor.update({"input_labels": input_labels} )
return encoding_image_processor
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]:
"""simple docstring"""
UpperCamelCase = max([point.shape[0] for point in input_points] )
UpperCamelCase = []
for i, point in enumerate(SCREAMING_SNAKE_CASE ):
if point.shape[0] != expected_nb_points:
UpperCamelCase = np.concatenate(
[point, np.zeros((expected_nb_points - point.shape[0], 2) ) + self.point_pad_value] , axis=0 )
UpperCamelCase = np.append(input_labels[i] , [self.point_pad_value] )
processed_input_points.append(SCREAMING_SNAKE_CASE )
UpperCamelCase = processed_input_points
return input_points, input_labels
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False ) -> np.ndarray:
"""simple docstring"""
UpperCamelCase , UpperCamelCase = original_size
UpperCamelCase , UpperCamelCase = self.image_processor._get_preprocess_shape(SCREAMING_SNAKE_CASE , longest_edge=SCREAMING_SNAKE_CASE )
UpperCamelCase = deepcopy(SCREAMING_SNAKE_CASE ).astype(SCREAMING_SNAKE_CASE )
if is_bounding_box:
UpperCamelCase = coords.reshape(-1 , 2 , 2 )
UpperCamelCase = coords[..., 0] * (new_w / old_w)
UpperCamelCase = coords[..., 1] * (new_h / old_h)
if is_bounding_box:
UpperCamelCase = coords.reshape(-1 , 4 )
return coords
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , ) -> Any:
"""simple docstring"""
if input_points is not None:
if hasattr(SCREAMING_SNAKE_CASE , "numpy" ): # Checks for TF or Torch tensor
UpperCamelCase = input_points.numpy().tolist()
if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) or not isinstance(input_points[0] , SCREAMING_SNAKE_CASE ):
raise ValueError("Input points must be a list of list of floating points." )
UpperCamelCase = [np.array(SCREAMING_SNAKE_CASE ) for input_point in input_points]
else:
UpperCamelCase = None
if input_labels is not None:
if hasattr(SCREAMING_SNAKE_CASE , "numpy" ):
UpperCamelCase = input_labels.numpy().tolist()
if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) or not isinstance(input_labels[0] , SCREAMING_SNAKE_CASE ):
raise ValueError("Input labels must be a list of list integers." )
UpperCamelCase = [np.array(SCREAMING_SNAKE_CASE ) for label in input_labels]
else:
UpperCamelCase = None
if input_boxes is not None:
if hasattr(SCREAMING_SNAKE_CASE , "numpy" ):
UpperCamelCase = input_boxes.numpy().tolist()
if (
not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
or not isinstance(input_boxes[0] , SCREAMING_SNAKE_CASE )
or not isinstance(input_boxes[0][0] , SCREAMING_SNAKE_CASE )
):
raise ValueError("Input boxes must be a list of list of list of floating points." )
UpperCamelCase = [np.array(SCREAMING_SNAKE_CASE ).astype(np.floataa ) for box in input_boxes]
else:
UpperCamelCase = None
return input_points, input_labels, input_boxes
@property
def __lowerCAmelCase ( self ) -> int:
"""simple docstring"""
UpperCamelCase = self.image_processor.model_input_names
return list(dict.fromkeys(SCREAMING_SNAKE_CASE ) )
def __lowerCAmelCase ( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Optional[int]:
"""simple docstring"""
return self.image_processor.post_process_masks(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
| 606 | 1 |
import unittest
from transformers import DebertaVaConfig, 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 (
DebertaVaForMaskedLM,
DebertaVaForMultipleChoice,
DebertaVaForQuestionAnswering,
DebertaVaForSequenceClassification,
DebertaVaForTokenClassification,
DebertaVaModel,
)
from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST
class lowerCamelCase__ ( _snake_case ):
def __init__( self : int , lowercase__ : List[str] , lowercase__ : Optional[int]=13 , lowercase__ : Optional[Any]=7 , lowercase__ : List[Any]=True , lowercase__ : int=True , lowercase__ : Dict=True , lowercase__ : Optional[int]=True , lowercase__ : Optional[int]=99 , lowercase__ : Tuple=32 , lowercase__ : List[str]=5 , lowercase__ : int=4 , lowercase__ : Optional[Any]=37 , lowercase__ : List[Any]="gelu" , lowercase__ : Any=0.1 , lowercase__ : int=0.1 , lowercase__ : Optional[Any]=5_12 , lowercase__ : Optional[int]=16 , lowercase__ : str=2 , lowercase__ : Union[str, Any]=0.0_2 , lowercase__ : int=False , lowercase__ : Dict=True , lowercase__ : Any="None" , lowercase__ : Optional[int]=3 , lowercase__ : List[str]=4 , lowercase__ : Union[str, Any]=None , ):
_lowerCAmelCase = parent
_lowerCAmelCase = batch_size
_lowerCAmelCase = seq_length
_lowerCAmelCase = is_training
_lowerCAmelCase = use_input_mask
_lowerCAmelCase = use_token_type_ids
_lowerCAmelCase = use_labels
_lowerCAmelCase = vocab_size
_lowerCAmelCase = hidden_size
_lowerCAmelCase = num_hidden_layers
_lowerCAmelCase = num_attention_heads
_lowerCAmelCase = intermediate_size
_lowerCAmelCase = hidden_act
_lowerCAmelCase = hidden_dropout_prob
_lowerCAmelCase = attention_probs_dropout_prob
_lowerCAmelCase = max_position_embeddings
_lowerCAmelCase = type_vocab_size
_lowerCAmelCase = type_sequence_label_size
_lowerCAmelCase = initializer_range
_lowerCAmelCase = num_labels
_lowerCAmelCase = num_choices
_lowerCAmelCase = relative_attention
_lowerCAmelCase = position_biased_input
_lowerCAmelCase = pos_att_type
_lowerCAmelCase = scope
def SCREAMING_SNAKE_CASE__ ( self : Dict ):
_lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
_lowerCAmelCase = None
if self.use_input_mask:
_lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 )
_lowerCAmelCase = None
if self.use_token_type_ids:
_lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
_lowerCAmelCase = None
_lowerCAmelCase = None
_lowerCAmelCase = None
if self.use_labels:
_lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size )
_lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
_lowerCAmelCase = ids_tensor([self.batch_size] , self.num_choices )
_lowerCAmelCase = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ):
return 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 , 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 SCREAMING_SNAKE_CASE__ ( self : List[Any] , lowercase__ : List[str] ):
self.parent.assertListEqual(list(result.loss.size() ) , [] )
def SCREAMING_SNAKE_CASE__ ( self : str , lowercase__ : Dict , lowercase__ : Optional[int] , lowercase__ : Tuple , lowercase__ : Dict , lowercase__ : Tuple , lowercase__ : Union[str, Any] , lowercase__ : Union[str, Any] ):
_lowerCAmelCase = DebertaVaModel(config=lowercase__ )
model.to(lowercase__ )
model.eval()
_lowerCAmelCase = model(lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ )[0]
_lowerCAmelCase = model(lowercase__ , token_type_ids=lowercase__ )[0]
_lowerCAmelCase = model(lowercase__ )[0]
self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] )
def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , lowercase__ : Any , lowercase__ : List[Any] , lowercase__ : List[Any] , lowercase__ : Any , lowercase__ : List[str] , lowercase__ : Any , lowercase__ : Optional[Any] ):
_lowerCAmelCase = DebertaVaForMaskedLM(config=lowercase__ )
model.to(lowercase__ )
model.eval()
_lowerCAmelCase = model(lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def SCREAMING_SNAKE_CASE__ ( self : List[Any] , lowercase__ : Optional[int] , lowercase__ : List[Any] , lowercase__ : Any , lowercase__ : Optional[int] , lowercase__ : int , lowercase__ : Optional[Any] , lowercase__ : List[Any] ):
_lowerCAmelCase = self.num_labels
_lowerCAmelCase = DebertaVaForSequenceClassification(lowercase__ )
model.to(lowercase__ )
model.eval()
_lowerCAmelCase = model(lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ )
self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] )
self.check_loss_output(lowercase__ )
def SCREAMING_SNAKE_CASE__ ( self : Any , lowercase__ : Dict , lowercase__ : Optional[int] , lowercase__ : List[Any] , lowercase__ : Tuple , lowercase__ : Dict , lowercase__ : List[Any] , lowercase__ : Optional[Any] ):
_lowerCAmelCase = self.num_labels
_lowerCAmelCase = DebertaVaForTokenClassification(config=lowercase__ )
model.to(lowercase__ )
model.eval()
_lowerCAmelCase = model(lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , lowercase__ : int , lowercase__ : Optional[int] , lowercase__ : Tuple , lowercase__ : Optional[int] , lowercase__ : Optional[int] , lowercase__ : Dict , lowercase__ : Tuple ):
_lowerCAmelCase = DebertaVaForQuestionAnswering(config=lowercase__ )
model.to(lowercase__ )
model.eval()
_lowerCAmelCase = model(
lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , start_positions=lowercase__ , end_positions=lowercase__ , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , lowercase__ : int , lowercase__ : Dict , lowercase__ : Optional[Any] , lowercase__ : int , lowercase__ : int , lowercase__ : Dict , lowercase__ : str ):
_lowerCAmelCase = DebertaVaForMultipleChoice(config=lowercase__ )
model.to(lowercase__ )
model.eval()
_lowerCAmelCase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
_lowerCAmelCase = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
_lowerCAmelCase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
_lowerCAmelCase = model(
lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def SCREAMING_SNAKE_CASE__ ( self : List[str] ):
_lowerCAmelCase = self.prepare_config_and_inputs()
(
(
_lowerCAmelCase
) , (
_lowerCAmelCase
) , (
_lowerCAmelCase
) , (
_lowerCAmelCase
) , (
_lowerCAmelCase
) , (
_lowerCAmelCase
) , (
_lowerCAmelCase
) ,
) = config_and_inputs
_lowerCAmelCase = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
return config, inputs_dict
@require_torch
class lowerCamelCase__ ( _snake_case ,_snake_case ,unittest.TestCase ):
UpperCamelCase__ =(
(
DebertaVaModel,
DebertaVaForMaskedLM,
DebertaVaForSequenceClassification,
DebertaVaForTokenClassification,
DebertaVaForQuestionAnswering,
DebertaVaForMultipleChoice,
)
if is_torch_available()
else ()
)
UpperCamelCase__ =(
{
'feature-extraction': DebertaVaModel,
'fill-mask': DebertaVaForMaskedLM,
'question-answering': DebertaVaForQuestionAnswering,
'text-classification': DebertaVaForSequenceClassification,
'token-classification': DebertaVaForTokenClassification,
'zero-shot': DebertaVaForSequenceClassification,
}
if is_torch_available()
else {}
)
UpperCamelCase__ =True
UpperCamelCase__ =False
UpperCamelCase__ =False
UpperCamelCase__ =False
UpperCamelCase__ =False
def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ):
_lowerCAmelCase = DebertaVaModelTester(self )
_lowerCAmelCase = ConfigTester(self , config_class=lowercase__ , hidden_size=37 )
def SCREAMING_SNAKE_CASE__ ( self : Dict ):
self.config_tester.run_common_tests()
def SCREAMING_SNAKE_CASE__ ( self : List[Any] ):
_lowerCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_model(*lowercase__ )
def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ):
_lowerCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_for_sequence_classification(*lowercase__ )
def SCREAMING_SNAKE_CASE__ ( self : List[Any] ):
_lowerCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_for_masked_lm(*lowercase__ )
def SCREAMING_SNAKE_CASE__ ( self : Any ):
_lowerCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_for_question_answering(*lowercase__ )
def SCREAMING_SNAKE_CASE__ ( self : int ):
_lowerCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_for_token_classification(*lowercase__ )
def SCREAMING_SNAKE_CASE__ ( self : List[Any] ):
_lowerCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_for_multiple_choice(*lowercase__ )
@slow
def SCREAMING_SNAKE_CASE__ ( self : Tuple ):
for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_lowerCAmelCase = DebertaVaModel.from_pretrained(lowercase__ )
self.assertIsNotNone(lowercase__ )
@require_torch
@require_sentencepiece
@require_tokenizers
class lowerCamelCase__ ( unittest.TestCase ):
@unittest.skip(reason='Model not available yet' )
def SCREAMING_SNAKE_CASE__ ( self : Dict ):
pass
@slow
def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ):
_lowerCAmelCase = DebertaVaModel.from_pretrained('microsoft/deberta-v2-xlarge' )
_lowerCAmelCase = torch.tensor([[0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2]] )
_lowerCAmelCase = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
with torch.no_grad():
_lowerCAmelCase = model(lowercase__ , attention_mask=lowercase__ )[0]
# compare the actual values for a slice.
_lowerCAmelCase = torch.tensor(
[[[0.2_3_5_6, 0.1_9_4_8, 0.0_3_6_9], [-0.1_0_6_3, 0.3_5_8_6, -0.5_1_5_2], [-0.6_3_9_9, -0.0_2_5_9, -0.2_5_2_5]]] )
self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , lowercase__ , atol=1e-4 ) , f'{output[:, 1:4, 1:4]}' )
| 713 |
import unittest
from transformers import AutoTokenizer, NystromformerConfig, 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 (
NystromformerForMaskedLM,
NystromformerForMultipleChoice,
NystromformerForQuestionAnswering,
NystromformerForSequenceClassification,
NystromformerForTokenClassification,
NystromformerModel,
)
from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST
class lowerCamelCase__ :
def __init__( self : int , lowercase__ : Tuple , lowercase__ : Union[str, Any]=13 , lowercase__ : Optional[Any]=7 , lowercase__ : List[str]=True , lowercase__ : Any=True , lowercase__ : int=True , lowercase__ : Tuple=True , lowercase__ : str=99 , lowercase__ : Optional[Any]=32 , lowercase__ : Dict=5 , lowercase__ : Tuple=4 , lowercase__ : Optional[Any]=37 , lowercase__ : Tuple="gelu" , lowercase__ : List[str]=0.1 , lowercase__ : Union[str, Any]=0.1 , lowercase__ : Union[str, Any]=5_12 , lowercase__ : Optional[Any]=16 , lowercase__ : int=2 , lowercase__ : Union[str, Any]=0.0_2 , lowercase__ : Optional[int]=3 , lowercase__ : List[str]=4 , lowercase__ : Any=None , ):
_lowerCAmelCase = parent
_lowerCAmelCase = batch_size
_lowerCAmelCase = seq_length
_lowerCAmelCase = is_training
_lowerCAmelCase = use_input_mask
_lowerCAmelCase = use_token_type_ids
_lowerCAmelCase = use_labels
_lowerCAmelCase = vocab_size
_lowerCAmelCase = hidden_size
_lowerCAmelCase = num_hidden_layers
_lowerCAmelCase = num_attention_heads
_lowerCAmelCase = intermediate_size
_lowerCAmelCase = hidden_act
_lowerCAmelCase = hidden_dropout_prob
_lowerCAmelCase = attention_probs_dropout_prob
_lowerCAmelCase = max_position_embeddings
_lowerCAmelCase = type_vocab_size
_lowerCAmelCase = type_sequence_label_size
_lowerCAmelCase = initializer_range
_lowerCAmelCase = num_labels
_lowerCAmelCase = num_choices
_lowerCAmelCase = scope
def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ):
_lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
_lowerCAmelCase = None
if self.use_input_mask:
_lowerCAmelCase = random_attention_mask([self.batch_size, self.seq_length] )
_lowerCAmelCase = None
if self.use_token_type_ids:
_lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
_lowerCAmelCase = None
_lowerCAmelCase = None
_lowerCAmelCase = None
if self.use_labels:
_lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size )
_lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
_lowerCAmelCase = ids_tensor([self.batch_size] , self.num_choices )
_lowerCAmelCase = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def SCREAMING_SNAKE_CASE__ ( self : str ):
return NystromformerConfig(
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=lowercase__ , initializer_range=self.initializer_range , )
def SCREAMING_SNAKE_CASE__ ( self : Tuple , lowercase__ : List[str] , lowercase__ : str , lowercase__ : Tuple , lowercase__ : str , lowercase__ : Optional[Any] , lowercase__ : str , lowercase__ : Dict ):
_lowerCAmelCase = NystromformerModel(config=lowercase__ )
model.to(lowercase__ )
model.eval()
_lowerCAmelCase = model(lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ )
_lowerCAmelCase = model(lowercase__ , token_type_ids=lowercase__ )
_lowerCAmelCase = model(lowercase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def SCREAMING_SNAKE_CASE__ ( self : Tuple , lowercase__ : str , lowercase__ : Optional[Any] , lowercase__ : List[str] , lowercase__ : Union[str, Any] , lowercase__ : Union[str, Any] , lowercase__ : Any , lowercase__ : Any ):
_lowerCAmelCase = NystromformerForMaskedLM(config=lowercase__ )
model.to(lowercase__ )
model.eval()
_lowerCAmelCase = model(lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def SCREAMING_SNAKE_CASE__ ( self : List[Any] , lowercase__ : Optional[Any] , lowercase__ : Dict , lowercase__ : List[Any] , lowercase__ : Any , lowercase__ : str , lowercase__ : Optional[Any] , lowercase__ : Optional[int] ):
_lowerCAmelCase = NystromformerForQuestionAnswering(config=lowercase__ )
model.to(lowercase__ )
model.eval()
_lowerCAmelCase = model(
lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , start_positions=lowercase__ , end_positions=lowercase__ , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , lowercase__ : Optional[Any] , lowercase__ : List[Any] , lowercase__ : List[str] , lowercase__ : Optional[Any] , lowercase__ : Optional[Any] , lowercase__ : List[Any] , lowercase__ : Tuple ):
_lowerCAmelCase = self.num_labels
_lowerCAmelCase = NystromformerForSequenceClassification(lowercase__ )
model.to(lowercase__ )
model.eval()
_lowerCAmelCase = model(lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , lowercase__ : Tuple , lowercase__ : Any , lowercase__ : Tuple , lowercase__ : List[Any] , lowercase__ : str , lowercase__ : Any , lowercase__ : Optional[int] ):
_lowerCAmelCase = self.num_labels
_lowerCAmelCase = NystromformerForTokenClassification(config=lowercase__ )
model.to(lowercase__ )
model.eval()
_lowerCAmelCase = model(lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def SCREAMING_SNAKE_CASE__ ( self : str , lowercase__ : Optional[Any] , lowercase__ : Tuple , lowercase__ : Any , lowercase__ : List[Any] , lowercase__ : Tuple , lowercase__ : Optional[int] , lowercase__ : List[str] ):
_lowerCAmelCase = self.num_choices
_lowerCAmelCase = NystromformerForMultipleChoice(config=lowercase__ )
model.to(lowercase__ )
model.eval()
_lowerCAmelCase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
_lowerCAmelCase = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
_lowerCAmelCase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
_lowerCAmelCase = model(
lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ):
_lowerCAmelCase = self.prepare_config_and_inputs()
(
(
_lowerCAmelCase
) , (
_lowerCAmelCase
) , (
_lowerCAmelCase
) , (
_lowerCAmelCase
) , (
_lowerCAmelCase
) , (
_lowerCAmelCase
) , (
_lowerCAmelCase
) ,
) = config_and_inputs
_lowerCAmelCase = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
return config, inputs_dict
@require_torch
class lowerCamelCase__ ( UpperCAmelCase ,UpperCAmelCase ,unittest.TestCase ):
UpperCamelCase__ =(
(
NystromformerModel,
NystromformerForMaskedLM,
NystromformerForMultipleChoice,
NystromformerForQuestionAnswering,
NystromformerForSequenceClassification,
NystromformerForTokenClassification,
)
if is_torch_available()
else ()
)
UpperCamelCase__ =(
{
"feature-extraction": NystromformerModel,
"fill-mask": NystromformerForMaskedLM,
"question-answering": NystromformerForQuestionAnswering,
"text-classification": NystromformerForSequenceClassification,
"token-classification": NystromformerForTokenClassification,
"zero-shot": NystromformerForSequenceClassification,
}
if is_torch_available()
else {}
)
UpperCamelCase__ =False
UpperCamelCase__ =False
def SCREAMING_SNAKE_CASE__ ( self : List[str] ):
_lowerCAmelCase = NystromformerModelTester(self )
_lowerCAmelCase = ConfigTester(self , config_class=lowercase__ , hidden_size=37 )
def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ):
self.config_tester.run_common_tests()
def SCREAMING_SNAKE_CASE__ ( self : str ):
_lowerCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowercase__ )
def SCREAMING_SNAKE_CASE__ ( self : int ):
_lowerCAmelCase = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
_lowerCAmelCase = type
self.model_tester.create_and_check_model(*lowercase__ )
def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ):
_lowerCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*lowercase__ )
def SCREAMING_SNAKE_CASE__ ( self : str ):
_lowerCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*lowercase__ )
def SCREAMING_SNAKE_CASE__ ( self : Dict ):
_lowerCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*lowercase__ )
def SCREAMING_SNAKE_CASE__ ( self : Any ):
_lowerCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*lowercase__ )
def SCREAMING_SNAKE_CASE__ ( self : Any ):
_lowerCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*lowercase__ )
@slow
def SCREAMING_SNAKE_CASE__ ( self : Tuple ):
for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_lowerCAmelCase = NystromformerModel.from_pretrained(lowercase__ )
self.assertIsNotNone(lowercase__ )
@require_torch
class lowerCamelCase__ ( unittest.TestCase ):
@slow
def SCREAMING_SNAKE_CASE__ ( self : Tuple ):
_lowerCAmelCase = NystromformerModel.from_pretrained('uw-madison/nystromformer-512' )
_lowerCAmelCase = torch.tensor([[0, 1, 2, 3, 4, 5]] )
with torch.no_grad():
_lowerCAmelCase = model(lowercase__ )[0]
_lowerCAmelCase = torch.Size((1, 6, 7_68) )
self.assertEqual(output.shape , lowercase__ )
_lowerCAmelCase = torch.tensor(
[[[-0.4_5_3_2, -0.0_9_3_6, 0.5_1_3_7], [-0.2_6_7_6, 0.0_6_2_8, 0.6_1_8_6], [-0.3_6_2_9, -0.1_7_2_6, 0.4_7_1_6]]] )
self.assertTrue(torch.allclose(output[:, :3, :3] , lowercase__ , atol=1e-4 ) )
@slow
def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ):
_lowerCAmelCase = 'the [MASK] of Belgium is Brussels'
_lowerCAmelCase = AutoTokenizer.from_pretrained('uw-madison/nystromformer-512' )
_lowerCAmelCase = NystromformerForMaskedLM.from_pretrained('uw-madison/nystromformer-512' )
_lowerCAmelCase = tokenizer(lowercase__ , return_tensors='pt' )
with torch.no_grad():
_lowerCAmelCase = model(encoding.input_ids ).logits
_lowerCAmelCase = token_logits[:, 2, :].argmax(-1 )[0]
self.assertEqual(tokenizer.decode(lowercase__ ) , 'capital' )
| 225 | 0 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_torch_available,
)
SCREAMING_SNAKE_CASE_: Tuple ={
'configuration_encodec': [
'ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP',
'EncodecConfig',
],
'feature_extraction_encodec': ['EncodecFeatureExtractor'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_: Optional[Any] =[
'ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST',
'EncodecModel',
'EncodecPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_encodec import (
ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP,
EncodecConfig,
)
from .feature_extraction_encodec import EncodecFeatureExtractor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_encodec import (
ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST,
EncodecModel,
EncodecPreTrainedModel,
)
else:
import sys
SCREAMING_SNAKE_CASE_: List[str] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 78 |
import warnings
from typing import List, Optional, Union
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class _lowercase ( snake_case_ ):
lowercase = ['image_processor', 'tokenizer']
lowercase = 'LayoutLMv3ImageProcessor'
lowercase = ('LayoutLMv3Tokenizer', 'LayoutLMv3TokenizerFast')
def __init__( self : List[Any] , snake_case : int=None , snake_case : str=None , **snake_case : int ) -> Tuple:
"""simple docstring"""
UpperCamelCase_ : str = None
if "feature_extractor" in kwargs:
warnings.warn(
'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
' instead.' , snake_case , )
UpperCamelCase_ : Optional[Any] = kwargs.pop('feature_extractor' )
UpperCamelCase_ : Optional[Any] = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError('You need to specify an `image_processor`.' )
if tokenizer is None:
raise ValueError('You need to specify a `tokenizer`.' )
super().__init__(snake_case , snake_case )
def __call__( self : Optional[Any] , snake_case : List[Any] , snake_case : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , snake_case : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , snake_case : Union[List[List[int]], List[List[List[int]]]] = None , snake_case : Optional[Union[List[int], List[List[int]]]] = None , snake_case : bool = True , snake_case : Union[bool, str, PaddingStrategy] = False , snake_case : Union[bool, str, TruncationStrategy] = None , snake_case : Optional[int] = None , snake_case : int = 0 , snake_case : Optional[int] = None , snake_case : Optional[bool] = None , snake_case : Optional[bool] = None , snake_case : bool = False , snake_case : bool = False , snake_case : bool = False , snake_case : bool = False , snake_case : bool = True , snake_case : Optional[Union[str, TensorType]] = None , **snake_case : Optional[int] , ) -> BatchEncoding:
"""simple docstring"""
if self.image_processor.apply_ocr and (boxes is not None):
raise ValueError(
'You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True.' )
if self.image_processor.apply_ocr and (word_labels is not None):
raise ValueError(
'You cannot provide word labels if you initialized the image processor with apply_ocr set to True.' )
# first, apply the image processor
UpperCamelCase_ : Optional[int] = self.image_processor(images=snake_case , return_tensors=snake_case )
# second, apply the tokenizer
if text is not None and self.image_processor.apply_ocr and text_pair is None:
if isinstance(snake_case , snake_case ):
UpperCamelCase_ : Optional[Any] = [text] # add batch dimension (as the image processor always adds a batch dimension)
UpperCamelCase_ : str = features['words']
UpperCamelCase_ : int = self.tokenizer(
text=text if text is not None else features['words'] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['boxes'] , word_labels=snake_case , add_special_tokens=snake_case , padding=snake_case , truncation=snake_case , max_length=snake_case , stride=snake_case , pad_to_multiple_of=snake_case , return_token_type_ids=snake_case , return_attention_mask=snake_case , return_overflowing_tokens=snake_case , return_special_tokens_mask=snake_case , return_offsets_mapping=snake_case , return_length=snake_case , verbose=snake_case , return_tensors=snake_case , **snake_case , )
# add pixel values
UpperCamelCase_ : int = features.pop('pixel_values' )
if return_overflowing_tokens is True:
UpperCamelCase_ : Optional[Any] = self.get_overflowing_images(snake_case , encoded_inputs['overflow_to_sample_mapping'] )
UpperCamelCase_ : List[str] = images
return encoded_inputs
def SCREAMING_SNAKE_CASE__ ( self : Any , snake_case : Any , snake_case : Dict ) -> Union[str, Any]:
"""simple docstring"""
UpperCamelCase_ : List[str] = []
for sample_idx in overflow_to_sample_mapping:
images_with_overflow.append(images[sample_idx] )
if len(snake_case ) != len(snake_case ):
raise ValueError(
'Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got'
f" {len(snake_case )} and {len(snake_case )}" )
return images_with_overflow
def SCREAMING_SNAKE_CASE__ ( self : List[str] , *snake_case : Dict , **snake_case : List[Any] ) -> Tuple:
"""simple docstring"""
return self.tokenizer.batch_decode(*snake_case , **snake_case )
def SCREAMING_SNAKE_CASE__ ( self : List[Any] , *snake_case : Optional[int] , **snake_case : int ) -> Any:
"""simple docstring"""
return self.tokenizer.decode(*snake_case , **snake_case )
@property
def SCREAMING_SNAKE_CASE__ ( self : str ) -> List[str]:
"""simple docstring"""
return ["input_ids", "bbox", "attention_mask", "pixel_values"]
@property
def SCREAMING_SNAKE_CASE__ ( self : int ) -> List[Any]:
"""simple docstring"""
warnings.warn(
'`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , snake_case , )
return self.image_processor_class
@property
def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Optional[Any]:
"""simple docstring"""
warnings.warn(
'`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , snake_case , )
return self.image_processor
| 417 | 0 |
"""simple docstring"""
import unittest
from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin
UpperCamelCase__ = get_tests_dir('''fixtures/test_sentencepiece.model''')
@require_sentencepiece
class a__ ( UpperCamelCase_ , unittest.TestCase ):
snake_case__ = XLMProphetNetTokenizer
snake_case__ = False
snake_case__ = True
def __UpperCamelCase ( self : Optional[Any]) -> Union[str, Any]:
"""simple docstring"""
super().setUp()
# We have a SentencePiece fixture for testing
_lowerCAmelCase:Union[str, Any] = XLMProphetNetTokenizer(a__ ,keep_accents=a__)
tokenizer.save_pretrained(self.tmpdirname)
def __UpperCamelCase ( self : str) -> List[Any]:
"""simple docstring"""
_lowerCAmelCase:Union[str, Any] = '''[PAD]'''
_lowerCAmelCase:List[Any] = 0
self.assertEqual(self.get_tokenizer()._convert_token_to_id(a__) ,a__)
self.assertEqual(self.get_tokenizer()._convert_id_to_token(a__) ,a__)
def __UpperCamelCase ( self : int) -> Optional[int]:
"""simple docstring"""
_lowerCAmelCase:Any = list(self.get_tokenizer().get_vocab().keys())
self.assertEqual(vocab_keys[0] ,'''[PAD]''')
self.assertEqual(vocab_keys[1] ,'''[CLS]''')
self.assertEqual(vocab_keys[-1] ,'''j''')
self.assertEqual(len(a__) ,1012)
def __UpperCamelCase ( self : str) -> int:
"""simple docstring"""
self.assertEqual(self.get_tokenizer().vocab_size ,1012)
def __UpperCamelCase ( self : Optional[int]) -> str:
"""simple docstring"""
_lowerCAmelCase:Tuple = XLMProphetNetTokenizer(a__ ,keep_accents=a__)
_lowerCAmelCase:Any = tokenizer.tokenize('''This is a test''')
self.assertListEqual(a__ ,['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''])
self.assertListEqual(
tokenizer.convert_tokens_to_ids(a__) ,[value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] ,)
_lowerCAmelCase:Optional[Any] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''')
self.assertListEqual(
a__ ,[
SPIECE_UNDERLINE + '''I''',
SPIECE_UNDERLINE + '''was''',
SPIECE_UNDERLINE + '''b''',
'''or''',
'''n''',
SPIECE_UNDERLINE + '''in''',
SPIECE_UNDERLINE + '''''',
'''9''',
'''2''',
'''0''',
'''0''',
'''0''',
''',''',
SPIECE_UNDERLINE + '''and''',
SPIECE_UNDERLINE + '''this''',
SPIECE_UNDERLINE + '''is''',
SPIECE_UNDERLINE + '''f''',
'''al''',
'''s''',
'''é''',
'''.''',
] ,)
_lowerCAmelCase:int = tokenizer.convert_tokens_to_ids(a__)
self.assertListEqual(
a__ ,[
value + tokenizer.fairseq_offset
for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4]
] ,)
_lowerCAmelCase:List[Any] = tokenizer.convert_ids_to_tokens(a__)
self.assertListEqual(
a__ ,[
SPIECE_UNDERLINE + '''I''',
SPIECE_UNDERLINE + '''was''',
SPIECE_UNDERLINE + '''b''',
'''or''',
'''n''',
SPIECE_UNDERLINE + '''in''',
SPIECE_UNDERLINE + '''''',
'''[UNK]''',
'''2''',
'''0''',
'''0''',
'''0''',
''',''',
SPIECE_UNDERLINE + '''and''',
SPIECE_UNDERLINE + '''this''',
SPIECE_UNDERLINE + '''is''',
SPIECE_UNDERLINE + '''f''',
'''al''',
'''s''',
'''[UNK]''',
'''.''',
] ,)
@cached_property
def __UpperCamelCase ( self : str) -> Optional[int]:
"""simple docstring"""
return XLMProphetNetTokenizer.from_pretrained('''microsoft/xprophetnet-large-wiki100-cased''')
@slow
def __UpperCamelCase ( self : Union[str, Any]) -> List[Any]:
"""simple docstring"""
_lowerCAmelCase:Optional[int] = '''Hello World!'''
_lowerCAmelCase:Union[str, Any] = [3_5389, 6672, 49, 2]
self.assertListEqual(a__ ,self.big_tokenizer.encode(a__))
@slow
def __UpperCamelCase ( self : Optional[Any]) -> Optional[int]:
"""simple docstring"""
_lowerCAmelCase:Optional[int] = {'''input_ids''': [[1_1073, 8_2783, 18, 26, 8_2783, 549, 5_1540, 248, 1_7209, 1301, 217, 20, 21_5186, 1325, 147, 1_7209, 1301, 217, 20, 5_6370, 53, 12_2020, 20, 1_6477, 27, 8_7355, 4548, 20, 4728, 7_8392, 17, 15_9969, 18, 26, 2_4491, 629, 15, 538, 2_2704, 5439, 15, 2788, 2_4491, 9885, 15, 4_3534, 605, 15, 814, 1_8403, 3_3200, 29, 15, 4_3534, 2_4458, 1_2410, 111, 2_4966, 8_3669, 9637, 14_4068, 26, 850, 2_2346, 27, 147, 2_4966, 8_3669, 8_3490, 26, 3_9113, 735, 27, 689, 656, 2800, 1339, 4600, 53, 12_2020, 11_5785, 34, 816, 1339, 4_6887, 18, 147, 5_3905, 1951, 4_2238, 4_1170, 1_7732, 834, 436, 15, 2_7523, 9_8733, 217, 147, 5542, 4981, 930, 1_7347, 16, 2], [2_0091, 629, 94, 8_2786, 58, 490, 20, 1528, 84, 5_3905, 344, 8_0592, 11_0128, 1_8822, 5267, 1306, 62, 15_2537, 308, 7997, 401, 12_4427, 549, 3_5442, 225, 109, 1_5055, 2_5748, 147, 7119, 4_3712, 34, 767, 13_5366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 6_3784, 11_9466, 17, 14_7808, 8_8214, 18, 656, 81, 32, 3296, 1_0280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=a__ ,model_name='''microsoft/xprophetnet-large-wiki100-cased''' ,revision='''1acad1643ddd54a44df6a1b797ada8373685d90e''' ,)
| 439 |
"""simple docstring"""
from argparse import ArgumentParser
from .add_new_model import AddNewModelCommand
from .add_new_model_like import AddNewModelLikeCommand
from .convert import ConvertCommand
from .download import DownloadCommand
from .env import EnvironmentCommand
from .lfs import LfsCommands
from .pt_to_tf import PTtoTFCommand
from .run import RunCommand
from .serving import ServeCommand
from .user import UserCommands
def UpperCAmelCase ( ):
_lowerCAmelCase:List[Any] = ArgumentParser('''Transformers CLI tool''' , usage='''transformers-cli <command> [<args>]''' )
_lowerCAmelCase:Union[str, Any] = parser.add_subparsers(help='''transformers-cli command helpers''' )
# Register commands
ConvertCommand.register_subcommand(snake_case )
DownloadCommand.register_subcommand(snake_case )
EnvironmentCommand.register_subcommand(snake_case )
RunCommand.register_subcommand(snake_case )
ServeCommand.register_subcommand(snake_case )
UserCommands.register_subcommand(snake_case )
AddNewModelCommand.register_subcommand(snake_case )
AddNewModelLikeCommand.register_subcommand(snake_case )
LfsCommands.register_subcommand(snake_case )
PTtoTFCommand.register_subcommand(snake_case )
# Let's go
_lowerCAmelCase:Union[str, Any] = parser.parse_args()
if not hasattr(snake_case , '''func''' ):
parser.print_help()
exit(1 )
# Run
_lowerCAmelCase:Any = args.func(snake_case )
service.run()
if __name__ == "__main__":
main()
| 439 | 1 |
import argparse
import requests
import torch
from PIL import Image
from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor
def A__ ( __A : Optional[int] ) ->Optional[Any]:
if "cls_token" in name:
__A =name.replace('''cls_token''' , '''vit.embeddings.cls_token''' )
if "mask_token" in name:
__A =name.replace('''mask_token''' , '''decoder.mask_token''' )
if "decoder_pos_embed" in name:
__A =name.replace('''decoder_pos_embed''' , '''decoder.decoder_pos_embed''' )
if "pos_embed" in name and "decoder" not in name:
__A =name.replace('''pos_embed''' , '''vit.embeddings.position_embeddings''' )
if "patch_embed.proj" in name:
__A =name.replace('''patch_embed.proj''' , '''vit.embeddings.patch_embeddings.projection''' )
if "patch_embed.norm" in name:
__A =name.replace('''patch_embed.norm''' , '''vit.embeddings.norm''' )
if "decoder_blocks" in name:
__A =name.replace('''decoder_blocks''' , '''decoder.decoder_layers''' )
if "blocks" in name:
__A =name.replace('''blocks''' , '''vit.encoder.layer''' )
if "attn.proj" in name:
__A =name.replace('''attn.proj''' , '''attention.output.dense''' )
if "attn" in name:
__A =name.replace('''attn''' , '''attention.self''' )
if "norm1" in name:
__A =name.replace('''norm1''' , '''layernorm_before''' )
if "norm2" in name:
__A =name.replace('''norm2''' , '''layernorm_after''' )
if "mlp.fc1" in name:
__A =name.replace('''mlp.fc1''' , '''intermediate.dense''' )
if "mlp.fc2" in name:
__A =name.replace('''mlp.fc2''' , '''output.dense''' )
if "decoder_embed" in name:
__A =name.replace('''decoder_embed''' , '''decoder.decoder_embed''' )
if "decoder_norm" in name:
__A =name.replace('''decoder_norm''' , '''decoder.decoder_norm''' )
if "decoder_pred" in name:
__A =name.replace('''decoder_pred''' , '''decoder.decoder_pred''' )
if "norm.weight" in name and "decoder" not in name:
__A =name.replace('''norm.weight''' , '''vit.layernorm.weight''' )
if "norm.bias" in name and "decoder" not in name:
__A =name.replace('''norm.bias''' , '''vit.layernorm.bias''' )
return name
def A__ ( __A : Any , __A : Optional[int] ) ->Dict:
for key in orig_state_dict.copy().keys():
__A =orig_state_dict.pop(snake_case__ )
if "qkv" in key:
__A =key.split('''.''' )
__A =int(key_split[1] )
if "decoder_blocks" in key:
__A =config.decoder_hidden_size
__A ="""decoder.decoder_layers."""
if "weight" in key:
__A =val[:dim, :]
__A =val[dim : dim * 2, :]
__A =val[-dim:, :]
elif "bias" in key:
__A =val[:dim]
__A =val[dim : dim * 2]
__A =val[-dim:]
else:
__A =config.hidden_size
__A ="""vit.encoder.layer."""
if "weight" in key:
__A =val[:dim, :]
__A =val[dim : dim * 2, :]
__A =val[-dim:, :]
elif "bias" in key:
__A =val[:dim]
__A =val[dim : dim * 2]
__A =val[-dim:]
else:
__A =val
return orig_state_dict
def A__ ( __A : Dict , __A : Any ) ->Dict:
__A =ViTMAEConfig()
if "large" in checkpoint_url:
__A =10_24
__A =40_96
__A =24
__A =16
elif "huge" in checkpoint_url:
__A =14
__A =12_80
__A =51_20
__A =32
__A =16
__A =ViTMAEForPreTraining(snake_case__ )
__A =torch.hub.load_state_dict_from_url(snake_case__ , map_location='''cpu''' )["""model"""]
__A =ViTMAEImageProcessor(size=config.image_size )
__A =convert_state_dict(snake_case__ , snake_case__ )
model.load_state_dict(snake_case__ )
model.eval()
__A ="""https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg"""
__A =Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw )
__A =ViTMAEImageProcessor(size=config.image_size )
__A =image_processor(images=snake_case__ , return_tensors='''pt''' )
# forward pass
torch.manual_seed(2 )
__A =model(**snake_case__ )
__A =outputs.logits
if "large" in checkpoint_url:
__A =torch.tensor(
[[-0.7309, -0.7128, -1.0169], [-1.0161, -0.9058, -1.1878], [-1.0478, -0.9411, -1.1911]] )
elif "huge" in checkpoint_url:
__A =torch.tensor(
[[-1.1599, -0.9199, -1.2221], [-1.1952, -0.9269, -1.2307], [-1.2143, -0.9337, -1.2262]] )
else:
__A =torch.tensor(
[[-0.9192, -0.8481, -1.1259], [-1.1349, -1.0034, -1.2599], [-1.1757, -1.0429, -1.2726]] )
# verify logits
assert torch.allclose(logits[0, :3, :3] , snake_case__ , atol=1e-4 )
print(F'''Saving model to {pytorch_dump_folder_path}''' )
model.save_pretrained(snake_case__ )
print(F'''Saving image processor to {pytorch_dump_folder_path}''' )
image_processor.save_pretrained(snake_case__ )
if __name__ == "__main__":
_lowerCamelCase : Any = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--checkpoint_url''',
default='''https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth''',
type=str,
help='''URL of the checkpoint you\'d like to convert.''',
)
parser.add_argument(
'''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.'''
)
_lowerCamelCase : int = parser.parse_args()
convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
| 184 |
"""simple docstring"""
from typing import Dict
from .base import GenericTensor, Pipeline
class SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE ):
"""simple docstring"""
def lowerCamelCase(self , lowerCAmelCase_=None , lowerCAmelCase_=None , lowerCAmelCase_=None , **lowerCAmelCase_ ):
if tokenize_kwargs is None:
A_ : Dict = {}
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)""" )
A_ : Optional[Any] = truncation
A_ : Optional[int] = tokenize_kwargs
A_ : Optional[Any] = {}
if return_tensors is not None:
A_ : Optional[Any] = return_tensors
return preprocess_params, {}, postprocess_params
def lowerCamelCase(self , lowerCAmelCase_ , **lowerCAmelCase_ ):
A_ : List[Any] = self.framework
A_ : Optional[int] = self.tokenizer(lowerCAmelCase_ , return_tensors=lowerCAmelCase_ , **lowerCAmelCase_ )
return model_inputs
def lowerCamelCase(self , lowerCAmelCase_ ):
A_ : List[Any] = self.model(**lowerCAmelCase_ )
return model_outputs
def lowerCamelCase(self , lowerCAmelCase_ , lowerCAmelCase_=False ):
# [0] is the first available tensor, logits or last_hidden_state.
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 , *lowerCAmelCase_ , **lowerCAmelCase_ ):
return super().__call__(*lowerCAmelCase_ , **lowerCAmelCase_ )
| 180 | 0 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available
_lowercase : Tuple ={
"configuration_longt5": ["LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "LongT5Config", "LongT5OnnxConfig"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase : Tuple =[
"LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST",
"LongT5EncoderModel",
"LongT5ForConditionalGeneration",
"LongT5Model",
"LongT5PreTrainedModel",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase : Tuple =[
"FlaxLongT5ForConditionalGeneration",
"FlaxLongT5Model",
"FlaxLongT5PreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_longta import LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP, LongTaConfig, LongTaOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_longta import (
LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST,
LongTaEncoderModel,
LongTaForConditionalGeneration,
LongTaModel,
LongTaPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_longta import (
FlaxLongTaForConditionalGeneration,
FlaxLongTaModel,
FlaxLongTaPreTrainedModel,
)
else:
import sys
_lowercase : Optional[int] =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 708 |
'''simple docstring'''
import json
import os
from datetime import date
from pathlib import Path
from tabulate import DataRow, TableFormat, tabulate
_lowercase : List[Any] =TableFormat(
lineabove=None,
linebelowheader=None,
linebetweenrows=None,
linebelow=None,
headerrow=DataRow("", "|", "|"),
datarow=DataRow("", "|", "|"),
padding=1,
with_header_hide=None,
)
_lowercase : List[Any] =[]
_lowercase : List[str] =[]
_lowercase : Tuple ={"type": "section", "text": {"type": "plain_text", "text": "No failed tests! 🤗", "emoji": True}}
_lowercase : Union[str, Any] =[
{
"type": "header",
"text": {
"type": "plain_text",
"text": F"🤗 Accelerate nightly {os.environ.get('TEST_TYPE', '')} test results",
"emoji": True,
},
}
]
_lowercase : int =0
for log in Path().glob("*.log"):
_lowercase : Tuple =0
with open(log, "r") as f:
for line in f:
_lowercase : str =json.loads(line)
if line.get("nodeid", "") != "":
_lowercase : List[Any] =line["nodeid"]
if line.get("duration", None) is not None:
_lowercase : Optional[int] =F"{line['duration']:.4f}"
if line.get("outcome", "") == "failed":
section_num_failed += 1
failed.append([test, duration, log.name.split("_")[0]])
total_num_failed += 1
group_info.append([str(log), section_num_failed, failed])
_lowercase : Optional[int] =[]
log.unlink()
_lowercase : Optional[int] =""
_lowercase : List[Any] =[]
if total_num_failed > 0:
for name, num_failed, failed_tests in group_info:
if num_failed > 0:
if num_failed == 1:
message += F"*{name[1:]}: {num_failed} failed test*\n"
else:
message += F"*{name[1:]}: {num_failed} failed tests*\n"
_lowercase : Dict =[]
_lowercase : Dict ={}
for test in failed_tests:
_lowercase : Union[str, Any] =test[0].split("::")
_lowercase : Dict =data[0].split("/")[-1]
if data[0] not in filesafailed:
_lowercase : Union[str, Any] =[data[1:]]
else:
filesafailed[data[0]] += [data[1:]]
failed_table.append(data)
_lowercase : Dict =[test[0] for test in failed_table]
_lowercase : Dict =list(set(files))
# Count number of instances in failed_tests
_lowercase : Tuple =[]
for file in individual_files:
table.append([file, len(filesafailed[file])])
_lowercase : Dict =tabulate(
table,
headers=["Test Location", "Num Failed"],
tablefmt=hf_table_format,
stralign="right",
)
message += F"\n```\n{failed_table}\n```"
all_filesafailed.append(filesafailed)
if len(message) > 3000:
_lowercase : Tuple ="Too many failed tests, please see the full report in the Action results."
_lowercase : Optional[int] =len(err) + 10
_lowercase : str =message[: 3000 - offset] + F"\n...\n```\n{err}"
print(F"### {message}")
else:
_lowercase : Union[str, Any] ="No failed tests! 🤗"
print(F"## {message}")
payload.append(no_error_payload)
if os.environ.get("TEST_TYPE", "") != "":
from slack_sdk import WebClient
_lowercase : List[str] =WebClient(token=os.environ["SLACK_API_TOKEN"])
if message != "No failed tests! 🤗":
_lowercase : Optional[Any] ={
"type": "section",
"text": {
"type": "mrkdwn",
"text": message,
},
}
payload.append(md_report)
_lowercase : Union[str, Any] ={
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*For more details:*",
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "Check Action results",
"emoji": True,
},
"url": F"https://github.com/{os.environ['GITHUB_REPOSITORY']}/actions/runs/{os.environ['GITHUB_RUN_ID']}",
},
}
payload.append(action_button)
_lowercase : Tuple ={
"type": "context",
"elements": [
{
"type": "plain_text",
"text": F"Nightly {os.environ.get('TEST_TYPE')} test results for {date.today()}",
}
],
}
payload.append(date_report)
_lowercase : List[str] =client.chat_postMessage(channel="#accelerate-ci-daily", text=message, blocks=payload)
_lowercase : int =response.data["ts"]
for failed_file in all_filesafailed:
for test_location, test_failures in failed_file.items():
# Keep only the first instance of the test name
_lowercase : Tuple =""
for i, row in enumerate(test_failures):
if row[0] != test_class:
_lowercase : List[str] =row[0]
else:
_lowercase : int =""
_lowercase : Tuple ={
"type": "section",
"text": {
"type": "mrkdwn",
"text": F"Test location: {test_location}\n```\n{tabulate(test_failures, headers=['Class', 'Test'], tablefmt=hf_table_format, stralign='right')}\n```",
},
}
client.chat_postMessage(
channel="#accelerate-ci-daily",
thread_ts=ts,
blocks=[payload],
)
| 574 | 0 |
"""simple docstring"""
import inspect
import unittest
from transformers import DPTConfig
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel
from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import DPTImageProcessor
class __SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__( self : Union[str, Any] , __a : Dict , __a : str=2 , __a : int=32 , __a : Optional[int]=16 , __a : List[str]=3 , __a : Dict=True , __a : List[str]=True , __a : Union[str, Any]=32 , __a : Optional[int]=4 , __a : int=[0, 1, 2, 3] , __a : Union[str, Any]=4 , __a : List[Any]=37 , __a : Optional[Any]="gelu" , __a : Dict=0.1 , __a : Any=0.1 , __a : Optional[Any]=0.02 , __a : Optional[int]=3 , __a : int=[1, 384, 24, 24] , __a : Optional[Any]=True , __a : int=None , ) -> Tuple:
_UpperCamelCase : int = parent
_UpperCamelCase : Optional[int] = batch_size
_UpperCamelCase : Union[str, Any] = image_size
_UpperCamelCase : Dict = patch_size
_UpperCamelCase : Optional[Any] = num_channels
_UpperCamelCase : int = is_training
_UpperCamelCase : int = use_labels
_UpperCamelCase : Optional[Any] = hidden_size
_UpperCamelCase : str = num_hidden_layers
_UpperCamelCase : Dict = backbone_out_indices
_UpperCamelCase : List[str] = num_attention_heads
_UpperCamelCase : Dict = intermediate_size
_UpperCamelCase : int = hidden_act
_UpperCamelCase : List[Any] = hidden_dropout_prob
_UpperCamelCase : Optional[Any] = attention_probs_dropout_prob
_UpperCamelCase : Union[str, Any] = initializer_range
_UpperCamelCase : int = num_labels
_UpperCamelCase : List[str] = backbone_featmap_shape
_UpperCamelCase : str = scope
_UpperCamelCase : Any = is_hybrid
# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
_UpperCamelCase : List[str] = (image_size // patch_size) ** 2
_UpperCamelCase : List[Any] = num_patches + 1
def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Tuple:
_UpperCamelCase : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
_UpperCamelCase : Any = None
if self.use_labels:
_UpperCamelCase : str = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels )
_UpperCamelCase : List[Any] = self.get_config()
return config, pixel_values, labels
def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]:
_UpperCamelCase : List[str] = {
"global_padding": "same",
"layer_type": "bottleneck",
"depths": [3, 4, 9],
"out_features": ["stage1", "stage2", "stage3"],
"embedding_dynamic_padding": True,
"hidden_sizes": [96, 192, 384, 768],
"num_groups": 2,
}
return DPTConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , backbone_out_indices=self.backbone_out_indices , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__a , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=__a , backbone_featmap_shape=self.backbone_featmap_shape , )
def __SCREAMING_SNAKE_CASE ( self : Any , __a : Dict , __a : str , __a : Tuple ) -> Union[str, Any]:
_UpperCamelCase : Optional[int] = DPTModel(config=__a )
model.to(__a )
model.eval()
_UpperCamelCase : Tuple = model(__a )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __a : Tuple , __a : Optional[int] , __a : Tuple ) -> Optional[int]:
_UpperCamelCase : int = self.num_labels
_UpperCamelCase : int = DPTForDepthEstimation(__a )
model.to(__a )
model.eval()
_UpperCamelCase : Optional[int] = model(__a )
self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) )
def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __a : int , __a : str , __a : Dict ) -> int:
_UpperCamelCase : List[Any] = self.num_labels
_UpperCamelCase : Dict = DPTForSemanticSegmentation(__a )
model.to(__a )
model.eval()
_UpperCamelCase : str = model(__a , labels=__a )
self.parent.assertEqual(
result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) )
def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]:
_UpperCamelCase : Tuple = self.prepare_config_and_inputs()
_UpperCamelCase, _UpperCamelCase, _UpperCamelCase : List[Any] = config_and_inputs
_UpperCamelCase : Any = {"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
class __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE__ :Union[str, Any] = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
SCREAMING_SNAKE_CASE__ :str = (
{
"depth-estimation": DPTForDepthEstimation,
"feature-extraction": DPTModel,
"image-segmentation": DPTForSemanticSegmentation,
}
if is_torch_available()
else {}
)
SCREAMING_SNAKE_CASE__ :List[str] = False
SCREAMING_SNAKE_CASE__ :Any = False
SCREAMING_SNAKE_CASE__ :int = False
def __SCREAMING_SNAKE_CASE ( self : str ) -> Optional[int]:
_UpperCamelCase : str = DPTModelTester(self )
_UpperCamelCase : Optional[int] = ConfigTester(self , config_class=__a , has_text_modality=__a , hidden_size=37 )
def __SCREAMING_SNAKE_CASE ( self : str ) -> Optional[int]:
self.config_tester.run_common_tests()
@unittest.skip(reason="DPT does not use inputs_embeds" )
def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Any:
pass
def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str:
_UpperCamelCase, _UpperCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase : List[str] = model_class(__a )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
_UpperCamelCase : Any = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(__a , nn.Linear ) )
def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]:
_UpperCamelCase, _UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase : str = model_class(__a )
_UpperCamelCase : Union[str, Any] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_UpperCamelCase : List[Any] = [*signature.parameters.keys()]
_UpperCamelCase : int = ["pixel_values"]
self.assertListEqual(arg_names[:1] , __a )
def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[str]:
_UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__a )
def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]:
_UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_depth_estimation(*__a )
def __SCREAMING_SNAKE_CASE ( self : Any ) -> Dict:
_UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_semantic_segmentation(*__a )
def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]:
for model_class in self.all_model_classes:
if model_class.__name__ == "DPTForDepthEstimation":
continue
_UpperCamelCase, _UpperCamelCase : str = self.model_tester.prepare_config_and_inputs_for_common()
_UpperCamelCase : int = True
if model_class in get_values(__a ):
continue
_UpperCamelCase : Union[str, Any] = model_class(__a )
model.to(__a )
model.train()
_UpperCamelCase : int = self._prepare_for_class(__a , __a , return_labels=__a )
_UpperCamelCase : Optional[int] = model(**__a ).loss
loss.backward()
def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[str]:
for model_class in self.all_model_classes:
if model_class.__name__ == "DPTForDepthEstimation":
continue
_UpperCamelCase, _UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
_UpperCamelCase : Dict = False
_UpperCamelCase : Dict = True
if model_class in get_values(__a ) or not model_class.supports_gradient_checkpointing:
continue
_UpperCamelCase : Optional[int] = model_class(__a )
model.to(__a )
model.gradient_checkpointing_enable()
model.train()
_UpperCamelCase : Tuple = self._prepare_for_class(__a , __a , return_labels=__a )
_UpperCamelCase : Optional[Any] = model(**__a ).loss
loss.backward()
def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[int]:
_UpperCamelCase, _UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common()
_UpperCamelCase : Tuple = _config_zero_init(__a )
for model_class in self.all_model_classes:
_UpperCamelCase : int = model_class(config=__a )
# Skip the check for the backbone
_UpperCamelCase : int = []
for name, module in model.named_modules():
if module.__class__.__name__ == "DPTViTHybridEmbeddings":
_UpperCamelCase : Optional[Any] = [F'''{name}.{key}''' for key in module.state_dict().keys()]
break
for name, param in model.named_parameters():
if param.requires_grad:
if name in backbone_params:
continue
self.assertIn(
((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , )
@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." )
def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]:
pass
@slow
def __SCREAMING_SNAKE_CASE ( self : int ) -> List[str]:
for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
_UpperCamelCase : Optional[Any] = DPTModel.from_pretrained(__a )
self.assertIsNotNone(__a )
def __SCREAMING_SNAKE_CASE ( self : Dict ) -> str:
# We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type
_UpperCamelCase, _UpperCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common()
_UpperCamelCase : Optional[Any] = "add"
with self.assertRaises(__a ):
_UpperCamelCase : str = DPTForDepthEstimation(__a )
def lowercase__ ( ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase : Optional[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_torch
@require_vision
@slow
class __SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def __SCREAMING_SNAKE_CASE ( self : str ) -> Tuple:
_UpperCamelCase : List[Any] = DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas" )
_UpperCamelCase : Optional[int] = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas" ).to(__a )
_UpperCamelCase : List[Any] = prepare_img()
_UpperCamelCase : Dict = image_processor(images=__a , return_tensors="pt" ).to(__a )
# forward pass
with torch.no_grad():
_UpperCamelCase : Optional[Any] = model(**__a )
_UpperCamelCase : int = outputs.predicted_depth
# verify the predicted depth
_UpperCamelCase : Tuple = torch.Size((1, 384, 384) )
self.assertEqual(predicted_depth.shape , __a )
_UpperCamelCase : Optional[int] = torch.tensor(
[[[5.64_37, 5.61_46, 5.65_11], [5.43_71, 5.56_49, 5.59_58], [5.52_15, 5.51_84, 5.52_93]]] ).to(__a )
self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 , __a , atol=1e-4 ) )
| 624 |
"""simple docstring"""
from typing import Any, Callable, Dict, List, Optional, Union
import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
DiffusionPipeline,
LMSDiscreteScheduler,
PNDMScheduler,
StableDiffusionPipeline,
UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
lowerCamelCase__ = "CompVis/stable-diffusion-v1-1"
lowerCamelCase__ = "CompVis/stable-diffusion-v1-2"
lowerCamelCase__ = "CompVis/stable-diffusion-v1-3"
lowerCamelCase__ = "CompVis/stable-diffusion-v1-4"
class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ):
'''simple docstring'''
def __init__( self : Union[str, Any] , __a : AutoencoderKL , __a : CLIPTextModel , __a : CLIPTokenizer , __a : UNetaDConditionModel , __a : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __a : StableDiffusionSafetyChecker , __a : CLIPImageProcessor , __a : bool = True , ) -> List[str]:
super()._init_()
_UpperCamelCase : Optional[int] = StableDiffusionPipeline.from_pretrained(__a )
_UpperCamelCase : int = StableDiffusionPipeline.from_pretrained(__a )
_UpperCamelCase : List[Any] = StableDiffusionPipeline.from_pretrained(__a )
_UpperCamelCase : int = StableDiffusionPipeline(
vae=__a , text_encoder=__a , tokenizer=__a , unet=__a , scheduler=__a , safety_checker=__a , feature_extractor=__a , requires_safety_checker=__a , )
self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea )
@property
def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict[str, Any]:
return {k: getattr(self , __a ) for k in self.config.keys() if not k.startswith("_" )}
def __SCREAMING_SNAKE_CASE ( self : Any , __a : Optional[Union[str, int]] = "auto" ) -> Optional[Any]:
if slice_size == "auto":
# half the attention head size is usually a good trade-off between
# speed and memory
_UpperCamelCase : Tuple = self.unet.config.attention_head_dim // 2
self.unet.set_attention_slice(__a )
def __SCREAMING_SNAKE_CASE ( self : str ) -> Any:
self.enable_attention_slicing(__a )
@torch.no_grad()
def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : Union[str, List[str]] , __a : int = 512 , __a : int = 512 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : Any , ) -> Optional[int]:
return self.pipea(
prompt=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , **__a , )
@torch.no_grad()
def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : Union[str, List[str]] , __a : int = 512 , __a : int = 512 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : Tuple , ) -> str:
return self.pipea(
prompt=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , **__a , )
@torch.no_grad()
def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : Union[str, List[str]] , __a : int = 512 , __a : int = 512 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : Tuple , ) -> Any:
return self.pipea(
prompt=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , **__a , )
@torch.no_grad()
def __SCREAMING_SNAKE_CASE ( self : Dict , __a : Union[str, List[str]] , __a : int = 512 , __a : int = 512 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : List[Any] , ) -> Union[str, Any]:
return self.pipea(
prompt=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , **__a , )
@torch.no_grad()
def __SCREAMING_SNAKE_CASE ( self : str , __a : Union[str, List[str]] , __a : int = 512 , __a : int = 512 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : int , ) -> List[Any]:
_UpperCamelCase : Tuple = "cuda" if torch.cuda.is_available() else "cpu"
self.to(__a )
# Checks if the height and width are divisible by 8 or not
if height % 8 != 0 or width % 8 != 0:
raise ValueError(F'''`height` and `width` must be divisible by 8 but are {height} and {width}.''' )
# Get first result from Stable Diffusion Checkpoint v1.1
_UpperCamelCase : List[str] = self.textaimg_sda_a(
prompt=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , **__a , )
# Get first result from Stable Diffusion Checkpoint v1.2
_UpperCamelCase : Optional[Any] = self.textaimg_sda_a(
prompt=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , **__a , )
# Get first result from Stable Diffusion Checkpoint v1.3
_UpperCamelCase : str = self.textaimg_sda_a(
prompt=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , **__a , )
# Get first result from Stable Diffusion Checkpoint v1.4
_UpperCamelCase : str = self.textaimg_sda_a(
prompt=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , **__a , )
# Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result
return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
| 624 | 1 |
from dataclasses import dataclass, field
from typing import ClassVar, Dict
from ..features import Features, Sequence, Value
from .base import TaskTemplate
@dataclass(frozen=__lowercase )
class a ( __lowercase ):
# `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization
SCREAMING_SNAKE_CASE__ : str = field(default='''question-answering-extractive''' ,metadata={'''include_in_asdict_even_if_is_default''': True} )
SCREAMING_SNAKE_CASE__ : ClassVar[Features] = Features({'''question''': Value('''string''' ), '''context''': Value('''string''' )} )
SCREAMING_SNAKE_CASE__ : ClassVar[Features] = Features(
{
'''answers''': Sequence(
{
'''text''': Value('''string''' ),
'''answer_start''': Value('''int32''' ),
} )
} )
SCREAMING_SNAKE_CASE__ : str = "question"
SCREAMING_SNAKE_CASE__ : str = "context"
SCREAMING_SNAKE_CASE__ : str = "answers"
@property
def snake_case_ ( self ):
"""simple docstring"""
return {self.question_column: "question", self.context_column: "context", self.answers_column: "answers"}
| 146 |
import math
import numpy as np
import qiskit
from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute
def lowerCAmelCase ( UpperCamelCase__ : int = 3 ) -> qiskit.result.counts.Counts:
"""simple docstring"""
if isinstance(UpperCamelCase__ , UpperCamelCase__ ):
raise TypeError('''number of qubits must be a integer.''' )
if number_of_qubits <= 0:
raise ValueError('''number of qubits must be > 0.''' )
if math.floor(UpperCamelCase__ ) != number_of_qubits:
raise ValueError('''number of qubits must be exact integer.''' )
if number_of_qubits > 10:
raise ValueError('''number of qubits too large to simulate(>10).''' )
__SCREAMING_SNAKE_CASE: Dict = QuantumRegister(UpperCamelCase__ , '''qr''' )
__SCREAMING_SNAKE_CASE: Optional[Any] = ClassicalRegister(UpperCamelCase__ , '''cr''' )
__SCREAMING_SNAKE_CASE: List[str] = QuantumCircuit(UpperCamelCase__ , UpperCamelCase__ )
__SCREAMING_SNAKE_CASE: Optional[Any] = number_of_qubits
for i in range(UpperCamelCase__ ):
quantum_circuit.h(number_of_qubits - i - 1 )
counter -= 1
for j in range(UpperCamelCase__ ):
quantum_circuit.cp(np.pi / 2 ** (counter - j) , UpperCamelCase__ , UpperCamelCase__ )
for k in range(number_of_qubits // 2 ):
quantum_circuit.swap(UpperCamelCase__ , number_of_qubits - k - 1 )
# measure all the qubits
quantum_circuit.measure(UpperCamelCase__ , UpperCamelCase__ )
# simulate with 10000 shots
__SCREAMING_SNAKE_CASE: Dict = Aer.get_backend('''qasm_simulator''' )
__SCREAMING_SNAKE_CASE: Tuple = execute(UpperCamelCase__ , UpperCamelCase__ , shots=10_000 )
return job.result().get_counts(UpperCamelCase__ )
if __name__ == "__main__":
print(
f'''Total count for quantum fourier transform state is: \
{quantum_fourier_transform(3)}'''
)
| 146 | 1 |
'''simple docstring'''
import numpy as np
class _UpperCAmelCase :
def __init__( self ):
'''simple docstring'''
__lowerCAmelCase = (0, 0)
__lowerCAmelCase = None
__lowerCAmelCase = 0
__lowerCAmelCase = 0
__lowerCAmelCase = 0
def __eq__( self,__SCREAMING_SNAKE_CASE ):
'''simple docstring'''
return self.position == cell.position
def lowerCamelCase__ ( self ):
'''simple docstring'''
print(self.position )
class _UpperCAmelCase :
def __init__( self,__SCREAMING_SNAKE_CASE=(5, 5) ):
'''simple docstring'''
__lowerCAmelCase = np.zeros(__SCREAMING_SNAKE_CASE )
__lowerCAmelCase = world_size[0]
__lowerCAmelCase = world_size[1]
def lowerCamelCase__ ( self ):
'''simple docstring'''
print(self.w )
def lowerCamelCase__ ( self,__SCREAMING_SNAKE_CASE ):
'''simple docstring'''
__lowerCAmelCase = [
(-1, -1),
(-1, 0),
(-1, 1),
(0, -1),
(0, 1),
(1, -1),
(1, 0),
(1, 1),
]
__lowerCAmelCase = cell.position[0]
__lowerCAmelCase = cell.position[1]
__lowerCAmelCase = []
for n in neughbour_cord:
__lowerCAmelCase = current_x + n[0]
__lowerCAmelCase = current_y + n[1]
if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit:
__lowerCAmelCase = Cell()
__lowerCAmelCase = (x, y)
__lowerCAmelCase = cell
neighbours.append(__SCREAMING_SNAKE_CASE )
return neighbours
def _lowerCAmelCase ( lowercase , lowercase , lowercase ) -> str:
__lowerCAmelCase = []
__lowerCAmelCase = []
_open.append(lowercase )
while _open:
__lowerCAmelCase = np.argmin([n.f for n in _open] )
__lowerCAmelCase = _open[min_f]
_closed.append(_open.pop(lowercase ) )
if current == goal:
break
for n in world.get_neigbours(lowercase ):
for c in _closed:
if c == n:
continue
__lowerCAmelCase = current.g + 1
__lowerCAmelCase , __lowerCAmelCase = n.position
__lowerCAmelCase , __lowerCAmelCase = goal.position
__lowerCAmelCase = (ya - ya) ** 2 + (xa - xa) ** 2
__lowerCAmelCase = n.h + n.g
for c in _open:
if c == n and c.f < n.f:
continue
_open.append(lowercase )
__lowerCAmelCase = []
while current.parent is not None:
path.append(current.position )
__lowerCAmelCase = current.parent
path.append(current.position )
return path[::-1]
if __name__ == "__main__":
_a : int = Gridworld()
# Start position and goal
_a : Optional[int] = Cell()
_a : int = (0, 0)
_a : Dict = Cell()
_a : Optional[int] = (4, 4)
print(f'path from {start.position} to {goal.position}')
_a : Dict = astar(world, start, goal)
# Just for visual reasons.
for i in s:
_a : Tuple = 1
print(world.w)
| 689 |
'''simple docstring'''
import argparse
import requests
import torch
from PIL import Image
from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel
def _lowerCAmelCase ( lowercase ) -> Optional[Any]:
# vision encoder
if "img_encoder.pos_embed" in name:
__lowerCAmelCase = name.replace("""img_encoder.pos_embed""" , """vision_model.embeddings.position_embeddings""" )
if "img_encoder.patch_embed.proj" in name:
__lowerCAmelCase = name.replace("""img_encoder.patch_embed.proj""" , """vision_model.embeddings.patch_embeddings.projection""" )
if "img_encoder.patch_embed.norm" in name:
__lowerCAmelCase = name.replace("""img_encoder.patch_embed.norm""" , """vision_model.embeddings.layernorm""" )
if "img_encoder.layers" in name:
__lowerCAmelCase = name.replace("""img_encoder.layers""" , """vision_model.encoder.stages""" )
if "blocks" in name and "res" not in name:
__lowerCAmelCase = name.replace("""blocks""" , """layers""" )
if "attn" in name and "pre_assign" not in name:
__lowerCAmelCase = name.replace("""attn""" , """self_attn""" )
if "proj" in name and "self_attn" in name and "text" not in name:
__lowerCAmelCase = name.replace("""proj""" , """out_proj""" )
if "pre_assign_attn.attn.proj" in name:
__lowerCAmelCase = name.replace("""pre_assign_attn.attn.proj""" , """pre_assign_attn.attn.out_proj""" )
if "norm1" in name:
__lowerCAmelCase = name.replace("""norm1""" , """layer_norm1""" )
if "norm2" in name and "pre_assign" not in name:
__lowerCAmelCase = name.replace("""norm2""" , """layer_norm2""" )
if "img_encoder.norm" in name:
__lowerCAmelCase = name.replace("""img_encoder.norm""" , """vision_model.layernorm""" )
# text encoder
if "text_encoder.token_embedding" in name:
__lowerCAmelCase = name.replace("""text_encoder.token_embedding""" , """text_model.embeddings.token_embedding""" )
if "text_encoder.positional_embedding" in name:
__lowerCAmelCase = name.replace("""text_encoder.positional_embedding""" , """text_model.embeddings.position_embedding.weight""" )
if "text_encoder.transformer.resblocks." in name:
__lowerCAmelCase = name.replace("""text_encoder.transformer.resblocks.""" , """text_model.encoder.layers.""" )
if "ln_1" in name:
__lowerCAmelCase = name.replace("""ln_1""" , """layer_norm1""" )
if "ln_2" in name:
__lowerCAmelCase = name.replace("""ln_2""" , """layer_norm2""" )
if "c_fc" in name:
__lowerCAmelCase = name.replace("""c_fc""" , """fc1""" )
if "c_proj" in name:
__lowerCAmelCase = name.replace("""c_proj""" , """fc2""" )
if "text_encoder" in name:
__lowerCAmelCase = name.replace("""text_encoder""" , """text_model""" )
if "ln_final" in name:
__lowerCAmelCase = name.replace("""ln_final""" , """final_layer_norm""" )
# projection layers
if "img_projector.linear_hidden." in name:
__lowerCAmelCase = name.replace("""img_projector.linear_hidden.""" , """visual_projection.""" )
if "img_projector.linear_out." in name:
__lowerCAmelCase = name.replace("""img_projector.linear_out.""" , """visual_projection.3.""" )
if "text_projector.linear_hidden" in name:
__lowerCAmelCase = name.replace("""text_projector.linear_hidden""" , """text_projection""" )
if "text_projector.linear_out" in name:
__lowerCAmelCase = name.replace("""text_projector.linear_out""" , """text_projection.3""" )
return name
def _lowerCAmelCase ( lowercase , lowercase ) -> Dict:
for key in orig_state_dict.copy().keys():
__lowerCAmelCase = orig_state_dict.pop(lowercase )
if "qkv" in key:
# weights and biases of the key, value and query projections of vision encoder's attention layers require special treatment:
# we need to split them up into separate matrices/vectors
__lowerCAmelCase = key.split(""".""" )
__lowerCAmelCase , __lowerCAmelCase = int(key_split[2] ), int(key_split[4] )
__lowerCAmelCase = config.vision_config.hidden_size
if "weight" in key:
__lowerCAmelCase = val[:dim, :]
__lowerCAmelCase = val[dim : dim * 2, :]
__lowerCAmelCase = val[-dim:, :]
else:
__lowerCAmelCase = val[:dim]
__lowerCAmelCase = val[dim : dim * 2]
__lowerCAmelCase = val[-dim:]
elif "in_proj" in key:
# weights and biases of the key, value and query projections of text encoder's attention layers require special treatment:
# we need to split them up into separate matrices/vectors
__lowerCAmelCase = key.split(""".""" )
__lowerCAmelCase = int(key_split[3] )
__lowerCAmelCase = config.text_config.hidden_size
if "weight" in key:
__lowerCAmelCase = val[:dim, :]
__lowerCAmelCase = val[
dim : dim * 2, :
]
__lowerCAmelCase = val[-dim:, :]
else:
__lowerCAmelCase = val[:dim]
__lowerCAmelCase = val[dim : dim * 2]
__lowerCAmelCase = val[-dim:]
else:
__lowerCAmelCase = rename_key(lowercase )
# squeeze if necessary
if (
"text_projection.0" in new_name
or "text_projection.3" in new_name
or "visual_projection.0" in new_name
or "visual_projection.3" in new_name
):
__lowerCAmelCase = val.squeeze_()
else:
__lowerCAmelCase = val
return orig_state_dict
def _lowerCAmelCase ( ) -> str:
__lowerCAmelCase = """http://images.cocodataset.org/val2017/000000039769.jpg"""
__lowerCAmelCase = Image.open(requests.get(lowercase , stream=lowercase ).raw )
return im
@torch.no_grad()
def _lowerCAmelCase ( lowercase , lowercase , lowercase="groupvit-gcc-yfcc" , lowercase=False ) -> List[Any]:
__lowerCAmelCase = GroupViTConfig()
__lowerCAmelCase = GroupViTModel(lowercase ).eval()
__lowerCAmelCase = torch.load(lowercase , map_location="""cpu""" )["""model"""]
__lowerCAmelCase = convert_state_dict(lowercase , lowercase )
__lowerCAmelCase , __lowerCAmelCase = model.load_state_dict(lowercase , strict=lowercase )
assert missing_keys == ["text_model.embeddings.position_ids"]
assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(lowercase ) == 0)
# verify result
__lowerCAmelCase = CLIPProcessor.from_pretrained("""openai/clip-vit-base-patch32""" )
__lowerCAmelCase = prepare_img()
__lowerCAmelCase = processor(text=["""a photo of a cat""", """a photo of a dog"""] , images=lowercase , padding=lowercase , return_tensors="""pt""" )
with torch.no_grad():
__lowerCAmelCase = model(**lowercase )
if model_name == "groupvit-gcc-yfcc":
__lowerCAmelCase = torch.tensor([[13.35_23, 6.36_29]] )
elif model_name == "groupvit-gcc-redcaps":
__lowerCAmelCase = torch.tensor([[16.18_73, 8.62_30]] )
else:
raise ValueError(f'Model name {model_name} not supported.' )
assert torch.allclose(outputs.logits_per_image , lowercase , atol=1e-3 )
processor.save_pretrained(lowercase )
model.save_pretrained(lowercase )
print("""Successfully saved processor and model to""" , lowercase )
if push_to_hub:
print("""Pushing to the hub...""" )
processor.push_to_hub(lowercase , organization="""nielsr""" )
model.push_to_hub(lowercase , organization="""nielsr""" )
if __name__ == "__main__":
_a : int = argparse.ArgumentParser()
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to dump the processor and PyTorch model."""
)
parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to GroupViT checkpoint""")
parser.add_argument(
"""--model_name""",
default="""groupvit-gccy-fcc""",
type=str,
help="""Name of the model. Expecting either 'groupvit-gcc-yfcc' or 'groupvit-gcc-redcaps'""",
)
parser.add_argument(
"""--push_to_hub""",
action="""store_true""",
help="""Whether or not to push the converted model and processor to the 🤗 hub using the provided `model_name`.""",
)
_a : List[str] = parser.parse_args()
convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
| 689 | 1 |
from collections import deque
def __lowerCAmelCase (SCREAMING_SNAKE_CASE )-> Dict:
"""simple docstring"""
snake_case_ = len(SCREAMING_SNAKE_CASE )
snake_case_ = deque()
snake_case_ = [False for _ in range(SCREAMING_SNAKE_CASE )]
snake_case_ = [-1 for _ in range(SCREAMING_SNAKE_CASE )]
snake_case_ = index_of[:]
def strong_connect(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
snake_case_ = index # the number when this node is seen
snake_case_ = index # lowest rank node reachable from here
index += 1
stack.append(SCREAMING_SNAKE_CASE )
snake_case_ = True
for w in g[v]:
if index_of[w] == -1:
snake_case_ = strong_connect(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
snake_case_ = (
lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v]
)
elif on_stack[w]:
snake_case_ = (
lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v]
)
if lowlink_of[v] == index_of[v]:
snake_case_ = []
snake_case_ = stack.pop()
snake_case_ = False
component.append(SCREAMING_SNAKE_CASE )
while w != v:
snake_case_ = stack.pop()
snake_case_ = False
component.append(SCREAMING_SNAKE_CASE )
components.append(SCREAMING_SNAKE_CASE )
return index
snake_case_ = []
for v in range(SCREAMING_SNAKE_CASE ):
if index_of[v] == -1:
strong_connect(SCREAMING_SNAKE_CASE , 0 , SCREAMING_SNAKE_CASE )
return components
def __lowerCAmelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )-> Dict:
"""simple docstring"""
snake_case_ = [[] for _ in range(SCREAMING_SNAKE_CASE )]
for u, v in edges:
g[u].append(SCREAMING_SNAKE_CASE )
return g
if __name__ == "__main__":
# Test
UpperCAmelCase = 7
UpperCAmelCase = [0, 0, 1, 2, 3, 3, 4, 4, 6]
UpperCAmelCase = [1, 3, 2, 0, 1, 4, 5, 6, 5]
UpperCAmelCase = [(u, v) for u, v in zip(source, target)]
UpperCAmelCase = create_graph(n_vertices, edges)
assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
| 531 |
import unittest
import numpy as np
from diffusers import LMSDiscreteScheduler, OnnxStableDiffusionInpaintPipeline
from diffusers.utils.testing_utils import (
is_onnx_available,
load_image,
nightly,
require_onnxruntime,
require_torch_gpu,
)
from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin
if is_onnx_available():
import onnxruntime as ort
class lowerCAmelCase_ ( lowerCamelCase__ , unittest.TestCase ):
'''simple docstring'''
pass
@nightly
@require_onnxruntime
@require_torch_gpu
class lowerCAmelCase_ ( unittest.TestCase ):
'''simple docstring'''
@property
def UpperCamelCase__ ( self ):
return (
"CUDAExecutionProvider",
{
"gpu_mem_limit": "15000000000", # 15GB
"arena_extend_strategy": "kSameAsRequested",
},
)
@property
def UpperCamelCase__ ( self ):
snake_case_ = ort.SessionOptions()
snake_case_ = False
return options
def UpperCamelCase__ ( self ):
snake_case_ = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/in_paint/overture-creations-5sI6fQgYIuo.png''' )
snake_case_ = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/in_paint/overture-creations-5sI6fQgYIuo_mask.png''' )
snake_case_ = OnnxStableDiffusionInpaintPipeline.from_pretrained(
'''runwayml/stable-diffusion-inpainting''' , revision='''onnx''' , safety_checker=_UpperCAmelCase , feature_extractor=_UpperCAmelCase , provider=self.gpu_provider , sess_options=self.gpu_options , )
pipe.set_progress_bar_config(disable=_UpperCAmelCase )
snake_case_ = '''A red cat sitting on a park bench'''
snake_case_ = np.random.RandomState(0 )
snake_case_ = pipe(
prompt=_UpperCAmelCase , image=_UpperCAmelCase , mask_image=_UpperCAmelCase , guidance_scale=7.5 , num_inference_steps=10 , generator=_UpperCAmelCase , output_type='''np''' , )
snake_case_ = output.images
snake_case_ = images[0, 2_55:2_58, 2_55:2_58, -1]
assert images.shape == (1, 5_12, 5_12, 3)
snake_case_ = np.array([0.2_514, 0.3_007, 0.3_517, 0.1_790, 0.2_382, 0.3_167, 0.1_944, 0.2_273, 0.2_464] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
def UpperCamelCase__ ( self ):
snake_case_ = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/in_paint/overture-creations-5sI6fQgYIuo.png''' )
snake_case_ = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/in_paint/overture-creations-5sI6fQgYIuo_mask.png''' )
snake_case_ = LMSDiscreteScheduler.from_pretrained(
'''runwayml/stable-diffusion-inpainting''' , subfolder='''scheduler''' , revision='''onnx''' )
snake_case_ = OnnxStableDiffusionInpaintPipeline.from_pretrained(
'''runwayml/stable-diffusion-inpainting''' , revision='''onnx''' , scheduler=_UpperCAmelCase , safety_checker=_UpperCAmelCase , feature_extractor=_UpperCAmelCase , provider=self.gpu_provider , sess_options=self.gpu_options , )
pipe.set_progress_bar_config(disable=_UpperCAmelCase )
snake_case_ = '''A red cat sitting on a park bench'''
snake_case_ = np.random.RandomState(0 )
snake_case_ = pipe(
prompt=_UpperCAmelCase , image=_UpperCAmelCase , mask_image=_UpperCAmelCase , guidance_scale=7.5 , num_inference_steps=20 , generator=_UpperCAmelCase , output_type='''np''' , )
snake_case_ = output.images
snake_case_ = images[0, 2_55:2_58, 2_55:2_58, -1]
assert images.shape == (1, 5_12, 5_12, 3)
snake_case_ = np.array([0.0_086, 0.0_077, 0.0_083, 0.0_093, 0.0_107, 0.0_139, 0.0_094, 0.0_097, 0.0_125] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
| 531 | 1 |
"""simple docstring"""
def UpperCAmelCase ( a__ , a__ ):
'''simple docstring'''
lowerCAmelCase :Tuple = len(a__ )
print('The following activities are selected:' )
# The first activity is always selected
lowerCAmelCase :Dict = 0
print(a__ , end=',' )
# Consider rest of the activities
for j in range(a__ ):
# If this activity has start time greater than
# or equal to the finish time of previously
# selected activity, then select it
if start[j] >= finish[i]:
print(a__ , end=',' )
lowerCAmelCase :List[str] = j
if __name__ == "__main__":
import doctest
doctest.testmod()
__SCREAMING_SNAKE_CASE = [1, 3, 0, 5, 8, 5]
__SCREAMING_SNAKE_CASE = [2, 4, 6, 7, 9, 9]
print_max_activities(start, finish)
| 553 |
"""simple docstring"""
import qiskit
def UpperCAmelCase ( a__ , a__ ):
'''simple docstring'''
lowerCAmelCase :List[Any] = qiskit.Aer.get_backend('aer_simulator' )
# Create a Quantum Circuit acting on the q register
lowerCAmelCase :Optional[int] = qiskit.QuantumCircuit(a__ , a__ )
# Apply X (NOT) Gate to Qubits 0 & 1
circuit.x(0 )
circuit.x(1 )
# Map the quantum measurement to the classical bits
circuit.measure([0, 1] , [0, 1] )
# Execute the circuit on the qasm simulator
lowerCAmelCase :Dict = qiskit.execute(a__ , a__ , shots=10_00 )
# Return the histogram data of the results of the experiment.
return job.result().get_counts(a__ )
if __name__ == "__main__":
__SCREAMING_SNAKE_CASE = single_qubit_measure(2, 2)
print(F"""Total count for various states are: {counts}""")
| 553 | 1 |
import argparse
import logging
import os
import time
import timeit
import datasets
import numpy as np
import pycuda.autoinit # noqa: F401
import pycuda.driver as cuda
import tensorrt as trt
import torch
from absl import logging as absl_logging
from accelerate import Accelerator
from datasets import load_dataset, load_metric
from torch.utils.data import DataLoader
from utils_qa import postprocess_qa_predictions
import transformers
from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed
from transformers.trainer_pt_utils import nested_concat, nested_truncate
__lowercase = trt.Logger(trt.Logger.WARNING)
__lowercase = absl_logging.get_absl_logger()
absl_logger.setLevel(logging.WARNING)
__lowercase = logging.getLogger(__name__)
__lowercase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--onnx_model_path""",
default=None,
type=str,
required=True,
help="""Path to ONNX model: """,
)
parser.add_argument(
"""--output_dir""",
default=None,
type=str,
required=True,
help="""The output directory where the model checkpoints and predictions will be written.""",
)
# Other parameters
parser.add_argument(
"""--tokenizer_name""",
default="""""",
type=str,
required=True,
help="""Pretrained tokenizer name or path if not the same as model_name""",
)
parser.add_argument(
"""--version_2_with_negative""",
action="""store_true""",
help="""If true, the SQuAD examples contain some that do not have an answer.""",
)
parser.add_argument(
"""--null_score_diff_threshold""",
type=float,
default=0.0,
help="""If null_score - best_non_null is greater than the threshold predict null.""",
)
parser.add_argument(
"""--max_seq_length""",
default=384,
type=int,
help=(
"""The maximum total input sequence length after WordPiece tokenization. Sequences """
"""longer than this will be truncated, and sequences shorter than this will be padded."""
),
)
parser.add_argument(
"""--doc_stride""",
default=128,
type=int,
help="""When splitting up a long document into chunks, how much stride to take between chunks.""",
)
parser.add_argument("""--per_device_eval_batch_size""", default=8, type=int, help="""Batch size per GPU/CPU for evaluation.""")
parser.add_argument(
"""--n_best_size""",
default=20,
type=int,
help="""The total number of n-best predictions to generate in the nbest_predictions.json output file.""",
)
parser.add_argument(
"""--max_answer_length""",
default=30,
type=int,
help=(
"""The maximum length of an answer that can be generated. This is needed because the start """
"""and end predictions are not conditioned on one another."""
),
)
parser.add_argument("""--seed""", type=int, default=42, help="""random seed for initialization""")
parser.add_argument(
"""--dataset_name""",
type=str,
default=None,
required=True,
help="""The name of the dataset to use (via the datasets library).""",
)
parser.add_argument(
"""--dataset_config_name""",
type=str,
default=None,
help="""The configuration name of the dataset to use (via the datasets library).""",
)
parser.add_argument(
"""--preprocessing_num_workers""", type=int, default=4, help="""A csv or a json file containing the training data."""
)
parser.add_argument("""--overwrite_cache""", action="""store_true""", help="""Overwrite the cached training and evaluation sets""")
parser.add_argument(
"""--fp16""",
action="""store_true""",
help="""Whether to use 16-bit (mixed) precision instead of 32-bit""",
)
parser.add_argument(
"""--int8""",
action="""store_true""",
help="""Whether to use INT8""",
)
__lowercase = parser.parse_args()
if args.tokenizer_name:
__lowercase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True)
else:
raise ValueError(
"""You are instantiating a new tokenizer from scratch. This is not supported by this script."""
"""You can do it from another script, save it, and load it from here, using --tokenizer_name."""
)
logger.info("""Training/evaluation parameters %s""", args)
__lowercase = args.per_device_eval_batch_size
__lowercase = (args.eval_batch_size, args.max_seq_length)
# TRT Engine properties
__lowercase = True
__lowercase = """temp_engine/bert-fp32.engine"""
if args.fpaa:
__lowercase = """temp_engine/bert-fp16.engine"""
if args.inta:
__lowercase = """temp_engine/bert-int8.engine"""
# import ONNX file
if not os.path.exists("""temp_engine"""):
os.makedirs("""temp_engine""")
__lowercase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser(
network, TRT_LOGGER
) as parser:
with open(args.onnx_model_path, """rb""") as model:
if not parser.parse(model.read()):
for error in range(parser.num_errors):
print(parser.get_error(error))
# Query input names and shapes from parsed TensorRT network
__lowercase = [network.get_input(i) for i in range(network.num_inputs)]
__lowercase = [_input.name for _input in network_inputs] # ex: ["actual_input1"]
with builder.create_builder_config() as config:
__lowercase = 1 << 50
if STRICT_TYPES:
config.set_flag(trt.BuilderFlag.STRICT_TYPES)
if args.fpaa:
config.set_flag(trt.BuilderFlag.FPaa)
if args.inta:
config.set_flag(trt.BuilderFlag.INTa)
__lowercase = builder.create_optimization_profile()
config.add_optimization_profile(profile)
for i in range(len(input_names)):
profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE)
__lowercase = builder.build_engine(network, config)
# serialize_engine and store in file (can be directly loaded and deserialized):
with open(engine_name, """wb""") as f:
f.write(engine.serialize())
def _lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
'''simple docstring'''
A_ = np.asarray(inputs['''input_ids'''] , dtype=np.intaa )
A_ = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa )
A_ = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa )
# Copy inputs
cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , SCREAMING_SNAKE_CASE )
cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , SCREAMING_SNAKE_CASE )
cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , SCREAMING_SNAKE_CASE )
# start time
A_ = time.time()
# Run inference
context.execute_async(
bindings=[int(SCREAMING_SNAKE_CASE ) for d_inp in d_inputs] + [int(SCREAMING_SNAKE_CASE ), int(SCREAMING_SNAKE_CASE )] , stream_handle=stream.handle )
# Transfer predictions back from GPU
cuda.memcpy_dtoh_async(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
cuda.memcpy_dtoh_async(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
# Synchronize the stream and take time
stream.synchronize()
# end time
A_ = time.time()
A_ = end_time - start_time
A_ = (h_outputa, h_outputa)
# print(outputs)
return outputs, infer_time
# Initialize the accelerator. We will let the accelerator handle device placement for us in this example.
__lowercase = Accelerator()
# Make one log on every process with the configuration for debugging.
logging.basicConfig(
format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""",
datefmt="""%m/%d/%Y %H:%M:%S""",
level=logging.INFO,
)
# Setup logging, we only want one process per machine to log things on the screen.
# accelerator.is_local_main_process is only True for one process per machine.
logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR)
if accelerator.is_local_main_process:
datasets.utils.logging.set_verbosity_warning()
transformers.utils.logging.set_verbosity_info()
else:
datasets.utils.logging.set_verbosity_error()
transformers.utils.logging.set_verbosity_error()
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
# (the dataset will be downloaded automatically from the datasets Hub).
#
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
# 'text' is found. You can easily tweak this behavior (see below).
if args.dataset_name is not None:
# Downloading and loading a dataset from the hub.
__lowercase = load_dataset(args.dataset_name, args.dataset_config_name)
else:
raise ValueError("""Evaluation requires a dataset name""")
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
# Preprocessing the datasets.
# Preprocessing is slighlty different for training and evaluation.
__lowercase = raw_datasets["""validation"""].column_names
__lowercase = """question""" if """question""" in column_names else column_names[0]
__lowercase = """context""" if """context""" in column_names else column_names[1]
__lowercase = """answers""" if """answers""" in column_names else column_names[2]
# Padding side determines if we do (question|context) or (context|question).
__lowercase = tokenizer.padding_side == """right"""
if args.max_seq_length > tokenizer.model_max_length:
logger.warning(
f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the'
f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.'
)
__lowercase = min(args.max_seq_length, tokenizer.model_max_length)
def _lowerCamelCase ( SCREAMING_SNAKE_CASE ):
'''simple docstring'''
A_ = [q.lstrip() for q in examples[question_column_name]]
# Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results
# in one example possible giving several features when a context is long, each of those features having a
# context that overlaps a bit the context of the previous feature.
A_ = tokenizer(
examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=SCREAMING_SNAKE_CASE , stride=args.doc_stride , return_overflowing_tokens=SCREAMING_SNAKE_CASE , return_offsets_mapping=SCREAMING_SNAKE_CASE , padding='''max_length''' , )
# Since one example might give us several features if it has a long context, we need a map from a feature to
# its corresponding example. This key gives us just that.
A_ = tokenized_examples.pop('''overflow_to_sample_mapping''' )
# For evaluation, we will need to convert our predictions to substrings of the context, so we keep the
# corresponding example_id and we will store the offset mappings.
A_ = []
for i in range(len(tokenized_examples['''input_ids'''] ) ):
# Grab the sequence corresponding to that example (to know what is the context and what is the question).
A_ = tokenized_examples.sequence_ids(SCREAMING_SNAKE_CASE )
A_ = 1 if pad_on_right else 0
# One example can give several spans, this is the index of the example containing this span of text.
A_ = sample_mapping[i]
tokenized_examples["example_id"].append(examples['''id'''][sample_index] )
# Set to None the offset_mapping that are not part of the context so it's easy to determine if a token
# position is part of the context or not.
A_ = [
(o if sequence_ids[k] == context_index else None)
for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] )
]
return tokenized_examples
__lowercase = raw_datasets["""validation"""]
# Validation Feature Creation
__lowercase = eval_examples.map(
prepare_validation_features,
batched=True,
num_proc=args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not args.overwrite_cache,
desc="""Running tokenizer on validation dataset""",
)
__lowercase = default_data_collator
__lowercase = eval_dataset.remove_columns(["""example_id""", """offset_mapping"""])
__lowercase = DataLoader(
eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size
)
def _lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE="eval" ):
'''simple docstring'''
A_ = postprocess_qa_predictions(
examples=SCREAMING_SNAKE_CASE , features=SCREAMING_SNAKE_CASE , predictions=SCREAMING_SNAKE_CASE , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=SCREAMING_SNAKE_CASE , )
# Format the result to the format the metric expects.
if args.version_2_with_negative:
A_ = [
{'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items()
]
else:
A_ = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()]
A_ = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples]
return EvalPrediction(predictions=SCREAMING_SNAKE_CASE , label_ids=SCREAMING_SNAKE_CASE )
__lowercase = load_metric("""squad_v2""" if args.version_2_with_negative else """squad""")
# Evaluation!
logger.info("""Loading ONNX model %s for evaluation""", args.onnx_model_path)
with open(engine_name, """rb""") as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine(
f.read()
) as engine, engine.create_execution_context() as context:
# setup for TRT inferrence
for i in range(len(input_names)):
context.set_binding_shape(i, INPUT_SHAPE)
assert context.all_binding_shapes_specified
def _lowerCamelCase ( SCREAMING_SNAKE_CASE ):
'''simple docstring'''
return trt.volume(engine.get_binding_shape(SCREAMING_SNAKE_CASE ) ) * engine.get_binding_dtype(SCREAMING_SNAKE_CASE ).itemsize
# Allocate device memory for inputs and outputs.
__lowercase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)]
# Allocate output buffer
__lowercase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa)
__lowercase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa)
__lowercase = cuda.mem_alloc(h_outputa.nbytes)
__lowercase = cuda.mem_alloc(h_outputa.nbytes)
# Create a stream in which to copy inputs/outputs and run inference.
__lowercase = cuda.Stream()
# Evaluation
logger.info("""***** Running Evaluation *****""")
logger.info(f' Num examples = {len(eval_dataset)}')
logger.info(f' Batch size = {args.per_device_eval_batch_size}')
__lowercase = 0.0
__lowercase = 0
__lowercase = timeit.default_timer()
__lowercase = None
for step, batch in enumerate(eval_dataloader):
__lowercase , __lowercase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream)
total_time += infer_time
niter += 1
__lowercase , __lowercase = outputs
__lowercase = torch.tensor(start_logits)
__lowercase = torch.tensor(end_logits)
# necessary to pad predictions and labels for being gathered
__lowercase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-100)
__lowercase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-100)
__lowercase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy())
__lowercase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100)
if all_preds is not None:
__lowercase = nested_truncate(all_preds, len(eval_dataset))
__lowercase = timeit.default_timer() - start_time
logger.info(""" Evaluation done in total %f secs (%f sec per example)""", evalTime, evalTime / len(eval_dataset))
# Inference time from TRT
logger.info("""Average Inference Time = {:.3f} ms""".format(total_time * 1000 / niter))
logger.info("""Total Inference Time = {:.3f} ms""".format(total_time * 1000))
logger.info("""Total Number of Inference = %d""", niter)
__lowercase = post_processing_function(eval_examples, eval_dataset, all_preds)
__lowercase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids)
logger.info(f'Evaluation metrics: {eval_metric}')
| 563 |
def _lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
'''simple docstring'''
A_ = 0
while b > 0:
if b & 1:
res += a
a += a
b >>= 1
return res
def _lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
'''simple docstring'''
A_ = 0
while b > 0:
if b & 1:
A_ = ((res % c) + (a % c)) % c
a += a
b >>= 1
return res
| 563 | 1 |
def SCREAMING_SNAKE_CASE__ ( ):
return [list(range(1_000 - i , -1_000 - i , -1 ) ) for i in range(1_000 )]
_lowerCamelCase = generate_large_matrix()
_lowerCamelCase = (
[[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]],
[[3, 2], [1, 0]],
[[7, 7, 6]],
[[7, 7, 6], [-1, -2, -3]],
grid,
)
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[int]] ):
assert all(row == sorted(UpperCamelCase__ , reverse=UpperCamelCase__ ) for row in grid )
assert all(list(UpperCamelCase__ ) == sorted(UpperCamelCase__ , reverse=UpperCamelCase__ ) for col in zip(*UpperCamelCase__ ) )
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[int] ):
SCREAMING_SNAKE_CASE__ = 0
SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) - 1
# Edge cases such as no values or all numbers are negative.
if not array or array[0] < 0:
return 0
while right + 1 > left:
SCREAMING_SNAKE_CASE__ = (left + right) // 2
SCREAMING_SNAKE_CASE__ = array[mid]
# Num must be negative and the index must be greater than or equal to 0.
if num < 0 and array[mid - 1] >= 0:
return mid
if num >= 0:
SCREAMING_SNAKE_CASE__ = mid + 1
else:
SCREAMING_SNAKE_CASE__ = mid - 1
# No negative numbers so return the last index of the array + 1 which is the length.
return len(UpperCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[int]] ):
SCREAMING_SNAKE_CASE__ = 0
SCREAMING_SNAKE_CASE__ = len(grid[0] )
for i in range(len(UpperCamelCase__ ) ):
SCREAMING_SNAKE_CASE__ = find_negative_index(grid[i][:bound] )
total += bound
return (len(UpperCamelCase__ ) * len(grid[0] )) - total
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[int]] ):
return len([number for row in grid for number in row if number < 0] )
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[int]] ):
SCREAMING_SNAKE_CASE__ = 0
for row in grid:
for i, number in enumerate(UpperCamelCase__ ):
if number < 0:
total += len(UpperCamelCase__ ) - i
break
return total
def SCREAMING_SNAKE_CASE__ ( ):
from timeit import timeit
print("""Running benchmarks""" )
SCREAMING_SNAKE_CASE__ = (
"""from __main__ import count_negatives_binary_search, """
"""count_negatives_brute_force, count_negatives_brute_force_with_break, grid"""
)
for func in (
"count_negatives_binary_search", # took 0.7727 seconds
"count_negatives_brute_force_with_break", # took 4.6505 seconds
"count_negatives_brute_force", # took 12.8160 seconds
):
SCREAMING_SNAKE_CASE__ = timeit(f'''{func}(grid=grid)''' , setup=UpperCamelCase__ , number=500 )
print(f'''{func}() took {time:0.4f} seconds''' )
if __name__ == "__main__":
import doctest
doctest.testmod()
benchmark()
| 6 |
import json
import os
from dataclasses import dataclass
from functools import partial
from typing import Callable
import flax.linen as nn
import jax
import jax.numpy as jnp
import joblib
import optax
import wandb
from flax import jax_utils, struct, traverse_util
from flax.serialization import from_bytes, to_bytes
from flax.training import train_state
from flax.training.common_utils import shard
from tqdm.auto import tqdm
from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering
from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule
class UpperCamelCase_ ( UpperCamelCase__ ):
lowerCamelCase_ = 42
lowerCamelCase_ = jnp.floataa
lowerCamelCase_ = True
def _snake_case ( self :Tuple ) -> Optional[Any]:
"""simple docstring"""
super().setup()
SCREAMING_SNAKE_CASE__ = nn.Dense(5 , dtype=self.dtype )
def __call__( self :List[Any] , *__A :int , **__A :Optional[Any] ) -> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = super().__call__(*__A , **__A )
SCREAMING_SNAKE_CASE__ = self.cls(outputs[2] )
return outputs[:2] + (cls_out,)
class UpperCamelCase_ ( UpperCamelCase__ ):
lowerCamelCase_ = FlaxBigBirdForNaturalQuestionsModule
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Tuple , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple ):
def cross_entropy(UpperCamelCase__: List[str] , UpperCamelCase__: List[str] , UpperCamelCase__: List[str]=None ):
SCREAMING_SNAKE_CASE__ = logits.shape[-1]
SCREAMING_SNAKE_CASE__ = (labels[..., None] == jnp.arange(UpperCamelCase__ )[None]).astype("""f4""" )
SCREAMING_SNAKE_CASE__ = jax.nn.log_softmax(UpperCamelCase__ , axis=-1 )
SCREAMING_SNAKE_CASE__ = -jnp.sum(labels * logits , axis=-1 )
if reduction is not None:
SCREAMING_SNAKE_CASE__ = reduction(UpperCamelCase__ )
return loss
SCREAMING_SNAKE_CASE__ = partial(UpperCamelCase__ , reduction=jnp.mean )
SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ )
return (start_loss + end_loss + pooled_loss) / 3
@dataclass
class UpperCamelCase_ :
lowerCamelCase_ = "google/bigbird-roberta-base"
lowerCamelCase_ = 30_00
lowerCamelCase_ = 1_05_00
lowerCamelCase_ = 1_28
lowerCamelCase_ = 3
lowerCamelCase_ = 1
lowerCamelCase_ = 5
# tx_args
lowerCamelCase_ = 3e-5
lowerCamelCase_ = 0.0
lowerCamelCase_ = 2_00_00
lowerCamelCase_ = 0.0095
lowerCamelCase_ = "bigbird-roberta-natural-questions"
lowerCamelCase_ = "training-expt"
lowerCamelCase_ = "data/nq-training.jsonl"
lowerCamelCase_ = "data/nq-validation.jsonl"
def _snake_case ( self :str ) -> Optional[int]:
"""simple docstring"""
os.makedirs(self.base_dir , exist_ok=__A )
SCREAMING_SNAKE_CASE__ = os.path.join(self.base_dir , self.save_dir )
SCREAMING_SNAKE_CASE__ = self.batch_size_per_device * jax.device_count()
@dataclass
class UpperCamelCase_ :
lowerCamelCase_ = 42
lowerCamelCase_ = 40_96 # no dynamic padding on TPUs
def __call__( self :Optional[Any] , __A :Optional[int] ) -> Tuple:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = self.collate_fn(__A )
SCREAMING_SNAKE_CASE__ = jax.tree_util.tree_map(__A , __A )
return batch
def _snake_case ( self :List[Any] , __A :Union[str, Any] ) -> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.fetch_inputs(features["""input_ids"""] )
SCREAMING_SNAKE_CASE__ = {
"""input_ids""": jnp.array(__A , dtype=jnp.intaa ),
"""attention_mask""": jnp.array(__A , dtype=jnp.intaa ),
"""start_labels""": jnp.array(features["""start_token"""] , dtype=jnp.intaa ),
"""end_labels""": jnp.array(features["""end_token"""] , dtype=jnp.intaa ),
"""pooled_labels""": jnp.array(features["""category"""] , dtype=jnp.intaa ),
}
return batch
def _snake_case ( self :Tuple , __A :list ) -> Dict:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = [self._fetch_inputs(__A ) for ids in input_ids]
return zip(*__A )
def _snake_case ( self :List[str] , __A :list ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = [1 for _ in range(len(__A ) )]
while len(__A ) < self.max_length:
input_ids.append(self.pad_id )
attention_mask.append(0 )
return input_ids, attention_mask
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any]=None ):
if seed is not None:
SCREAMING_SNAKE_CASE__ = dataset.shuffle(seed=UpperCamelCase__ )
for i in range(len(UpperCamelCase__ ) // batch_size ):
SCREAMING_SNAKE_CASE__ = dataset[i * batch_size : (i + 1) * batch_size]
yield dict(UpperCamelCase__ )
@partial(jax.pmap , axis_name="""batch""" )
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Optional[int] , **UpperCamelCase__: Optional[int] ):
def loss_fn(UpperCamelCase__: List[Any] ):
SCREAMING_SNAKE_CASE__ = model_inputs.pop("""start_labels""" )
SCREAMING_SNAKE_CASE__ = model_inputs.pop("""end_labels""" )
SCREAMING_SNAKE_CASE__ = model_inputs.pop("""pooled_labels""" )
SCREAMING_SNAKE_CASE__ = state.apply_fn(**UpperCamelCase__ , params=UpperCamelCase__ , dropout_rng=UpperCamelCase__ , train=UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = outputs
return state.loss_fn(
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , )
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = jax.random.split(UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ = jax.value_and_grad(UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = grad_fn(state.params )
SCREAMING_SNAKE_CASE__ = jax.lax.pmean({"""loss""": loss} , axis_name="""batch""" )
SCREAMING_SNAKE_CASE__ = jax.lax.pmean(UpperCamelCase__ , """batch""" )
SCREAMING_SNAKE_CASE__ = state.apply_gradients(grads=UpperCamelCase__ )
return state, metrics, new_drp_rng
@partial(jax.pmap , axis_name="""batch""" )
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , **UpperCamelCase__: Dict ):
SCREAMING_SNAKE_CASE__ = model_inputs.pop("""start_labels""" )
SCREAMING_SNAKE_CASE__ = model_inputs.pop("""end_labels""" )
SCREAMING_SNAKE_CASE__ = model_inputs.pop("""pooled_labels""" )
SCREAMING_SNAKE_CASE__ = state.apply_fn(**UpperCamelCase__ , params=state.params , train=UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = outputs
SCREAMING_SNAKE_CASE__ = state.loss_fn(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ = jax.lax.pmean({"""loss""": loss} , axis_name="""batch""" )
return metrics
class UpperCamelCase_ ( train_state.TrainState ):
lowerCamelCase_ = struct.field(pytree_node=UpperCamelCase__ )
@dataclass
class UpperCamelCase_ :
lowerCamelCase_ = 42
lowerCamelCase_ = 42
lowerCamelCase_ = 42
lowerCamelCase_ = 42
lowerCamelCase_ = 42
lowerCamelCase_ = 42
lowerCamelCase_ = None
def _snake_case ( self :List[Any] , __A :str , __A :str , __A :str , __A :Tuple=None ) -> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = model.params
SCREAMING_SNAKE_CASE__ = TrainState.create(
apply_fn=model.__call__ , params=__A , tx=__A , loss_fn=__A , )
if ckpt_dir is not None:
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = restore_checkpoint(__A , __A )
SCREAMING_SNAKE_CASE__ = {
"""lr""": args.lr,
"""init_lr""": args.init_lr,
"""warmup_steps""": args.warmup_steps,
"""num_train_steps""": num_train_steps,
"""weight_decay""": args.weight_decay,
}
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = build_tx(**__A )
SCREAMING_SNAKE_CASE__ = train_state.TrainState(
step=__A , apply_fn=model.__call__ , params=__A , tx=__A , opt_state=__A , )
SCREAMING_SNAKE_CASE__ = args
SCREAMING_SNAKE_CASE__ = data_collator
SCREAMING_SNAKE_CASE__ = lr
SCREAMING_SNAKE_CASE__ = params
SCREAMING_SNAKE_CASE__ = jax_utils.replicate(__A )
return state
def _snake_case ( self :Optional[Any] , __A :Optional[int] , __A :int , __A :int ) -> str:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = self.args
SCREAMING_SNAKE_CASE__ = len(__A ) // args.batch_size
SCREAMING_SNAKE_CASE__ = jax.random.PRNGKey(0 )
SCREAMING_SNAKE_CASE__ = jax.random.split(__A , jax.device_count() )
for epoch in range(args.max_epochs ):
SCREAMING_SNAKE_CASE__ = jnp.array(0 , dtype=jnp.floataa )
SCREAMING_SNAKE_CASE__ = get_batched_dataset(__A , args.batch_size , seed=__A )
SCREAMING_SNAKE_CASE__ = 0
for batch in tqdm(__A , total=__A , desc=f'''Running EPOCH-{epoch}''' ):
SCREAMING_SNAKE_CASE__ = self.data_collator(__A )
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.train_step_fn(__A , __A , **__A )
running_loss += jax_utils.unreplicate(metrics["""loss"""] )
i += 1
if i % args.logging_steps == 0:
SCREAMING_SNAKE_CASE__ = jax_utils.unreplicate(state.step )
SCREAMING_SNAKE_CASE__ = running_loss.item() / i
SCREAMING_SNAKE_CASE__ = self.scheduler_fn(state_step - 1 )
SCREAMING_SNAKE_CASE__ = self.evaluate(__A , __A )
SCREAMING_SNAKE_CASE__ = {
"""step""": state_step.item(),
"""eval_loss""": eval_loss.item(),
"""tr_loss""": tr_loss,
"""lr""": lr.item(),
}
tqdm.write(str(__A ) )
self.logger.log(__A , commit=__A )
if i % args.save_steps == 0:
self.save_checkpoint(args.save_dir + f'''-e{epoch}-s{i}''' , state=__A )
def _snake_case ( self :List[str] , __A :Dict , __A :str ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = get_batched_dataset(__A , self.args.batch_size )
SCREAMING_SNAKE_CASE__ = len(__A ) // self.args.batch_size
SCREAMING_SNAKE_CASE__ = jnp.array(0 , dtype=jnp.floataa )
SCREAMING_SNAKE_CASE__ = 0
for batch in tqdm(__A , total=__A , desc="""Evaluating ... """ ):
SCREAMING_SNAKE_CASE__ = self.data_collator(__A )
SCREAMING_SNAKE_CASE__ = self.val_step_fn(__A , **__A )
running_loss += jax_utils.unreplicate(metrics["""loss"""] )
i += 1
return running_loss / i
def _snake_case ( self :List[Any] , __A :Any , __A :Dict ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = jax_utils.unreplicate(__A )
print(f'''SAVING CHECKPOINT IN {save_dir}''' , end=""" ... """ )
self.model_save_fn(__A , params=state.params )
with open(os.path.join(__A , """opt_state.msgpack""" ) , """wb""" ) as f:
f.write(to_bytes(state.opt_state ) )
joblib.dump(self.args , os.path.join(__A , """args.joblib""" ) )
joblib.dump(self.data_collator , os.path.join(__A , """data_collator.joblib""" ) )
with open(os.path.join(__A , """training_state.json""" ) , """w""" ) as f:
json.dump({"""step""": state.step.item()} , __A )
print("""DONE""" )
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Optional[Any] ):
print(f'''RESTORING CHECKPOINT FROM {save_dir}''' , end=""" ... """ )
with open(os.path.join(UpperCamelCase__ , """flax_model.msgpack""" ) , """rb""" ) as f:
SCREAMING_SNAKE_CASE__ = from_bytes(state.params , f.read() )
with open(os.path.join(UpperCamelCase__ , """opt_state.msgpack""" ) , """rb""" ) as f:
SCREAMING_SNAKE_CASE__ = from_bytes(state.opt_state , f.read() )
SCREAMING_SNAKE_CASE__ = joblib.load(os.path.join(UpperCamelCase__ , """args.joblib""" ) )
SCREAMING_SNAKE_CASE__ = joblib.load(os.path.join(UpperCamelCase__ , """data_collator.joblib""" ) )
with open(os.path.join(UpperCamelCase__ , """training_state.json""" ) , """r""" ) as f:
SCREAMING_SNAKE_CASE__ = json.load(UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ = training_state["""step"""]
print("""DONE""" )
return params, opt_state, step, args, data_collator
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Dict ):
SCREAMING_SNAKE_CASE__ = num_train_steps - warmup_steps
SCREAMING_SNAKE_CASE__ = optax.linear_schedule(init_value=UpperCamelCase__ , end_value=UpperCamelCase__ , transition_steps=UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ = optax.linear_schedule(init_value=UpperCamelCase__ , end_value=1e-7 , transition_steps=UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ = optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] )
return lr
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple , UpperCamelCase__: Tuple , UpperCamelCase__: Tuple ):
def weight_decay_mask(UpperCamelCase__: Any ):
SCREAMING_SNAKE_CASE__ = traverse_util.flatten_dict(UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ = {k: (v[-1] != """bias""" and v[-2:] != ("""LayerNorm""", """scale""")) for k, v in params.items()}
return traverse_util.unflatten_dict(UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ = scheduler_fn(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ = optax.adamw(learning_rate=UpperCamelCase__ , weight_decay=UpperCamelCase__ , mask=UpperCamelCase__ )
return tx, lr
| 6 | 1 |
'''simple docstring'''
from __future__ import annotations
def a__ ( _SCREAMING_SNAKE_CASE : Tuple ) -> Optional[Any]:
"""simple docstring"""
UpperCAmelCase_ : Optional[int] = 0.00
UpperCAmelCase_ : List[Any] = 0
for resistor in resistors:
if resistor <= 0:
UpperCAmelCase_ : Any = F'''Resistor at index {index} has a negative or zero value!'''
raise ValueError(_SCREAMING_SNAKE_CASE )
first_sum += 1 / float(_SCREAMING_SNAKE_CASE )
index += 1
return 1 / first_sum
def a__ ( _SCREAMING_SNAKE_CASE : Tuple ) -> Any:
"""simple docstring"""
UpperCAmelCase_ : Tuple = 0.00
UpperCAmelCase_ : Union[str, Any] = 0
for resistor in resistors:
sum_r += resistor
if resistor < 0:
UpperCAmelCase_ : int = F'''Resistor at index {index} has a negative value!'''
raise ValueError(_SCREAMING_SNAKE_CASE )
index += 1
return sum_r
if __name__ == "__main__":
import doctest
doctest.testmod()
| 717 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
_lowerCamelCase = {
"""configuration_swinv2""": ["""SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Swinv2Config"""],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase = [
"""SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""Swinv2ForImageClassification""",
"""Swinv2ForMaskedImageModeling""",
"""Swinv2Model""",
"""Swinv2PreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_swinva import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinvaConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_swinva import (
SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST,
SwinvaForImageClassification,
SwinvaForMaskedImageModeling,
SwinvaModel,
SwinvaPreTrainedModel,
)
else:
import sys
_lowerCamelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 323 | 0 |
'''simple docstring'''
from pathlib import Path
import fire
from tqdm import tqdm
def lowerCamelCase_ ( __UpperCamelCase : Optional[int]="ro" , __UpperCamelCase : Dict="en" , __UpperCamelCase : Union[str, Any]="wmt16" , __UpperCamelCase : Optional[Any]=None ) -> None:
"""simple docstring"""
try:
import datasets
except (ModuleNotFoundError, ImportError):
raise ImportError('run pip install datasets' )
_A = F'{src_lang}-{tgt_lang}'
print(F'Converting {dataset}-{pair}' )
_A = datasets.load_dataset(__UpperCamelCase , __UpperCamelCase )
if save_dir is None:
_A = F'{dataset}-{pair}'
_A = Path(__UpperCamelCase )
save_dir.mkdir(exist_ok=__UpperCamelCase )
for split in ds.keys():
print(F'Splitting {split} with {ds[split].num_rows} records' )
# to save to val.source, val.target like summary datasets
_A = 'val' if split == 'validation' else split
_A = save_dir.joinpath(F'{fn}.source' )
_A = save_dir.joinpath(F'{fn}.target' )
_A = src_path.open('w+' )
_A = tgt_path.open('w+' )
# reader is the bottleneck so writing one record at a time doesn't slow things down
for x in tqdm(ds[split] ):
_A = x['translation']
src_fp.write(ex[src_lang] + '\n' )
tgt_fp.write(ex[tgt_lang] + '\n' )
print(F'Saved {dataset} dataset to {save_dir}' )
if __name__ == "__main__":
fire.Fire(download_wmt_dataset)
| 292 |
'''simple docstring'''
def lowerCamelCase_ ( __UpperCamelCase : int ) -> list:
"""simple docstring"""
_A = int(__UpperCamelCase )
if n_element < 1:
_A = ValueError('a should be a positive number' )
raise my_error
_A = [1]
_A , _A , _A = (0, 0, 0)
_A = 1
while index < n_element:
while hamming_list[i] * 2 <= hamming_list[-1]:
i += 1
while hamming_list[j] * 3 <= hamming_list[-1]:
j += 1
while hamming_list[k] * 5 <= hamming_list[-1]:
k += 1
hamming_list.append(
min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) )
index += 1
return hamming_list
if __name__ == "__main__":
lowerCAmelCase = input("""Enter the last number (nth term) of the Hamming Number Series: """)
print("""Formula of Hamming Number Series => 2^i * 3^j * 5^k""")
lowerCAmelCase = hamming(int(n))
print("""-----------------------------------------------------""")
print(F'The list with nth numbers is: {hamming_numbers}')
print("""-----------------------------------------------------""")
| 292 | 1 |
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
from ..auto import CONFIG_MAPPING
UpperCamelCase__ =logging.get_logger(__name__)
UpperCamelCase__ ={
'microsoft/table-transformer-detection': (
'https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json'
),
}
class lowerCAmelCase__( __lowercase ):
'''simple docstring'''
__snake_case = 'table-transformer'
__snake_case = ['past_key_values']
__snake_case = {
'hidden_size': 'd_model',
'num_attention_heads': 'encoder_attention_heads',
}
def __init__( self , __lowerCamelCase=True , __lowerCamelCase=None , __lowerCamelCase=3 , __lowerCamelCase=1_0_0 , __lowerCamelCase=6 , __lowerCamelCase=2_0_4_8 , __lowerCamelCase=8 , __lowerCamelCase=6 , __lowerCamelCase=2_0_4_8 , __lowerCamelCase=8 , __lowerCamelCase=0.0 , __lowerCamelCase=0.0 , __lowerCamelCase=True , __lowerCamelCase="relu" , __lowerCamelCase=2_5_6 , __lowerCamelCase=0.1 , __lowerCamelCase=0.0 , __lowerCamelCase=0.0 , __lowerCamelCase=0.02 , __lowerCamelCase=1.0 , __lowerCamelCase=False , __lowerCamelCase="sine" , __lowerCamelCase="resnet50" , __lowerCamelCase=True , __lowerCamelCase=False , __lowerCamelCase=1 , __lowerCamelCase=5 , __lowerCamelCase=2 , __lowerCamelCase=1 , __lowerCamelCase=1 , __lowerCamelCase=5 , __lowerCamelCase=2 , __lowerCamelCase=0.1 , **__lowerCamelCase , ) -> Optional[Any]:
if backbone_config is not None and use_timm_backbone:
raise ValueError("You can't specify both `backbone_config` and `use_timm_backbone`." )
if not use_timm_backbone:
if backbone_config is None:
logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." )
_SCREAMING_SNAKE_CASE : Union[str, Any] = CONFIG_MAPPING["resnet"](out_features=["stage4"] )
elif isinstance(__lowerCamelCase , __lowerCamelCase ):
_SCREAMING_SNAKE_CASE : Dict = backbone_config.get("model_type" )
_SCREAMING_SNAKE_CASE : str = CONFIG_MAPPING[backbone_model_type]
_SCREAMING_SNAKE_CASE : Tuple = config_class.from_dict(__lowerCamelCase )
# set timm attributes to None
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = None, None, None
_SCREAMING_SNAKE_CASE : List[str] = use_timm_backbone
_SCREAMING_SNAKE_CASE : Tuple = backbone_config
_SCREAMING_SNAKE_CASE : int = num_channels
_SCREAMING_SNAKE_CASE : int = num_queries
_SCREAMING_SNAKE_CASE : Optional[int] = d_model
_SCREAMING_SNAKE_CASE : Optional[int] = encoder_ffn_dim
_SCREAMING_SNAKE_CASE : int = encoder_layers
_SCREAMING_SNAKE_CASE : Optional[Any] = encoder_attention_heads
_SCREAMING_SNAKE_CASE : Optional[int] = decoder_ffn_dim
_SCREAMING_SNAKE_CASE : Union[str, Any] = decoder_layers
_SCREAMING_SNAKE_CASE : str = decoder_attention_heads
_SCREAMING_SNAKE_CASE : Any = dropout
_SCREAMING_SNAKE_CASE : str = attention_dropout
_SCREAMING_SNAKE_CASE : str = activation_dropout
_SCREAMING_SNAKE_CASE : Tuple = activation_function
_SCREAMING_SNAKE_CASE : List[Any] = init_std
_SCREAMING_SNAKE_CASE : Dict = init_xavier_std
_SCREAMING_SNAKE_CASE : Dict = encoder_layerdrop
_SCREAMING_SNAKE_CASE : Optional[Any] = decoder_layerdrop
_SCREAMING_SNAKE_CASE : Optional[Any] = encoder_layers
_SCREAMING_SNAKE_CASE : int = auxiliary_loss
_SCREAMING_SNAKE_CASE : Optional[Any] = position_embedding_type
_SCREAMING_SNAKE_CASE : List[Any] = backbone
_SCREAMING_SNAKE_CASE : str = use_pretrained_backbone
_SCREAMING_SNAKE_CASE : Optional[Any] = dilation
# Hungarian matcher
_SCREAMING_SNAKE_CASE : Optional[Any] = class_cost
_SCREAMING_SNAKE_CASE : str = bbox_cost
_SCREAMING_SNAKE_CASE : int = giou_cost
# Loss coefficients
_SCREAMING_SNAKE_CASE : List[str] = mask_loss_coefficient
_SCREAMING_SNAKE_CASE : Tuple = dice_loss_coefficient
_SCREAMING_SNAKE_CASE : Union[str, Any] = bbox_loss_coefficient
_SCREAMING_SNAKE_CASE : Tuple = giou_loss_coefficient
_SCREAMING_SNAKE_CASE : Optional[Any] = eos_coefficient
super().__init__(is_encoder_decoder=__lowerCamelCase , **__lowerCamelCase )
@property
def UpperCamelCase_ ( self ) -> int:
return self.encoder_attention_heads
@property
def UpperCamelCase_ ( self ) -> int:
return self.d_model
class lowerCAmelCase__( __lowercase ):
'''simple docstring'''
__snake_case = version.parse('1.11' )
@property
def UpperCamelCase_ ( self ) -> Mapping[str, Mapping[int, str]]:
return OrderedDict(
[
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
("pixel_mask", {0: "batch"}),
] )
@property
def UpperCamelCase_ ( self ) -> float:
return 1E-5
@property
def UpperCamelCase_ ( self ) -> int:
return 1_2
| 381 |
from PIL import Image
def lowerCamelCase__ (__lowerCamelCase ):
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = image.size
_SCREAMING_SNAKE_CASE : Tuple = 0
_SCREAMING_SNAKE_CASE : Dict = image.load()
for i in range(__lowerCamelCase ):
for j in range(__lowerCamelCase ):
_SCREAMING_SNAKE_CASE : List[Any] = pixels[j, i]
mean += pixel
mean //= width * height
for j in range(__lowerCamelCase ):
for i in range(__lowerCamelCase ):
_SCREAMING_SNAKE_CASE : int = 255 if pixels[i, j] > mean else 0
return image
if __name__ == "__main__":
UpperCamelCase__ =mean_threshold(Image.open('path_to_image').convert('L'))
image.save('output_image_path')
| 381 | 1 |
'''simple docstring'''
import warnings
from typing import List
import numpy as np
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import is_flax_available, is_tf_available, is_torch_available
class lowercase_ (lowerCamelCase__ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Union[str, Any] = ['image_processor', 'tokenizer']
SCREAMING_SNAKE_CASE : str = 'OwlViTImageProcessor'
SCREAMING_SNAKE_CASE : List[str] = ('CLIPTokenizer', 'CLIPTokenizerFast')
def __init__( self : Any ,lowercase__ : str=None ,lowercase__ : Any=None ,**lowercase__ : List[Any] ):
__lowercase = None
if "feature_extractor" in kwargs:
warnings.warn(
'''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
''' instead.''' ,lowercase__ ,)
__lowercase = kwargs.pop('''feature_extractor''' )
__lowercase = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError('''You need to specify an `image_processor`.''' )
if tokenizer is None:
raise ValueError('''You need to specify a `tokenizer`.''' )
super().__init__(lowercase__ ,lowercase__ )
def __call__( self : str ,lowercase__ : Tuple=None ,lowercase__ : List[Any]=None ,lowercase__ : Dict=None ,lowercase__ : List[str]="max_length" ,lowercase__ : List[Any]="np" ,**lowercase__ : Dict ):
if text is None and query_images is None and images is None:
raise ValueError(
'''You have to specify at least one text or query image or image. All three cannot be none.''' )
if text is not None:
if isinstance(lowercase__ ,lowercase__ ) or (isinstance(lowercase__ ,lowercase__ ) and not isinstance(text[0] ,lowercase__ )):
__lowercase = [self.tokenizer(lowercase__ ,padding=lowercase__ ,return_tensors=lowercase__ ,**lowercase__ )]
elif isinstance(lowercase__ ,lowercase__ ) and isinstance(text[0] ,lowercase__ ):
__lowercase = []
# Maximum number of queries across batch
__lowercase = max([len(lowercase__ ) for t in text] )
# Pad all batch samples to max number of text queries
for t in text:
if len(lowercase__ ) != max_num_queries:
__lowercase = t + [''' '''] * (max_num_queries - len(lowercase__ ))
__lowercase = self.tokenizer(lowercase__ ,padding=lowercase__ ,return_tensors=lowercase__ ,**lowercase__ )
encodings.append(lowercase__ )
else:
raise TypeError('''Input text should be a string, a list of strings or a nested list of strings''' )
if return_tensors == "np":
__lowercase = np.concatenate([encoding['''input_ids'''] for encoding in encodings] ,axis=0 )
__lowercase = np.concatenate([encoding['''attention_mask'''] for encoding in encodings] ,axis=0 )
elif return_tensors == "jax" and is_flax_available():
import jax.numpy as jnp
__lowercase = jnp.concatenate([encoding['''input_ids'''] for encoding in encodings] ,axis=0 )
__lowercase = jnp.concatenate([encoding['''attention_mask'''] for encoding in encodings] ,axis=0 )
elif return_tensors == "pt" and is_torch_available():
import torch
__lowercase = torch.cat([encoding['''input_ids'''] for encoding in encodings] ,dim=0 )
__lowercase = torch.cat([encoding['''attention_mask'''] for encoding in encodings] ,dim=0 )
elif return_tensors == "tf" and is_tf_available():
import tensorflow as tf
__lowercase = tf.stack([encoding['''input_ids'''] for encoding in encodings] ,axis=0 )
__lowercase = tf.stack([encoding['''attention_mask'''] for encoding in encodings] ,axis=0 )
else:
raise ValueError('''Target return tensor type could not be returned''' )
__lowercase = BatchEncoding()
__lowercase = input_ids
__lowercase = attention_mask
if query_images is not None:
__lowercase = BatchEncoding()
__lowercase = self.image_processor(
lowercase__ ,return_tensors=lowercase__ ,**lowercase__ ).pixel_values
__lowercase = query_pixel_values
if images is not None:
__lowercase = self.image_processor(lowercase__ ,return_tensors=lowercase__ ,**lowercase__ )
if text is not None and images is not None:
__lowercase = image_features.pixel_values
return encoding
elif query_images is not None and images is not None:
__lowercase = image_features.pixel_values
return encoding
elif text is not None or query_images is not None:
return encoding
else:
return BatchEncoding(data=dict(**lowercase__ ) ,tensor_type=lowercase__ )
def SCREAMING_SNAKE_CASE ( self : int ,*lowercase__ : Optional[int] ,**lowercase__ : Tuple ):
return self.image_processor.post_process(*lowercase__ ,**lowercase__ )
def SCREAMING_SNAKE_CASE ( self : Dict ,*lowercase__ : List[Any] ,**lowercase__ : int ):
return self.image_processor.post_process_object_detection(*lowercase__ ,**lowercase__ )
def SCREAMING_SNAKE_CASE ( self : int ,*lowercase__ : List[str] ,**lowercase__ : Union[str, Any] ):
return self.image_processor.post_process_image_guided_detection(*lowercase__ ,**lowercase__ )
def SCREAMING_SNAKE_CASE ( self : int ,*lowercase__ : str ,**lowercase__ : Union[str, Any] ):
return self.tokenizer.batch_decode(*lowercase__ ,**lowercase__ )
def SCREAMING_SNAKE_CASE ( self : str ,*lowercase__ : List[Any] ,**lowercase__ : Dict ):
return self.tokenizer.decode(*lowercase__ ,**lowercase__ )
@property
def SCREAMING_SNAKE_CASE ( self : List[Any] ):
warnings.warn(
'''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' ,lowercase__ ,)
return self.image_processor_class
@property
def SCREAMING_SNAKE_CASE ( self : Dict ):
warnings.warn(
'''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' ,lowercase__ ,)
return self.image_processor
| 41 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_torch_available,
is_vision_available,
)
_UpperCamelCase = {"""configuration_vit""": ["""VIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ViTConfig""", """ViTOnnxConfig"""]}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCamelCase = ["""ViTFeatureExtractor"""]
_UpperCamelCase = ["""ViTImageProcessor"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCamelCase = [
"""VIT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""ViTForImageClassification""",
"""ViTForMaskedImageModeling""",
"""ViTModel""",
"""ViTPreTrainedModel""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCamelCase = [
"""TFViTForImageClassification""",
"""TFViTModel""",
"""TFViTPreTrainedModel""",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCamelCase = [
"""FlaxViTForImageClassification""",
"""FlaxViTModel""",
"""FlaxViTPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_vit import ViTFeatureExtractor
from .image_processing_vit import ViTImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_vit import (
VIT_PRETRAINED_MODEL_ARCHIVE_LIST,
ViTForImageClassification,
ViTForMaskedImageModeling,
ViTModel,
ViTPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel
else:
import sys
_UpperCamelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 111 | 0 |
import argparse
from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta
from transformers.utils import logging
logging.set_verbosity_info()
def lowerCAmelCase_ ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Dict ):
# Initialise PyTorch model
UpperCamelCase_ : List[Any] = TaConfig.from_json_file(_SCREAMING_SNAKE_CASE )
print(f'''Building PyTorch model from configuration: {config}''' )
UpperCamelCase_ : Tuple = TaForConditionalGeneration(_SCREAMING_SNAKE_CASE )
# Load weights from tf checkpoint
load_tf_weights_in_ta(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# Save pytorch-model
print(f'''Save PyTorch model to {pytorch_dump_path}''' )
model.save_pretrained(_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE : 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."
)
SCREAMING_SNAKE_CASE : Optional[Any] = parser.parse_args()
convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
| 702 |
import baseaa
def lowerCAmelCase_ ( _SCREAMING_SNAKE_CASE : str ):
return baseaa.baaencode(string.encode("""utf-8""" ) )
def lowerCAmelCase_ ( _SCREAMING_SNAKE_CASE : bytes ):
return baseaa.baadecode(_SCREAMING_SNAKE_CASE ).decode("""utf-8""" )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE : Any = "Hello World!"
SCREAMING_SNAKE_CASE : int = baseaa_encode(test)
print(encoded)
SCREAMING_SNAKE_CASE : Union[str, Any] = baseaa_decode(encoded)
print(decoded)
| 138 | 0 |
'''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 |
"""simple docstring"""
from __future__ import annotations
def __UpperCamelCase ( snake_case__ , snake_case__ = None , snake_case__ = None ):
if start is None:
A_ : Dict = 0
if end is None:
A_ : Dict = len(snake_case__ ) - 1
if start >= end:
return
A_ : List[Any] = (start + end) // 2
slowsort(snake_case__ , snake_case__ , snake_case__ )
slowsort(snake_case__ , mid + 1 , snake_case__ )
if sequence[end] < sequence[mid]:
A_ , A_ : Dict = sequence[mid], sequence[end]
slowsort(snake_case__ , snake_case__ , end - 1 )
if __name__ == "__main__":
from doctest import testmod
testmod()
| 180 | 0 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_speech_available,
is_torch_available,
)
a : int = {
"""configuration_trocr""": ["""TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TrOCRConfig"""],
"""processing_trocr""": ["""TrOCRProcessor"""],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : int = [
"""TROCR_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""TrOCRForCausalLM""",
"""TrOCRPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig
from .processing_trocr import TrOCRProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel
else:
import sys
a : Any = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 719 |
"""simple docstring"""
from typing import List, Optional, Union
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ):
"""simple docstring"""
__lowerCamelCase = ["image_processor", "tokenizer"]
__lowerCamelCase = "BridgeTowerImageProcessor"
__lowerCamelCase = ("RobertaTokenizer", "RobertaTokenizerFast")
def __init__( self , snake_case__ , snake_case__ ):
'''simple docstring'''
super().__init__(snake_case__ , snake_case__ )
def __call__( self , snake_case__ , snake_case__ = None , snake_case__ = True , snake_case__ = False , snake_case__ = None , snake_case__ = None , snake_case__ = 0 , snake_case__ = None , snake_case__ = None , snake_case__ = None , snake_case__ = False , snake_case__ = False , snake_case__ = False , snake_case__ = False , snake_case__ = True , snake_case__ = None , **snake_case__ , ):
'''simple docstring'''
lowercase__ : Optional[int]= self.tokenizer(
text=snake_case__ , add_special_tokens=snake_case__ , padding=snake_case__ , truncation=snake_case__ , max_length=snake_case__ , stride=snake_case__ , pad_to_multiple_of=snake_case__ , return_token_type_ids=snake_case__ , return_attention_mask=snake_case__ , return_overflowing_tokens=snake_case__ , return_special_tokens_mask=snake_case__ , return_offsets_mapping=snake_case__ , return_length=snake_case__ , verbose=snake_case__ , return_tensors=snake_case__ , **snake_case__ , )
# add pixel_values + pixel_mask
lowercase__ : Optional[int]= self.image_processor(
snake_case__ , return_tensors=snake_case__ , do_normalize=snake_case__ , do_center_crop=snake_case__ , **snake_case__ )
encoding.update(snake_case__ )
return encoding
def UpperCAmelCase_ ( self , *snake_case__ , **snake_case__ ):
'''simple docstring'''
return self.tokenizer.batch_decode(*snake_case__ , **snake_case__ )
def UpperCAmelCase_ ( self , *snake_case__ , **snake_case__ ):
'''simple docstring'''
return self.tokenizer.decode(*snake_case__ , **snake_case__ )
@property
def UpperCAmelCase_ ( self ):
'''simple docstring'''
lowercase__ : Optional[Any]= self.tokenizer.model_input_names
lowercase__ : List[Any]= self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
| 85 | 0 |
class __lowercase :
def __init__( self ) ->int:
'''simple docstring'''
__lowerCAmelCase : List[str] = 0
__lowerCAmelCase : Optional[int] = 0
__lowerCAmelCase : Union[str, Any] = {}
def UpperCamelCase__ ( self , A_ ) ->Tuple:
'''simple docstring'''
if vertex not in self.adjacency:
__lowerCAmelCase : Any = {}
self.num_vertices += 1
def UpperCamelCase__ ( self , A_ , A_ , A_ ) ->Any:
'''simple docstring'''
self.add_vertex(A_ )
self.add_vertex(A_ )
if head == tail:
return
__lowerCAmelCase : Optional[Any] = weight
__lowerCAmelCase : Dict = weight
def UpperCamelCase__ ( self ) ->List[Any]:
'''simple docstring'''
__lowerCAmelCase : List[Any] = self.get_edges()
for edge in edges:
__lowerCAmelCase, __lowerCAmelCase, __lowerCAmelCase : int = edge
edges.remove((tail, head, weight) )
for i in range(len(A_ ) ):
__lowerCAmelCase : List[Any] = list(edges[i] )
edges.sort(key=lambda A_ : e[2] )
for i in range(len(A_ ) - 1 ):
if edges[i][2] >= edges[i + 1][2]:
__lowerCAmelCase : Tuple = edges[i][2] + 1
for edge in edges:
__lowerCAmelCase, __lowerCAmelCase, __lowerCAmelCase : Tuple = edge
__lowerCAmelCase : Tuple = weight
__lowerCAmelCase : Dict = weight
def __str__( self ) ->int:
'''simple docstring'''
__lowerCAmelCase : List[Any] = ''''''
for tail in self.adjacency:
for head in self.adjacency[tail]:
__lowerCAmelCase : List[Any] = self.adjacency[head][tail]
string += f"""{head} -> {tail} == {weight}\n"""
return string.rstrip('''\n''' )
def UpperCamelCase__ ( self ) ->Union[str, Any]:
'''simple docstring'''
__lowerCAmelCase : Dict = []
for tail in self.adjacency:
for head in self.adjacency[tail]:
output.append((tail, head, self.adjacency[head][tail]) )
return output
def UpperCamelCase__ ( self ) ->Optional[int]:
'''simple docstring'''
return self.adjacency.keys()
@staticmethod
def UpperCamelCase__ ( A_=None , A_=None ) ->Any:
'''simple docstring'''
__lowerCAmelCase : str = Graph()
if vertices is None:
__lowerCAmelCase : Optional[Any] = []
if edges is None:
__lowerCAmelCase : Union[str, Any] = []
for vertex in vertices:
g.add_vertex(A_ )
for edge in edges:
g.add_edge(*A_ )
return g
class __lowercase :
def __init__( self ) ->List[Any]:
'''simple docstring'''
__lowerCAmelCase : List[str] = {}
__lowerCAmelCase : Optional[int] = {}
def __len__( self ) ->int:
'''simple docstring'''
return len(self.parent )
def UpperCamelCase__ ( self , A_ ) ->Optional[Any]:
'''simple docstring'''
if item in self.parent:
return self.find(A_ )
__lowerCAmelCase : List[Any] = item
__lowerCAmelCase : Union[str, Any] = 0
return item
def UpperCamelCase__ ( self , A_ ) ->str:
'''simple docstring'''
if item not in self.parent:
return self.make_set(A_ )
if item != self.parent[item]:
__lowerCAmelCase : Tuple = self.find(self.parent[item] )
return self.parent[item]
def UpperCamelCase__ ( self , A_ , A_ ) ->Dict:
'''simple docstring'''
__lowerCAmelCase : Any = self.find(A_ )
__lowerCAmelCase : Dict = self.find(A_ )
if roota == roota:
return roota
if self.rank[roota] > self.rank[roota]:
__lowerCAmelCase : Optional[int] = roota
return roota
if self.rank[roota] < self.rank[roota]:
__lowerCAmelCase : Dict = roota
return roota
if self.rank[roota] == self.rank[roota]:
self.rank[roota] += 1
__lowerCAmelCase : int = roota
return roota
return None
@staticmethod
def UpperCamelCase__ ( A_ ) ->Any:
'''simple docstring'''
__lowerCAmelCase : str = graph.num_vertices
__lowerCAmelCase : List[Any] = Graph.UnionFind()
__lowerCAmelCase : Any = []
while num_components > 1:
__lowerCAmelCase : Optional[int] = {}
for vertex in graph.get_vertices():
__lowerCAmelCase : Any = -1
__lowerCAmelCase : Any = graph.get_edges()
for edge in edges:
__lowerCAmelCase, __lowerCAmelCase, __lowerCAmelCase : Union[str, Any] = edge
edges.remove((tail, head, weight) )
for edge in edges:
__lowerCAmelCase, __lowerCAmelCase, __lowerCAmelCase : Optional[Any] = edge
__lowerCAmelCase : Union[str, Any] = union_find.find(A_ )
__lowerCAmelCase : List[Any] = union_find.find(A_ )
if seta != seta:
if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight:
__lowerCAmelCase : List[Any] = [head, tail, weight]
if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight:
__lowerCAmelCase : Dict = [head, tail, weight]
for vertex in cheap_edge:
if cheap_edge[vertex] != -1:
__lowerCAmelCase, __lowerCAmelCase, __lowerCAmelCase : Any = cheap_edge[vertex]
if union_find.find(A_ ) != union_find.find(A_ ):
union_find.union(A_ , A_ )
mst_edges.append(cheap_edge[vertex] )
__lowerCAmelCase : Union[str, Any] = num_components - 1
__lowerCAmelCase : Tuple = Graph.build(edges=A_ )
return mst
| 492 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
_UpperCamelCase = {"configuration_xlnet": ["XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLNetConfig"]}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCamelCase = ["XLNetTokenizer"]
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCamelCase = ["XLNetTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCamelCase = [
"XLNET_PRETRAINED_MODEL_ARCHIVE_LIST",
"XLNetForMultipleChoice",
"XLNetForQuestionAnswering",
"XLNetForQuestionAnsweringSimple",
"XLNetForSequenceClassification",
"XLNetForTokenClassification",
"XLNetLMHeadModel",
"XLNetModel",
"XLNetPreTrainedModel",
"load_tf_weights_in_xlnet",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCamelCase = [
"TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFXLNetForMultipleChoice",
"TFXLNetForQuestionAnsweringSimple",
"TFXLNetForSequenceClassification",
"TFXLNetForTokenClassification",
"TFXLNetLMHeadModel",
"TFXLNetMainLayer",
"TFXLNetModel",
"TFXLNetPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_xlnet import XLNetTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_xlnet_fast import XLNetTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_xlnet import (
XLNET_PRETRAINED_MODEL_ARCHIVE_LIST,
XLNetForMultipleChoice,
XLNetForQuestionAnswering,
XLNetForQuestionAnsweringSimple,
XLNetForSequenceClassification,
XLNetForTokenClassification,
XLNetLMHeadModel,
XLNetModel,
XLNetPreTrainedModel,
load_tf_weights_in_xlnet,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_xlnet import (
TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST,
TFXLNetForMultipleChoice,
TFXLNetForQuestionAnsweringSimple,
TFXLNetForSequenceClassification,
TFXLNetForTokenClassification,
TFXLNetLMHeadModel,
TFXLNetMainLayer,
TFXLNetModel,
TFXLNetPreTrainedModel,
)
else:
import sys
_UpperCamelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 492 | 1 |
"""simple docstring"""
import argparse
import gdown
import numpy as np
import torch
from huggingface_hub import hf_hub_download
from transformers import (
CLIPTokenizer,
CLIPTokenizerFast,
VideoMAEImageProcessor,
XCLIPConfig,
XCLIPModel,
XCLIPProcessor,
XCLIPTextConfig,
XCLIPVisionConfig,
)
def __snake_case ( UpperCamelCase , UpperCamelCase ) -> Tuple:
"""simple docstring"""
a__ = XCLIPTextConfig()
# derive patch size from model name
a__ = model_name.find('''patch''' )
a__ = int(model_name[start_idx + len('''patch''' ) : start_idx + len('''patch''' ) + 2] )
a__ = XCLIPVisionConfig(patch_size=UpperCamelCase , num_frames=UpperCamelCase )
if "large" in model_name:
a__ = 768
a__ = 3_072
a__ = 12
a__ = 1_024
a__ = 4_096
a__ = 16
a__ = 24
a__ = 768
a__ = 3_072
if model_name == "xclip-large-patch14-16-frames":
a__ = 336
a__ = XCLIPConfig.from_text_vision_configs(UpperCamelCase , UpperCamelCase )
if "large" in model_name:
a__ = 768
return config
def __snake_case ( UpperCamelCase ) -> Optional[int]:
"""simple docstring"""
if name == "token_embedding.weight":
a__ = name.replace('''token_embedding.weight''' , '''text_model.embeddings.token_embedding.weight''' )
if name == "positional_embedding":
a__ = name.replace('''positional_embedding''' , '''text_model.embeddings.position_embedding.weight''' )
if "ln_1" in name:
a__ = name.replace('''ln_1''' , '''layer_norm1''' )
if "ln_2" in name:
a__ = name.replace('''ln_2''' , '''layer_norm2''' )
if "c_fc" in name:
a__ = name.replace('''c_fc''' , '''fc1''' )
if "c_proj" in name:
a__ = name.replace('''c_proj''' , '''fc2''' )
if name.startswith('''transformer.resblocks''' ):
a__ = name.replace('''transformer.resblocks''' , '''text_model.encoder.layers''' )
if "attn.out_proj" in name and "message" not in name:
a__ = name.replace('''attn.out_proj''' , '''self_attn.out_proj''' )
if "ln_final" in name:
a__ = name.replace('''ln_final''' , '''text_model.final_layer_norm''' )
# visual encoder
if name == "visual.class_embedding":
a__ = name.replace('''visual.class_embedding''' , '''vision_model.embeddings.class_embedding''' )
if name == "visual.positional_embedding":
a__ = name.replace('''visual.positional_embedding''' , '''vision_model.embeddings.position_embedding.weight''' )
if name.startswith('''visual.transformer.resblocks''' ):
a__ = name.replace('''visual.transformer.resblocks''' , '''vision_model.encoder.layers''' )
if "visual.conv1" in name:
a__ = name.replace('''visual.conv1''' , '''vision_model.embeddings.patch_embedding''' )
if "visual.ln_pre" in name:
a__ = name.replace('''visual.ln_pre''' , '''vision_model.pre_layernorm''' )
if "visual.ln_post" in name:
a__ = name.replace('''visual.ln_post''' , '''vision_model.post_layernorm''' )
if "visual.proj" in name:
a__ = name.replace('''visual.proj''' , '''visual_projection.weight''' )
if "text_projection" in name:
a__ = name.replace('''text_projection''' , '''text_projection.weight''' )
# things on top
if "prompts_visual_proj" in name:
a__ = name.replace('''prompts_visual_proj''' , '''prompts_visual_projection''' )
if "prompts_visual_ln" in name:
a__ = name.replace('''prompts_visual_ln''' , '''prompts_visual_layernorm''' )
# mit
if name == "mit.positional_embedding":
a__ = name.replace('''positional''' , '''position''' )
if name.startswith('''mit.resblocks''' ):
a__ = name.replace('''mit.resblocks''' , '''mit.encoder.layers''' )
# prompts generator
if name.startswith('''prompts_generator.norm''' ):
a__ = name.replace('''prompts_generator.norm''' , '''prompts_generator.layernorm''' )
return name
def __snake_case ( UpperCamelCase , UpperCamelCase ) -> List[Any]:
"""simple docstring"""
for key in orig_state_dict.copy().keys():
a__ = orig_state_dict.pop(UpperCamelCase )
if "attn.in_proj" in key:
a__ = key.split('''.''' )
if key.startswith('''visual''' ):
a__ = key_split[3]
a__ = config.vision_config.hidden_size
if "message_attn" in key:
if "weight" in key:
a__ = val[
:dim, :
]
a__ = val[
dim : dim * 2, :
]
a__ = val[
-dim:, :
]
else:
a__ = val[
:dim
]
a__ = val[
dim : dim * 2
]
a__ = val[
-dim:
]
else:
if "weight" in key:
a__ = val[
:dim, :
]
a__ = val[
dim : dim * 2, :
]
a__ = val[
-dim:, :
]
else:
a__ = val[:dim]
a__ = val[
dim : dim * 2
]
a__ = val[-dim:]
elif key.startswith('''mit''' ):
a__ = key_split[2]
a__ = config.vision_config.mit_hidden_size
if "weight" in key:
a__ = val[:dim, :]
a__ = val[dim : dim * 2, :]
a__ = val[-dim:, :]
else:
a__ = val[:dim]
a__ = val[dim : dim * 2]
a__ = val[-dim:]
else:
a__ = key_split[2]
a__ = config.text_config.hidden_size
if "weight" in key:
a__ = val[:dim, :]
a__ = val[
dim : dim * 2, :
]
a__ = val[-dim:, :]
else:
a__ = val[:dim]
a__ = val[
dim : dim * 2
]
a__ = val[-dim:]
else:
a__ = rename_key(UpperCamelCase )
if new_key_name in ["visual_projection.weight", "text_projection.weight"]:
a__ = val.T
a__ = val
return orig_state_dict
def __snake_case ( UpperCamelCase ) -> str:
"""simple docstring"""
if num_frames == 8:
a__ = '''eating_spaghetti_8_frames.npy'''
elif num_frames == 16:
a__ = '''eating_spaghetti.npy'''
elif num_frames == 32:
a__ = '''eating_spaghetti_32_frames.npy'''
a__ = hf_hub_download(
repo_id='''hf-internal-testing/spaghetti-video''' , filename=UpperCamelCase , repo_type='''dataset''' , )
a__ = np.load(UpperCamelCase )
return list(UpperCamelCase )
def __snake_case ( UpperCamelCase , UpperCamelCase=None , UpperCamelCase=False ) -> Union[str, Any]:
"""simple docstring"""
a__ = {
# fully supervised kinetics-400 checkpoints
'''xclip-base-patch32''': '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_8.pth''',
'''xclip-base-patch32-16-frames''': (
'''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_16.pth'''
),
'''xclip-base-patch16''': '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_8.pth''',
'''xclip-base-patch16-16-frames''': (
'''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_16.pth'''
),
'''xclip-large-patch14''': '''https://drive.google.com/u/0/uc?id=1NUOImq0o5DlQTST17iIP3vG7DgmHQuCx&export=download&confirm=t&uuid=b26caedc-88e2-473e-830a-9d158b653cdb''',
'''xclip-large-patch14-16-frames''': '''https://drive.google.com/u/0/uc?id=1FOYgnJc097OJ4lGwtRCCydQyVPJEOH7d&export=download&confirm=t&uuid=538fa810-e671-4050-b385-9a623f89804f''',
# fully supervised kinetics-600 checkpoints
'''xclip-base-patch16-kinetics-600''': (
'''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_8.pth'''
),
'''xclip-base-patch16-kinetics-600-16-frames''': (
'''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_16.pth'''
),
'''xclip-large-patch14-kinetics-600''': '''https://drive.google.com/u/0/uc?id=1FV8C1INuM91sLAN4ImjzePLIlpMSihwV&export=download&confirm=t&uuid=141d4977-4a65-44ae-864f-4b0c19f838be''',
# few shot
'''xclip-base-patch16-hmdb-2-shot''': (
'''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_2.pth'''
),
'''xclip-base-patch16-hmdb-4-shot''': (
'''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_4.pth'''
),
'''xclip-base-patch16-hmdb-8-shot''': (
'''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_8.pth'''
),
'''xclip-base-patch16-hmdb-16-shot''': (
'''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_16.pth'''
),
'''xclip-base-patch16-ucf-2-shot''': (
'''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_2.pth'''
),
'''xclip-base-patch16-ucf-4-shot''': (
'''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_4.pth'''
),
'''xclip-base-patch16-ucf-8-shot''': (
'''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_8.pth'''
),
'''xclip-base-patch16-ucf-16-shot''': (
'''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_16.pth'''
),
# zero shot
'''xclip-base-patch16-zero-shot''': '''https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/zero.pth''',
}
a__ = model_to_url[model_name]
a__ = 8
if "16-frames" in model_name:
a__ = 16
elif "shot" in model_name:
a__ = 32
a__ = get_xclip_config(UpperCamelCase , UpperCamelCase )
a__ = XCLIPModel(UpperCamelCase )
model.eval()
if "drive" in checkpoint_url:
a__ = '''pytorch_model.bin'''
gdown.cached_download(UpperCamelCase , UpperCamelCase , quiet=UpperCamelCase )
a__ = torch.load(UpperCamelCase , map_location='''cpu''' )['''model''']
else:
a__ = torch.hub.load_state_dict_from_url(UpperCamelCase )['''model''']
a__ = convert_state_dict(UpperCamelCase , UpperCamelCase )
a__ = XCLIPModel(UpperCamelCase )
a__ , a__ = model.load_state_dict(UpperCamelCase , strict=UpperCamelCase )
assert missing_keys == ["text_model.embeddings.position_ids", "vision_model.embeddings.position_ids"]
model.eval()
a__ = 336 if model_name == '''xclip-large-patch14-16-frames''' else 224
a__ = VideoMAEImageProcessor(size=UpperCamelCase )
a__ = CLIPTokenizer.from_pretrained('''openai/clip-vit-base-patch32''' )
a__ = CLIPTokenizerFast.from_pretrained('''openai/clip-vit-base-patch32''' )
a__ = XCLIPProcessor(image_processor=UpperCamelCase , tokenizer=UpperCamelCase )
a__ = prepare_video(UpperCamelCase )
a__ = processor(
text=['''playing sports''', '''eating spaghetti''', '''go shopping'''] , videos=UpperCamelCase , return_tensors='''pt''' , padding=UpperCamelCase )
print('''Shape of pixel values:''' , inputs.pixel_values.shape )
with torch.no_grad():
a__ = model(**UpperCamelCase )
# Verify outputs
a__ = outputs.logits_per_video
a__ = logits_per_video.softmax(dim=1 )
print('''Probs:''' , UpperCamelCase )
# kinetics-400
if model_name == "xclip-base-patch32":
a__ = torch.tensor([[0.00_19, 0.99_51, 0.00_30]] )
elif model_name == "xclip-base-patch32-16-frames":
a__ = torch.tensor([[7.0_999E-04, 9.9_883E-01, 4.5_580E-04]] )
elif model_name == "xclip-base-patch16":
a__ = torch.tensor([[0.00_83, 0.96_81, 0.02_36]] )
elif model_name == "xclip-base-patch16-16-frames":
a__ = torch.tensor([[7.6_937E-04, 9.9_728E-01, 1.9_473E-03]] )
elif model_name == "xclip-large-patch14":
a__ = torch.tensor([[0.00_62, 0.98_64, 0.00_75]] )
elif model_name == "xclip-large-patch14-16-frames":
a__ = torch.tensor([[3.3_877E-04, 9.9_937E-01, 2.8_888E-04]] )
# kinetics-600
elif model_name == "xclip-base-patch16-kinetics-600":
a__ = torch.tensor([[0.05_55, 0.89_14, 0.05_31]] )
elif model_name == "xclip-base-patch16-kinetics-600-16-frames":
a__ = torch.tensor([[3.8_554E-04, 9.9_929E-01, 3.2_754E-04]] )
elif model_name == "xclip-large-patch14-kinetics-600":
a__ = torch.tensor([[0.00_36, 0.99_20, 0.00_45]] )
# few shot
elif model_name == "xclip-base-patch16-hmdb-2-shot":
a__ = torch.tensor([[7.1_890E-06, 9.9_994E-01, 5.6_559E-05]] )
elif model_name == "xclip-base-patch16-hmdb-4-shot":
a__ = torch.tensor([[1.0_320E-05, 9.9_993E-01, 6.2_435E-05]] )
elif model_name == "xclip-base-patch16-hmdb-8-shot":
a__ = torch.tensor([[4.1_377E-06, 9.9_990E-01, 9.8_386E-05]] )
elif model_name == "xclip-base-patch16-hmdb-16-shot":
a__ = torch.tensor([[4.1_347E-05, 9.9_962E-01, 3.3_411E-04]] )
elif model_name == "xclip-base-patch16-ucf-2-shot":
a__ = torch.tensor([[8.5_857E-05, 9.9_928E-01, 6.3_291E-04]] )
elif model_name == "xclip-base-patch16-ucf-4-shot":
a__ = torch.tensor([[8.5_857E-05, 9.9_928E-01, 6.3_291E-04]] )
elif model_name == "xclip-base-patch16-ucf-8-shot":
a__ = torch.tensor([[0.00_27, 0.99_04, 0.00_70]] )
elif model_name == "xclip-base-patch16-ucf-16-shot":
a__ = torch.tensor([[9.8_219E-04, 9.9_593E-01, 3.0_863E-03]] )
# zero shot
elif model_name == "xclip-base-patch16-zero-shot":
a__ = torch.tensor([[3.5_082E-04, 9.9_785E-01, 1.7_966E-03]] )
else:
raise ValueError(f"Model name {model_name} not supported" )
assert torch.allclose(UpperCamelCase , UpperCamelCase , atol=1E-3 )
print('''Looks ok!''' )
if pytorch_dump_folder_path is not None:
print(f"Saving model {model_name} to {pytorch_dump_folder_path}" )
model.save_pretrained(UpperCamelCase )
if push_to_hub:
print('''Pushing model, processor and slow tokenizer files to the hub...''' )
model.push_to_hub(UpperCamelCase , organization='''nielsr''' )
processor.push_to_hub(UpperCamelCase , organization='''nielsr''' )
slow_tokenizer.push_to_hub(UpperCamelCase , organization='''nielsr''' )
if __name__ == "__main__":
__lowerCAmelCase : Optional[Any] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--model_name''',
default='''xclip-base-patch32''',
type=str,
help='''Name of the model.''',
)
parser.add_argument(
'''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.'''
)
parser.add_argument(
'''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.'''
)
__lowerCAmelCase : str = parser.parse_args()
convert_xclip_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 158 |
"""simple docstring"""
from __future__ import annotations
__lowerCAmelCase : Union[str, Any] = list[tuple[int, int]]
__lowerCAmelCase : Optional[int] = [
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
]
__lowerCAmelCase : Dict = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right
class SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__( self :str , __magic_name__ :int , __magic_name__ :int , __magic_name__ :int , __magic_name__ :int , __magic_name__ :float , __magic_name__ :Node | None , ) -> Tuple:
'''simple docstring'''
a__ = pos_x
a__ = pos_y
a__ = (pos_y, pos_x)
a__ = goal_x
a__ = goal_y
a__ = g_cost
a__ = parent
a__ = self.calculate_heuristic()
def _UpperCamelCase ( self :int ) -> float:
'''simple docstring'''
a__ = abs(self.pos_x - self.goal_x )
a__ = abs(self.pos_y - self.goal_y )
return dx + dy
def __lt__( self :List[str] , __magic_name__ :List[Any] ) -> bool:
'''simple docstring'''
return self.f_cost < other.f_cost
class SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__( self :Dict , __magic_name__ :tuple[int, int] , __magic_name__ :tuple[int, int] ) -> Tuple:
'''simple docstring'''
a__ = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , __magic_name__ )
a__ = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99999 , __magic_name__ )
a__ = [self.start]
a__ = []
a__ = False
def _UpperCamelCase ( self :Union[str, Any] ) -> Path | None:
'''simple docstring'''
while self.open_nodes:
# Open Nodes are sorted using __lt__
self.open_nodes.sort()
a__ = self.open_nodes.pop(0 )
if current_node.pos == self.target.pos:
a__ = True
return self.retrace_path(__magic_name__ )
self.closed_nodes.append(__magic_name__ )
a__ = self.get_successors(__magic_name__ )
for child_node in successors:
if child_node in self.closed_nodes:
continue
if child_node not in self.open_nodes:
self.open_nodes.append(__magic_name__ )
else:
# retrieve the best current path
a__ = self.open_nodes.pop(self.open_nodes.index(__magic_name__ ) )
if child_node.g_cost < better_node.g_cost:
self.open_nodes.append(__magic_name__ )
else:
self.open_nodes.append(__magic_name__ )
if not self.reached:
return [self.start.pos]
return None
def _UpperCamelCase ( self :List[str] , __magic_name__ :Node ) -> list[Node]:
'''simple docstring'''
a__ = []
for action in delta:
a__ = parent.pos_x + action[1]
a__ = parent.pos_y + action[0]
if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(__magic_name__ ) - 1):
continue
if grid[pos_y][pos_x] != 0:
continue
successors.append(
Node(
__magic_name__ , __magic_name__ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , __magic_name__ , ) )
return successors
def _UpperCamelCase ( self :Any , __magic_name__ :Node | None ) -> Path:
'''simple docstring'''
a__ = node
a__ = []
while current_node is not None:
path.append((current_node.pos_y, current_node.pos_x) )
a__ = current_node.parent
path.reverse()
return path
if __name__ == "__main__":
__lowerCAmelCase : str = (0, 0)
__lowerCAmelCase : Dict = (len(grid) - 1, len(grid[0]) - 1)
for elem in grid:
print(elem)
print('''------''')
__lowerCAmelCase : Optional[int] = GreedyBestFirst(init, goal)
__lowerCAmelCase : Tuple = greedy_bf.search()
if path:
for pos_x, pos_y in path:
__lowerCAmelCase : Tuple = 2
for elem in grid:
print(elem)
| 158 | 1 |
"""simple docstring"""
import copy
import json
import os
import tempfile
from transformers import is_torch_available
from .test_configuration_utils import config_common_kwargs
class __lowerCAmelCase ( _lowercase ):
"""simple docstring"""
def __init__( self : List[Any] , _snake_case : Union[str, Any] , _snake_case : Dict=None , _snake_case : int=True , _snake_case : Any=None , **_snake_case : List[str] ) -> str:
"""simple docstring"""
A_ = parent
A_ = config_class
A_ = has_text_modality
A_ = kwargs
A_ = common_properties
def lowerCamelCase__ ( self : Any ) -> Optional[int]:
"""simple docstring"""
A_ = self.config_class(**self.inputs_dict )
A_ = (
["hidden_size", "num_attention_heads", "num_hidden_layers"]
if self.common_properties is None
else self.common_properties
)
# Add common fields for text models
if self.has_text_modality:
common_properties.extend(["vocab_size"] )
# Test that config has the common properties as getters
for prop in common_properties:
self.parent.assertTrue(hasattr(_snake_case , _snake_case ) , msg=F'`{prop}` does not exist' )
# Test that config has the common properties as setter
for idx, name in enumerate(_snake_case ):
try:
setattr(_snake_case , _snake_case , _snake_case )
self.parent.assertEqual(
getattr(_snake_case , _snake_case ) , _snake_case , msg=F'`{name} value {idx} expected, but was {getattr(_snake_case , _snake_case )}' )
except NotImplementedError:
# Some models might not be able to implement setters for common_properties
# In that case, a NotImplementedError is raised
pass
# Test if config class can be called with Config(prop_name=..)
for idx, name in enumerate(_snake_case ):
try:
A_ = self.config_class(**{name: idx} )
self.parent.assertEqual(
getattr(_snake_case , _snake_case ) , _snake_case , msg=F'`{name} value {idx} expected, but was {getattr(_snake_case , _snake_case )}' )
except NotImplementedError:
# Some models might not be able to implement setters for common_properties
# In that case, a NotImplementedError is raised
pass
def lowerCamelCase__ ( self : str ) -> Union[str, Any]:
"""simple docstring"""
A_ = self.config_class(**self.inputs_dict )
A_ = json.loads(config.to_json_string() )
for key, value in self.inputs_dict.items():
self.parent.assertEqual(obj[key] , _snake_case )
def lowerCamelCase__ ( self : Optional[Any] ) -> Optional[int]:
"""simple docstring"""
A_ = self.config_class(**self.inputs_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
A_ = os.path.join(_snake_case , "config.json" )
config_first.to_json_file(_snake_case )
A_ = self.config_class.from_json_file(_snake_case )
self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() )
def lowerCamelCase__ ( self : List[Any] ) -> Optional[Any]:
"""simple docstring"""
A_ = self.config_class(**self.inputs_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
config_first.save_pretrained(_snake_case )
A_ = self.config_class.from_pretrained(_snake_case )
self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() )
def lowerCamelCase__ ( self : Optional[Any] ) -> str:
"""simple docstring"""
A_ = self.config_class(**self.inputs_dict )
A_ = "test"
with tempfile.TemporaryDirectory() as tmpdirname:
A_ = os.path.join(_snake_case , _snake_case )
config_first.save_pretrained(_snake_case )
A_ = self.config_class.from_pretrained(_snake_case , subfolder=_snake_case )
self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() )
def lowerCamelCase__ ( self : Union[str, Any] ) -> int:
"""simple docstring"""
A_ = self.config_class(**self.inputs_dict , num_labels=5 )
self.parent.assertEqual(len(config.idalabel ) , 5 )
self.parent.assertEqual(len(config.labelaid ) , 5 )
A_ = 3
self.parent.assertEqual(len(config.idalabel ) , 3 )
self.parent.assertEqual(len(config.labelaid ) , 3 )
def lowerCamelCase__ ( self : Any ) -> List[Any]:
"""simple docstring"""
if self.config_class.is_composition:
return
A_ = self.config_class()
self.parent.assertIsNotNone(_snake_case )
def lowerCamelCase__ ( self : Any ) -> Optional[int]:
"""simple docstring"""
A_ = copy.deepcopy(_snake_case )
A_ = self.config_class(**_snake_case )
A_ = []
for key, value in config_common_kwargs.items():
if key == "torch_dtype":
if not is_torch_available():
continue
else:
import torch
if config.torch_dtype != torch.floataa:
wrong_values.append(("torch_dtype", config.torch_dtype, torch.floataa) )
elif getattr(_snake_case , _snake_case ) != value:
wrong_values.append((key, getattr(_snake_case , _snake_case ), value) )
if len(_snake_case ) > 0:
A_ = "\n".join([F'- {v[0]}: got {v[1]} instead of {v[2]}' for v in wrong_values] )
raise ValueError(F'The following keys were not properly set in the config:\n{errors}' )
def lowerCamelCase__ ( self : Optional[Any] ) -> List[str]:
"""simple docstring"""
self.create_and_test_config_common_properties()
self.create_and_test_config_to_json_string()
self.create_and_test_config_to_json_file()
self.create_and_test_config_from_and_save_pretrained()
self.create_and_test_config_from_and_save_pretrained_subfolder()
self.create_and_test_config_with_num_labels()
self.check_config_can_be_init_without_params()
self.check_config_arguments_init()
| 115 |
"""simple docstring"""
def A_ (__a ):
'''simple docstring'''
A_ = len(__a )
while cur > 1:
# Find the maximum number in arr
A_ = arr.index(max(arr[0:cur] ) )
# Reverse from 0 to mi
A_ = arr[mi::-1] + arr[mi + 1 : len(__a )]
# Reverse whole list
A_ = arr[cur - 1 :: -1] + arr[cur : len(__a )]
cur -= 1
return arr
if __name__ == "__main__":
UpperCamelCase_ : Optional[Any] = input('''Enter numbers separated by a comma:\n''').strip()
UpperCamelCase_ : Any = [int(item) for item in user_input.split(''',''')]
print(pancake_sort(unsorted))
| 115 | 1 |
from string import ascii_uppercase
UpperCAmelCase_ = {char: i for i, char in enumerate(ascii_uppercase)}
UpperCAmelCase_ = dict(enumerate(ascii_uppercase))
def UpperCAmelCase__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str )->str:
_lowerCAmelCase = len(_SCREAMING_SNAKE_CASE )
_lowerCAmelCase = 0
while True:
if x == i:
_lowerCAmelCase = 0
if len(_SCREAMING_SNAKE_CASE ) == len(_SCREAMING_SNAKE_CASE ):
break
key += key[i]
i += 1
return key
def UpperCAmelCase__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str )->str:
_lowerCAmelCase = ''''''
_lowerCAmelCase = 0
for letter in message:
if letter == " ":
cipher_text += " "
else:
_lowerCAmelCase = (dicta[letter] - dicta[key_new[i]]) % 2_6
i += 1
cipher_text += dicta[x]
return cipher_text
def UpperCAmelCase__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str )->str:
_lowerCAmelCase = ''''''
_lowerCAmelCase = 0
for letter in cipher_text:
if letter == " ":
or_txt += " "
else:
_lowerCAmelCase = (dicta[letter] + dicta[key_new[i]] + 2_6) % 2_6
i += 1
or_txt += dicta[x]
return or_txt
def UpperCAmelCase__ ( )->None:
_lowerCAmelCase = '''THE GERMAN ATTACK'''
_lowerCAmelCase = '''SECRET'''
_lowerCAmelCase = generate_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
_lowerCAmelCase = cipher_text(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
print(f'''Encrypted Text = {s}''' )
print(f'''Original Text = {original_text(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )}''' )
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 706 |
from __future__ import annotations
def UpperCAmelCase__ ( _SCREAMING_SNAKE_CASE : list )->list:
if len(_SCREAMING_SNAKE_CASE ) == 0:
return []
_lowerCAmelCase , _lowerCAmelCase = min(_SCREAMING_SNAKE_CASE ), max(_SCREAMING_SNAKE_CASE )
_lowerCAmelCase = int(max_value - min_value ) + 1
_lowerCAmelCase = [[] for _ in range(_SCREAMING_SNAKE_CASE )]
for i in my_list:
buckets[int(i - min_value )].append(_SCREAMING_SNAKE_CASE )
return [v for bucket in buckets for v in sorted(_SCREAMING_SNAKE_CASE )]
if __name__ == "__main__":
from doctest import testmod
testmod()
assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5]
assert bucket_sort([0, 1, -1_0, 1_5, 2, -2]) == [-1_0, -2, 0, 1, 2, 1_5]
| 664 | 0 |
"""simple docstring"""
from string import ascii_uppercase
_snake_case = {str(ord(c) - 55): c for c in ascii_uppercase}
def snake_case ( _a: int , _a: int )-> str:
'''simple docstring'''
if isinstance(_a , _a ):
raise TypeError('int() can\'t convert non-string with explicit base' )
if num < 0:
raise ValueError('parameter must be positive int' )
if isinstance(_a , _a ):
raise TypeError('\'str\' object cannot be interpreted as an integer' )
if isinstance(_a , _a ):
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' )
lowerCamelCase__ = ''
lowerCamelCase__ = 0
lowerCamelCase__ = 0
while div != 1:
lowerCamelCase__ , lowerCamelCase__ = divmod(_a , _a )
if base >= 11 and 9 < mod < 36:
lowerCamelCase__ = ALPHABET_VALUES[str(_a )]
else:
lowerCamelCase__ = str(_a )
new_value += actual_value
lowerCamelCase__ = num // base
lowerCamelCase__ = div
if div == 0:
return str(new_value[::-1] )
elif div == 1:
new_value += str(_a )
return str(new_value[::-1] )
return new_value[::-1]
if __name__ == "__main__":
import doctest
doctest.testmod()
for base in range(2, 37):
for num in range(1000):
assert int(decimal_to_any(num, base), base) == num, (
num,
base,
decimal_to_any(num, base),
int(decimal_to_any(num, base), base),
)
| 510 |
"""simple docstring"""
import os
from datetime import datetime as dt
from github import Github
_snake_case = [
"good first issue",
"good second issue",
"good difficult issue",
"enhancement",
"new pipeline/model",
"new scheduler",
"wip",
]
def snake_case ( )-> int:
'''simple docstring'''
lowerCamelCase__ = Github(os.environ['GITHUB_TOKEN'] )
lowerCamelCase__ = g.get_repo('huggingface/diffusers' )
lowerCamelCase__ = repo.get_issues(state='open' )
for issue in open_issues:
lowerCamelCase__ = sorted(issue.get_comments() , key=lambda _a : i.created_at , reverse=_a )
lowerCamelCase__ = comments[0] if len(_a ) > 0 else None
if (
last_comment is not None
and last_comment.user.login == "github-actions[bot]"
and (dt.utcnow() - issue.updated_at).days > 7
and (dt.utcnow() - issue.created_at).days >= 30
and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
):
# Closes the issue after 7 days of inactivity since the Stalebot notification.
issue.edit(state='closed' )
elif (
"stale" in issue.get_labels()
and last_comment is not None
and last_comment.user.login != "github-actions[bot]"
):
# Opens the issue if someone other than Stalebot commented.
issue.edit(state='open' )
issue.remove_from_labels('stale' )
elif (
(dt.utcnow() - issue.updated_at).days > 23
and (dt.utcnow() - issue.created_at).days >= 30
and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
):
# Post a Stalebot notification after 23 days of inactivity.
issue.create_comment(
'This issue has been automatically marked as stale because it has not had '
'recent activity. If you think this still needs to be addressed '
'please comment on this thread.\n\nPlease note that issues that do not follow the '
'[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) '
'are likely to be ignored.' )
issue.add_to_labels('stale' )
if __name__ == "__main__":
main()
| 510 | 1 |
import pytest
import datasets.config
from datasets.utils.info_utils import is_small_dataset
@pytest.mark.parametrize("""dataset_size""" , [None, 400 * 2**20, 600 * 2**20] )
@pytest.mark.parametrize("""input_in_memory_max_size""" , ["""default""", 0, 100 * 2**20, 900 * 2**20] )
def lowerCamelCase ( UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[str] )-> Dict:
"""simple docstring"""
if input_in_memory_max_size != "default":
monkeypatch.setattr(datasets.config , """IN_MEMORY_MAX_SIZE""" , UpperCAmelCase_ )
a =datasets.config.IN_MEMORY_MAX_SIZE
if input_in_memory_max_size == "default":
assert in_memory_max_size == 0
else:
assert in_memory_max_size == input_in_memory_max_size
if dataset_size and in_memory_max_size:
a =dataset_size < in_memory_max_size
else:
a =False
a =is_small_dataset(UpperCAmelCase_ )
assert result == expected
| 321 |
def lowerCamelCase ( UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : int = 1000 , UpperCAmelCase_ : bool = True )-> int:
"""simple docstring"""
assert (
isinstance(UpperCAmelCase_ , UpperCAmelCase_ )
and isinstance(UpperCAmelCase_ , UpperCAmelCase_ )
and isinstance(UpperCAmelCase_ , UpperCAmelCase_ )
), "Invalid type of value(s) specified to function!"
if min_val > max_val:
raise ValueError("""Invalid value for min_val or max_val (min_value < max_value)""" )
return min_val if option else max_val
def lowerCamelCase ( UpperCAmelCase_ : int , UpperCAmelCase_ : int )-> int:
"""simple docstring"""
return int((number_a + number_a) / 2 )
def lowerCamelCase ( UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int )-> None:
"""simple docstring"""
assert (
isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and isinstance(UpperCAmelCase_ , UpperCAmelCase_ )
), 'argument values must be type of "int"'
if lower > higher:
raise ValueError("""argument value for lower and higher must be(lower > higher)""" )
if not lower < to_guess < higher:
raise ValueError(
"""guess value must be within the range of lower and higher value""" )
def answer(UpperCAmelCase_ : int ) -> str:
if number > to_guess:
return "high"
elif number < to_guess:
return "low"
else:
return "same"
print("""started...""" )
a =lower
a =higher
a =[]
while True:
a =get_avg(UpperCAmelCase_ , UpperCAmelCase_ )
last_numbers.append(UpperCAmelCase_ )
if answer(UpperCAmelCase_ ) == "low":
a =number
elif answer(UpperCAmelCase_ ) == "high":
a =number
else:
break
print(F'''guess the number : {last_numbers[-1]}''' )
print(F'''details : {last_numbers!s}''' )
def lowerCamelCase ( )-> None:
"""simple docstring"""
a =int(input("""Enter lower value : """ ).strip() )
a =int(input("""Enter high value : """ ).strip() )
a =int(input("""Enter value to guess : """ ).strip() )
guess_the_number(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
if __name__ == "__main__":
main()
| 321 | 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_roberta import RobertaTokenizer
__UpperCAmelCase = logging.get_logger(__name__)
__UpperCAmelCase = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'}
__UpperCAmelCase = {
'vocab_file': {
'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/vocab.json',
'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/vocab.json',
'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/vocab.json',
'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/vocab.json',
'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/vocab.json',
'roberta-large-openai-detector': (
'https://huggingface.co/roberta-large-openai-detector/resolve/main/vocab.json'
),
},
'merges_file': {
'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/merges.txt',
'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/merges.txt',
'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/merges.txt',
'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/merges.txt',
'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/merges.txt',
'roberta-large-openai-detector': (
'https://huggingface.co/roberta-large-openai-detector/resolve/main/merges.txt'
),
},
'tokenizer_file': {
'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/tokenizer.json',
'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/tokenizer.json',
'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/tokenizer.json',
'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/tokenizer.json',
'roberta-base-openai-detector': (
'https://huggingface.co/roberta-base-openai-detector/resolve/main/tokenizer.json'
),
'roberta-large-openai-detector': (
'https://huggingface.co/roberta-large-openai-detector/resolve/main/tokenizer.json'
),
},
}
__UpperCAmelCase = {
'roberta-base': 512,
'roberta-large': 512,
'roberta-large-mnli': 512,
'distilroberta-base': 512,
'roberta-base-openai-detector': 512,
'roberta-large-openai-detector': 512,
}
class __lowercase ( __lowerCamelCase ):
snake_case_ = VOCAB_FILES_NAMES
snake_case_ = PRETRAINED_VOCAB_FILES_MAP
snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
snake_case_ = ["""input_ids""", """attention_mask"""]
snake_case_ = RobertaTokenizer
def __init__( self : List[str] ,A : Optional[int]=None ,A : Tuple=None ,A : int=None ,A : Tuple="replace" ,A : Tuple="<s>" ,A : Dict="</s>" ,A : Optional[int]="</s>" ,A : Dict="<s>" ,A : List[Any]="<unk>" ,A : Optional[Any]="<pad>" ,A : List[str]="<mask>" ,A : List[Any]=False ,A : int=True ,**A : Optional[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 ,)
UpperCAmelCase__ : Any = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
if pre_tok_state.get("""add_prefix_space""" ,A ) != add_prefix_space:
UpperCAmelCase__ : Union[str, Any] = getattr(A ,pre_tok_state.pop("""type""" ) )
UpperCAmelCase__ : Dict = add_prefix_space
UpperCAmelCase__ : Dict = pre_tok_class(**A )
UpperCAmelCase__ : List[Any] = add_prefix_space
UpperCAmelCase__ : Dict = """post_processor"""
UpperCAmelCase__ : Any = getattr(self.backend_tokenizer ,A ,A )
if tokenizer_component_instance:
UpperCAmelCase__ : int = json.loads(tokenizer_component_instance.__getstate__() )
# The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
if "sep" in state:
UpperCAmelCase__ : List[Any] = tuple(state["""sep"""] )
if "cls" in state:
UpperCAmelCase__ : List[str] = tuple(state["""cls"""] )
UpperCAmelCase__ : Dict = False
if state.get("""add_prefix_space""" ,A ) != add_prefix_space:
UpperCAmelCase__ : Tuple = add_prefix_space
UpperCAmelCase__ : str = True
if state.get("""trim_offsets""" ,A ) != trim_offsets:
UpperCAmelCase__ : Tuple = trim_offsets
UpperCAmelCase__ : str = True
if changes_to_apply:
UpperCAmelCase__ : List[str] = getattr(A ,state.pop("""type""" ) )
UpperCAmelCase__ : List[Any] = component_class(**A )
setattr(self.backend_tokenizer ,A ,A )
@property
def __lowercase ( 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 __lowercase ( self : Dict ,A : Optional[int] ):
'''simple docstring'''
UpperCAmelCase__ : List[Any] = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else value
UpperCAmelCase__ : Union[str, Any] = value
def __lowercase ( self : int ,*A : Optional[Any] ,**A : Optional[int] ):
'''simple docstring'''
UpperCAmelCase__ : Optional[int] = kwargs.get("""is_split_into_words""" ,A )
assert self.add_prefix_space or not is_split_into_words, (
f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
"to use it with pretokenized inputs."
)
return super()._batch_encode_plus(*A ,**A )
def __lowercase ( self : Union[str, Any] ,*A : Optional[Any] ,**A : List[str] ):
'''simple docstring'''
UpperCAmelCase__ : str = kwargs.get("""is_split_into_words""" ,A )
assert self.add_prefix_space or not is_split_into_words, (
f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
"to use it with pretokenized inputs."
)
return super()._encode_plus(*A ,**A )
def __lowercase ( self : List[str] ,A : str ,A : Optional[str] = None ):
'''simple docstring'''
UpperCAmelCase__ : Optional[int] = self._tokenizer.model.save(A ,name=A )
return tuple(A )
def __lowercase ( self : Optional[int] ,A : List[Any] ,A : str=None ):
'''simple docstring'''
UpperCAmelCase__ : List[str] = [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 __lowercase ( self : List[str] ,A : List[int] ,A : Optional[List[int]] = None ):
'''simple docstring'''
UpperCAmelCase__ : Optional[Any] = [self.sep_token_id]
UpperCAmelCase__ : Dict = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
| 65 |
"""simple docstring"""
import argparse
import os
import torch
from transformers import FlavaConfig, FlavaForPreTraining
from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint
def __UpperCAmelCase ( __UpperCamelCase ):
# encoder.embeddings are double copied in original FLAVA
return sum(param.float().sum() if '''encoder.embeddings''' not in key else 0 for key, param in state_dict.items() )
def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase ):
__lowercase : Any = {}
for key, value in state_dict.items():
if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key:
continue
__lowercase : Dict = key.replace('''heads.cmd.mim_head.cls.predictions''' , '''mmm_image_head''' )
__lowercase : Dict = key.replace('''heads.cmd.mlm_head.cls.predictions''' , '''mmm_text_head''' )
__lowercase : Dict = key.replace('''heads.cmd.itm_head.cls''' , '''itm_head''' )
__lowercase : Tuple = key.replace('''heads.cmd.itm_head.pooler''' , '''itm_head.pooler''' )
__lowercase : Dict = key.replace('''heads.cmd.clip_head.logit_scale''' , '''flava.logit_scale''' )
__lowercase : Optional[int] = key.replace('''heads.fairseq_mlm.cls.predictions''' , '''mlm_head''' )
__lowercase : Optional[int] = key.replace('''heads.imagenet.mim_head.cls.predictions''' , '''mim_head''' )
__lowercase : Union[str, Any] = key.replace('''mm_text_projection''' , '''flava.text_to_mm_projection''' )
__lowercase : str = key.replace('''mm_image_projection''' , '''flava.image_to_mm_projection''' )
__lowercase : Dict = key.replace('''image_encoder.module''' , '''flava.image_model''' )
__lowercase : str = key.replace('''text_encoder.module''' , '''flava.text_model''' )
__lowercase : Dict = key.replace('''mm_encoder.module.encoder.cls_token''' , '''flava.multimodal_model.cls_token''' )
__lowercase : Union[str, Any] = key.replace('''mm_encoder.module''' , '''flava.multimodal_model''' )
__lowercase : List[str] = key.replace('''text_projection''' , '''flava.text_projection''' )
__lowercase : Any = key.replace('''image_projection''' , '''flava.image_projection''' )
__lowercase : Tuple = value.float()
for key, value in codebook_state_dict.items():
__lowercase : int = value
return upgrade
@torch.no_grad()
def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None ):
if config_path is not None:
__lowercase : Union[str, Any] = FlavaConfig.from_pretrained(__UpperCamelCase )
else:
__lowercase : Union[str, Any] = FlavaConfig()
__lowercase : Any = FlavaForPreTraining(__UpperCamelCase ).eval()
__lowercase : Any = convert_dalle_checkpoint(__UpperCamelCase , __UpperCamelCase , save_checkpoint=__UpperCamelCase )
if os.path.exists(__UpperCamelCase ):
__lowercase : Optional[Any] = torch.load(__UpperCamelCase , map_location='''cpu''' )
else:
__lowercase : List[Any] = torch.hub.load_state_dict_from_url(__UpperCamelCase , map_location='''cpu''' )
__lowercase : Optional[int] = upgrade_state_dict(__UpperCamelCase , __UpperCamelCase )
hf_model.load_state_dict(__UpperCamelCase )
__lowercase : Union[str, Any] = hf_model.state_dict()
__lowercase : Optional[Any] = count_parameters(__UpperCamelCase )
__lowercase : List[Any] = count_parameters(__UpperCamelCase ) + count_parameters(__UpperCamelCase )
assert torch.allclose(__UpperCamelCase , __UpperCamelCase , atol=1e-3 )
hf_model.save_pretrained(__UpperCamelCase )
if __name__ == "__main__":
a_ = argparse.ArgumentParser()
parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to flava checkpoint')
parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint')
parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert')
a_ = parser.parse_args()
convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
| 76 | 0 |
def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : int ,lowerCAmelCase_ : int ) -> int:
"""simple docstring"""
while b:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] =b, a % b
return a
def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : int ,lowerCAmelCase_ : int ) -> int:
"""simple docstring"""
return a if b == 0 else euclidean_gcd_recursive(lowerCAmelCase_ ,a % b )
def SCREAMING_SNAKE_CASE__ ( ) -> str:
"""simple docstring"""
print(F"""euclidean_gcd(3, 5) = {euclidean_gcd(3 ,5 )}""" )
print(F"""euclidean_gcd(5, 3) = {euclidean_gcd(5 ,3 )}""" )
print(F"""euclidean_gcd(1, 3) = {euclidean_gcd(1 ,3 )}""" )
print(F"""euclidean_gcd(3, 6) = {euclidean_gcd(3 ,6 )}""" )
print(F"""euclidean_gcd(6, 3) = {euclidean_gcd(6 ,3 )}""" )
print(F"""euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3 ,5 )}""" )
print(F"""euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5 ,3 )}""" )
print(F"""euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1 ,3 )}""" )
print(F"""euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3 ,6 )}""" )
print(F"""euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6 ,3 )}""" )
if __name__ == "__main__":
main()
| 153 |
from __future__ import annotations
__SCREAMING_SNAKE_CASE = '#'
class lowerCAmelCase_ :
'''simple docstring'''
def __init__( self ):
SCREAMING_SNAKE_CASE_ : dict ={}
def __lowerCamelCase ( self , __UpperCAmelCase ):
SCREAMING_SNAKE_CASE_ : Tuple =self._trie
for char in text:
if char not in trie:
SCREAMING_SNAKE_CASE_ : Optional[int] ={}
SCREAMING_SNAKE_CASE_ : Any =trie[char]
SCREAMING_SNAKE_CASE_ : Optional[Any] =True
def __lowerCamelCase ( self , __UpperCAmelCase ):
SCREAMING_SNAKE_CASE_ : Tuple =self._trie
for char in prefix:
if char in trie:
SCREAMING_SNAKE_CASE_ : Tuple =trie[char]
else:
return []
return self._elements(__UpperCAmelCase )
def __lowerCamelCase ( self , __UpperCAmelCase ):
SCREAMING_SNAKE_CASE_ : Optional[int] =[]
for c, v in d.items():
SCREAMING_SNAKE_CASE_ : List[Any] =[' '] if c == END else [(c + s) for s in self._elements(__UpperCAmelCase )]
result.extend(__UpperCAmelCase )
return tuple(__UpperCAmelCase )
__SCREAMING_SNAKE_CASE = Trie()
__SCREAMING_SNAKE_CASE = ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal')
for word in words:
trie.insert_word(word)
def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : str ) -> tuple:
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : str =trie.find_word(lowerCAmelCase_ )
return tuple(string + word for word in suffixes )
def SCREAMING_SNAKE_CASE__ ( ) -> None:
"""simple docstring"""
print(autocomplete_using_trie('de' ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 153 | 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 ) -> Optional[Any]:
return EnvironmentCommand()
class UpperCAmelCase ( UpperCAmelCase__ ):
'''simple docstring'''
@staticmethod
def UpperCamelCase( SCREAMING_SNAKE_CASE_ ) -> Dict:
'''simple docstring'''
lowerCamelCase_ = parser.add_parser('env' )
download_parser.set_defaults(func=SCREAMING_SNAKE_CASE_ )
def UpperCamelCase( self ) -> Dict:
'''simple docstring'''
lowerCamelCase_ = huggingface_hub.__version__
lowerCamelCase_ = 'not installed'
lowerCamelCase_ = 'NA'
if is_torch_available():
import torch
lowerCamelCase_ = torch.__version__
lowerCamelCase_ = torch.cuda.is_available()
lowerCamelCase_ = 'not installed'
if is_transformers_available():
import transformers
lowerCamelCase_ = transformers.__version__
lowerCamelCase_ = 'not installed'
if is_accelerate_available():
import accelerate
lowerCamelCase_ = accelerate.__version__
lowerCamelCase_ = 'not installed'
if is_xformers_available():
import xformers
lowerCamelCase_ = xformers.__version__
lowerCamelCase_ = {
'`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(SCREAMING_SNAKE_CASE_ ) )
return info
@staticmethod
def UpperCamelCase( SCREAMING_SNAKE_CASE_ ) -> List[str]:
'''simple docstring'''
return "\n".join([f'''- {prop}: {val}''' for prop, val in d.items()] ) + "\n"
| 42 |
'''simple docstring'''
def a__ ( lowercase : Dict, lowercase : Optional[Any] ) -> int:
"""simple docstring"""
_UpperCamelCase = 0
_UpperCamelCase = len(lowercase ) - 1
while left <= right:
# avoid divided by 0 during interpolation
if sorted_collection[left] == sorted_collection[right]:
if sorted_collection[left] == item:
return left
else:
return None
_UpperCamelCase = left + ((item - sorted_collection[left]) * (right - left)) // (
sorted_collection[right] - sorted_collection[left]
)
# out of range check
if point < 0 or point >= len(lowercase ):
return None
_UpperCamelCase = sorted_collection[point]
if current_item == item:
return point
else:
if point < left:
_UpperCamelCase = left
_UpperCamelCase = point
elif point > right:
_UpperCamelCase = right
_UpperCamelCase = point
else:
if item < current_item:
_UpperCamelCase = point - 1
else:
_UpperCamelCase = point + 1
return None
def a__ ( lowercase : int, lowercase : Optional[int], lowercase : List[Any], lowercase : List[Any] ) -> Dict:
"""simple docstring"""
if sorted_collection[left] == sorted_collection[right]:
if sorted_collection[left] == item:
return left
else:
return None
_UpperCamelCase = left + ((item - sorted_collection[left]) * (right - left)) // (
sorted_collection[right] - sorted_collection[left]
)
# out of range check
if point < 0 or point >= len(lowercase ):
return None
if sorted_collection[point] == item:
return point
elif point < left:
return interpolation_search_by_recursion(lowercase, lowercase, lowercase, lowercase )
elif point > right:
return interpolation_search_by_recursion(lowercase, lowercase, lowercase, lowercase )
else:
if sorted_collection[point] > item:
return interpolation_search_by_recursion(
lowercase, lowercase, lowercase, point - 1 )
else:
return interpolation_search_by_recursion(
lowercase, lowercase, point + 1, lowercase )
def a__ ( lowercase : Any ) -> List[Any]:
"""simple docstring"""
if collection != sorted(lowercase ):
raise ValueError('''Collection must be ascending sorted''' )
return True
if __name__ == "__main__":
import sys
lowercase__ : int = 0
if debug == 1:
lowercase__ : Optional[Any] = [10, 30, 40, 45, 50, 66, 77, 93]
try:
__assert_sorted(collection)
except ValueError:
sys.exit('Sequence must be ascending sorted to apply interpolation search')
lowercase__ : List[str] = 67
lowercase__ : Optional[int] = interpolation_search(collection, target)
if result is not None:
print(F"""{target} found at positions: {result}""")
else:
print('Not found')
| 98 | 0 |
"""simple docstring"""
import inspect
import unittest
from transformers import ViTConfig
from transformers.testing_utils import (
require_accelerate,
require_torch,
require_torch_gpu,
require_vision,
slow,
torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import ViTImageProcessor
class _lowerCAmelCase :
def __init__( self , UpperCamelCase__ , UpperCamelCase__=13 , UpperCamelCase__=30 , UpperCamelCase__=2 , UpperCamelCase__=3 , UpperCamelCase__=True , UpperCamelCase__=True , UpperCamelCase__=32 , UpperCamelCase__=5 , UpperCamelCase__=4 , UpperCamelCase__=37 , UpperCamelCase__="gelu" , UpperCamelCase__=0.1 , UpperCamelCase__=0.1 , UpperCamelCase__=10 , UpperCamelCase__=0.02 , UpperCamelCase__=None , UpperCamelCase__=2 , ) -> Optional[int]:
'''simple docstring'''
snake_case : Tuple = parent
snake_case : Dict = batch_size
snake_case : Union[str, Any] = image_size
snake_case : Tuple = patch_size
snake_case : List[Any] = num_channels
snake_case : Union[str, Any] = is_training
snake_case : Optional[int] = use_labels
snake_case : Any = hidden_size
snake_case : Optional[int] = num_hidden_layers
snake_case : Any = num_attention_heads
snake_case : Optional[int] = intermediate_size
snake_case : int = hidden_act
snake_case : Optional[Any] = hidden_dropout_prob
snake_case : Dict = attention_probs_dropout_prob
snake_case : str = type_sequence_label_size
snake_case : List[str] = initializer_range
snake_case : Optional[Any] = scope
snake_case : Tuple = encoder_stride
# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
snake_case : Optional[Any] = (image_size // patch_size) ** 2
snake_case : Union[str, Any] = num_patches + 1
def lowerCamelCase ( self ) -> Optional[int]:
'''simple docstring'''
snake_case : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
snake_case : Any = None
if self.use_labels:
snake_case : int = ids_tensor([self.batch_size] , self.type_sequence_label_size )
snake_case : List[str] = self.get_config()
return config, pixel_values, labels
def lowerCamelCase ( self ) -> Union[str, Any]:
'''simple docstring'''
return 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=UpperCamelCase__ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , )
def lowerCamelCase ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Union[str, Any]:
'''simple docstring'''
snake_case : str = ViTModel(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
snake_case : Any = model(UpperCamelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def lowerCamelCase ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> int:
'''simple docstring'''
snake_case : Union[str, Any] = ViTForMaskedImageModeling(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
snake_case : List[Any] = model(UpperCamelCase__ )
self.parent.assertEqual(
result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) )
# test greyscale images
snake_case : Optional[int] = 1
snake_case : Any = ViTForMaskedImageModeling(UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
snake_case : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
snake_case : int = model(UpperCamelCase__ )
self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) )
def lowerCamelCase ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Dict:
'''simple docstring'''
snake_case : List[Any] = self.type_sequence_label_size
snake_case : int = ViTForImageClassification(UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
snake_case : Tuple = model(UpperCamelCase__ , labels=UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
# test greyscale images
snake_case : Any = 1
snake_case : str = ViTForImageClassification(UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
snake_case : Union[str, Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
snake_case : int = model(UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def lowerCamelCase ( self ) -> List[Any]:
'''simple docstring'''
snake_case : Dict = self.prepare_config_and_inputs()
(
(
snake_case
) ,(
snake_case
) ,(
snake_case
) ,
) : List[Any] = config_and_inputs
snake_case : Tuple = {"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
class _lowerCAmelCase ( snake_case_ , snake_case_ , unittest.TestCase ):
__UpperCAmelCase : Tuple = (
(
ViTModel,
ViTForImageClassification,
ViTForMaskedImageModeling,
)
if is_torch_available()
else ()
)
__UpperCAmelCase : Any = (
{'''feature-extraction''': ViTModel, '''image-classification''': ViTForImageClassification}
if is_torch_available()
else {}
)
__UpperCAmelCase : Optional[int] = True
__UpperCAmelCase : Any = False
__UpperCAmelCase : str = False
__UpperCAmelCase : Tuple = False
def lowerCamelCase ( self ) -> Dict:
'''simple docstring'''
snake_case : Dict = ViTModelTester(self )
snake_case : str = ConfigTester(self , config_class=UpperCamelCase__ , has_text_modality=UpperCamelCase__ , hidden_size=37 )
def lowerCamelCase ( self ) -> Optional[Any]:
'''simple docstring'''
self.config_tester.run_common_tests()
@unittest.skip(reason="ViT does not use inputs_embeds" )
def lowerCamelCase ( self ) -> str:
'''simple docstring'''
pass
def lowerCamelCase ( self ) -> Tuple:
'''simple docstring'''
snake_case ,snake_case : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
snake_case : Optional[int] = model_class(UpperCamelCase__ )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
snake_case : Optional[Any] = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(UpperCamelCase__ , nn.Linear ) )
def lowerCamelCase ( self ) -> Union[str, Any]:
'''simple docstring'''
snake_case ,snake_case : List[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
snake_case : Union[str, Any] = model_class(UpperCamelCase__ )
snake_case : Optional[int] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
snake_case : int = [*signature.parameters.keys()]
snake_case : Dict = ["pixel_values"]
self.assertListEqual(arg_names[:1] , UpperCamelCase__ )
def lowerCamelCase ( self ) -> Optional[Any]:
'''simple docstring'''
snake_case : List[str] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*UpperCamelCase__ )
def lowerCamelCase ( self ) -> Tuple:
'''simple docstring'''
snake_case : List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_image_modeling(*UpperCamelCase__ )
def lowerCamelCase ( self ) -> Optional[int]:
'''simple docstring'''
snake_case : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__ )
@slow
def lowerCamelCase ( self ) -> List[str]:
'''simple docstring'''
for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
snake_case : Union[str, Any] = ViTModel.from_pretrained(UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
def __lowerCAmelCase ( ) -> Optional[Any]:
"""simple docstring"""
snake_case : str = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_torch
@require_vision
class _lowerCAmelCase ( unittest.TestCase ):
@cached_property
def lowerCamelCase ( self ) -> Dict:
'''simple docstring'''
return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224" ) if is_vision_available() else None
@slow
def lowerCamelCase ( self ) -> Tuple:
'''simple docstring'''
snake_case : Union[str, Any] = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224" ).to(UpperCamelCase__ )
snake_case : List[Any] = self.default_image_processor
snake_case : Optional[Any] = prepare_img()
snake_case : List[str] = image_processor(images=UpperCamelCase__ , return_tensors="pt" ).to(UpperCamelCase__ )
# forward pass
with torch.no_grad():
snake_case : List[Any] = model(**UpperCamelCase__ )
# verify the logits
snake_case : List[Any] = torch.Size((1, 1000) )
self.assertEqual(outputs.logits.shape , UpperCamelCase__ )
snake_case : List[str] = torch.tensor([-0.2744, 0.8215, -0.0836] ).to(UpperCamelCase__ )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCamelCase__ , atol=1e-4 ) )
@slow
def lowerCamelCase ( self ) -> Optional[Any]:
'''simple docstring'''
snake_case : Dict = ViTModel.from_pretrained("facebook/dino-vits8" ).to(UpperCamelCase__ )
snake_case : Dict = ViTImageProcessor.from_pretrained("facebook/dino-vits8" , size=480 )
snake_case : str = prepare_img()
snake_case : Any = image_processor(images=UpperCamelCase__ , return_tensors="pt" )
snake_case : List[Any] = inputs.pixel_values.to(UpperCamelCase__ )
# forward pass
with torch.no_grad():
snake_case : str = model(UpperCamelCase__ , interpolate_pos_encoding=UpperCamelCase__ )
# verify the logits
snake_case : Tuple = torch.Size((1, 3601, 384) )
self.assertEqual(outputs.last_hidden_state.shape , UpperCamelCase__ )
snake_case : List[str] = torch.tensor(
[[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]] ).to(UpperCamelCase__ )
self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , UpperCamelCase__ , atol=1e-4 ) )
@slow
@require_accelerate
@require_torch_gpu
def lowerCamelCase ( self ) -> Tuple:
'''simple docstring'''
snake_case : int = ViTModel.from_pretrained("facebook/dino-vits8" , torch_dtype=torch.floataa , device_map="auto" )
snake_case : Optional[int] = self.default_image_processor
snake_case : str = prepare_img()
snake_case : List[Any] = image_processor(images=UpperCamelCase__ , return_tensors="pt" )
snake_case : str = inputs.pixel_values.to(UpperCamelCase__ )
# forward pass to make sure inference works in fp16
with torch.no_grad():
snake_case : Any = model(UpperCamelCase__ )
| 117 |
"""simple docstring"""
import unittest
import numpy as np
import torch
from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device
enable_full_determinism()
class _lowerCAmelCase ( unittest.TestCase ):
@property
def lowerCamelCase ( self ) -> Any:
'''simple docstring'''
torch.manual_seed(0 )
snake_case : Tuple = UNetaDModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("DownBlock2D", "AttnDownBlock2D") , up_block_types=("AttnUpBlock2D", "UpBlock2D") , )
return model
def lowerCamelCase ( self ) -> Optional[Any]:
'''simple docstring'''
snake_case : Optional[Any] = self.dummy_uncond_unet
snake_case : str = PNDMScheduler()
snake_case : List[Any] = PNDMPipeline(unet=UpperCamelCase__ , scheduler=UpperCamelCase__ )
pndm.to(UpperCamelCase__ )
pndm.set_progress_bar_config(disable=UpperCamelCase__ )
snake_case : str = torch.manual_seed(0 )
snake_case : Union[str, Any] = pndm(generator=UpperCamelCase__ , num_inference_steps=20 , output_type="numpy" ).images
snake_case : Optional[int] = torch.manual_seed(0 )
snake_case : Any = pndm(generator=UpperCamelCase__ , num_inference_steps=20 , output_type="numpy" , return_dict=UpperCamelCase__ )[0]
snake_case : Optional[Any] = image[0, -3:, -3:, -1]
snake_case : List[str] = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 32, 32, 3)
snake_case : int = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
@slow
@require_torch
class _lowerCAmelCase ( unittest.TestCase ):
def lowerCamelCase ( self ) -> Optional[int]:
'''simple docstring'''
snake_case : Dict = "google/ddpm-cifar10-32"
snake_case : Optional[int] = UNetaDModel.from_pretrained(UpperCamelCase__ )
snake_case : List[str] = PNDMScheduler()
snake_case : Union[str, Any] = PNDMPipeline(unet=UpperCamelCase__ , scheduler=UpperCamelCase__ )
pndm.to(UpperCamelCase__ )
pndm.set_progress_bar_config(disable=UpperCamelCase__ )
snake_case : int = torch.manual_seed(0 )
snake_case : str = pndm(generator=UpperCamelCase__ , output_type="numpy" ).images
snake_case : Union[str, Any] = image[0, -3:, -3:, -1]
assert image.shape == (1, 32, 32, 3)
snake_case : Optional[Any] = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
| 117 | 1 |
def UpperCamelCase ( _A : int = 600851475143 )-> Tuple:
"""simple docstring"""
try:
A__ = int(_A )
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." )
A__ = 2
A__ = 0
if n == 2:
return 2
while n > 2:
while n % i != 0:
i += 1
A__ = i
while n % i == 0:
A__ = n // i
i += 1
return int(_A )
if __name__ == "__main__":
print(F'''{solution() = }''')
| 491 |
"""simple docstring"""
import argparse
from typing import List
import evaluate
import numpy as np
import torch
from datasets import DatasetDict, load_dataset
# New Code #
# We'll be using StratifiedKFold for this example
from sklearn.model_selection import StratifiedKFold
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to perform Cross Validation,
# and builds off the `nlp_example.py` script.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
# - single CPU or single GPU
# - multi GPUS (using PyTorch distributed mode)
# - (multi) TPUs
# - fp16 (mixed-precision) or fp32 (normal precision)
#
# To help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################
_UpperCamelCase = 16
_UpperCamelCase = 32
def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE : Accelerator , SCREAMING_SNAKE_CASE : DatasetDict , SCREAMING_SNAKE_CASE : List[int] , SCREAMING_SNAKE_CASE : List[int] , SCREAMING_SNAKE_CASE : int = 16 ):
'''simple docstring'''
__lowerCamelCase : Union[str, Any] =AutoTokenizer.from_pretrained('''bert-base-cased''' )
__lowerCamelCase : List[str] =DatasetDict(
{
'''train''': dataset['''train'''].select(SCREAMING_SNAKE_CASE ),
'''validation''': dataset['''train'''].select(SCREAMING_SNAKE_CASE ),
'''test''': dataset['''validation'''],
} )
def tokenize_function(SCREAMING_SNAKE_CASE : Optional[Any] ):
# max_length=None => use the model max length (it's actually the default)
__lowerCamelCase : Optional[int] =tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE )
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
__lowerCamelCase : Optional[Any] =datasets.map(
SCREAMING_SNAKE_CASE , batched=SCREAMING_SNAKE_CASE , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
__lowerCamelCase : Dict =tokenized_datasets.rename_column('''label''' , '''labels''' )
def collate_fn(SCREAMING_SNAKE_CASE : List[str] ):
# On TPU it's best to pad everything to the same length or training will be very slow.
__lowerCamelCase : Tuple =128 if accelerator.distributed_type == DistributedType.TPU else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
__lowerCamelCase : List[str] =16
elif accelerator.mixed_precision != "no":
__lowerCamelCase : Tuple =8
else:
__lowerCamelCase : Optional[int] =None
return tokenizer.pad(
SCREAMING_SNAKE_CASE , padding='''longest''' , max_length=SCREAMING_SNAKE_CASE , pad_to_multiple_of=SCREAMING_SNAKE_CASE , return_tensors='''pt''' , )
# Instantiate dataloaders.
__lowerCamelCase : int =DataLoader(
tokenized_datasets['''train'''] , shuffle=SCREAMING_SNAKE_CASE , collate_fn=SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE )
__lowerCamelCase : Optional[Any] =DataLoader(
tokenized_datasets['''validation'''] , shuffle=SCREAMING_SNAKE_CASE , collate_fn=SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE )
__lowerCamelCase : Tuple =DataLoader(
tokenized_datasets['''test'''] , shuffle=SCREAMING_SNAKE_CASE , collate_fn=SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE )
return train_dataloader, eval_dataloader, test_dataloader
def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : List[Any] ):
'''simple docstring'''
__lowerCamelCase : Optional[Any] =[]
# Download the dataset
__lowerCamelCase : Any =load_dataset('''glue''' , '''mrpc''' )
# Create our splits
__lowerCamelCase : Optional[Any] =StratifiedKFold(n_splits=int(args.num_folds ) )
# Initialize accelerator
__lowerCamelCase : str =Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
__lowerCamelCase : Any =config['''lr''']
__lowerCamelCase : int =int(config['''num_epochs'''] )
__lowerCamelCase : Optional[int] =int(config['''seed'''] )
__lowerCamelCase : Any =int(config['''batch_size'''] )
__lowerCamelCase : List[str] =evaluate.load('''glue''' , '''mrpc''' )
# If the batch size is too big we use gradient accumulation
__lowerCamelCase : List[Any] =1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
__lowerCamelCase : Optional[Any] =batch_size // MAX_GPU_BATCH_SIZE
__lowerCamelCase : List[Any] =MAX_GPU_BATCH_SIZE
set_seed(SCREAMING_SNAKE_CASE )
# New Code #
# Create our folds:
__lowerCamelCase : str =kfold.split(np.zeros(datasets['''train'''].num_rows ) , datasets['''train''']['''label'''] )
__lowerCamelCase : Tuple =[]
# Iterate over them
for i, (train_idxs, valid_idxs) in enumerate(SCREAMING_SNAKE_CASE ):
__lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any =get_fold_dataloaders(
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
__lowerCamelCase : Optional[int] =AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=SCREAMING_SNAKE_CASE )
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
__lowerCamelCase : Optional[Any] =model.to(accelerator.device )
# Instantiate optimizer
__lowerCamelCase : Any =AdamW(params=model.parameters() , lr=SCREAMING_SNAKE_CASE )
# Instantiate scheduler
__lowerCamelCase : Dict =get_linear_schedule_with_warmup(
optimizer=SCREAMING_SNAKE_CASE , num_warmup_steps=100 , num_training_steps=(len(SCREAMING_SNAKE_CASE ) * num_epochs) // gradient_accumulation_steps , )
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any =accelerator.prepare(
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
# Now we train the model
for epoch in range(SCREAMING_SNAKE_CASE ):
model.train()
for step, batch in enumerate(SCREAMING_SNAKE_CASE ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
__lowerCamelCase : Dict =model(**SCREAMING_SNAKE_CASE )
__lowerCamelCase : Optional[Any] =outputs.loss
__lowerCamelCase : int =loss / gradient_accumulation_steps
accelerator.backward(SCREAMING_SNAKE_CASE )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
for step, batch in enumerate(SCREAMING_SNAKE_CASE ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
__lowerCamelCase : Optional[int] =model(**SCREAMING_SNAKE_CASE )
__lowerCamelCase : int =outputs.logits.argmax(dim=-1 )
__lowerCamelCase , __lowerCamelCase : Union[str, Any] =accelerator.gather_for_metrics((predictions, batch['''labels''']) )
metric.add_batch(
predictions=SCREAMING_SNAKE_CASE , references=SCREAMING_SNAKE_CASE , )
__lowerCamelCase : str =metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(F'epoch {epoch}:' , SCREAMING_SNAKE_CASE )
# New Code #
# We also run predictions on the test set at the very end
__lowerCamelCase : Tuple =[]
for step, batch in enumerate(SCREAMING_SNAKE_CASE ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
__lowerCamelCase : List[Any] =model(**SCREAMING_SNAKE_CASE )
__lowerCamelCase : int =outputs.logits
__lowerCamelCase , __lowerCamelCase : Union[str, Any] =accelerator.gather_for_metrics((predictions, batch['''labels''']) )
fold_predictions.append(predictions.cpu() )
if i == 0:
# We need all of the test predictions
test_references.append(references.cpu() )
# Use accelerator.print to print only on the main process.
test_predictions.append(torch.cat(SCREAMING_SNAKE_CASE , dim=0 ) )
# We now need to release all our memory and get rid of the current model, optimizer, etc
accelerator.free_memory()
# New Code #
# Finally we check the accuracy of our folded results:
__lowerCamelCase : Optional[Any] =torch.cat(SCREAMING_SNAKE_CASE , dim=0 )
__lowerCamelCase : int =torch.stack(SCREAMING_SNAKE_CASE , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 )
__lowerCamelCase : Tuple =metric.compute(predictions=SCREAMING_SNAKE_CASE , references=SCREAMING_SNAKE_CASE )
accelerator.print('''Average test metrics from all folds:''' , SCREAMING_SNAKE_CASE )
def lowerCAmelCase_ ( ):
'''simple docstring'''
__lowerCamelCase : int =argparse.ArgumentParser(description='''Simple example of training script.''' )
parser.add_argument(
'''--mixed_precision''' , type=SCREAMING_SNAKE_CASE , default=SCREAMING_SNAKE_CASE , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose'''
'''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.'''
'''and an Nvidia Ampere GPU.''' , )
parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' )
# New Code #
parser.add_argument('''--num_folds''' , type=SCREAMING_SNAKE_CASE , default=3 , help='''The number of splits to perform across the dataset''' )
__lowerCamelCase : Any =parser.parse_args()
__lowerCamelCase : Optional[int] ={'''lr''': 2E-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16}
training_function(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
main()
| 179 | 0 |
import glob
import os
import random
from string import ascii_lowercase, digits
import cva
import numpy as np
# Parrameters
_lowerCamelCase =(7_20, 12_80) # Height, Width
_lowerCamelCase =(0.4, 0.6) # if height or width lower than this scale, drop it.
_lowerCamelCase =1 / 1_00
_lowerCamelCase =""
_lowerCamelCase =""
_lowerCamelCase =""
_lowerCamelCase =2_50
def snake_case__ ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE =get_dataset(lowerCamelCase__, lowerCamelCase__ )
for index in range(lowerCamelCase__ ):
SCREAMING_SNAKE_CASE =random.sample(range(len(lowerCamelCase__ ) ), 4 )
SCREAMING_SNAKE_CASE =update_image_and_anno(
lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, filter_scale=lowerCamelCase__, )
# Get random string code: '7b7ad245cdff75241935e4dd860f3bad'
SCREAMING_SNAKE_CASE =random_chars(32 )
SCREAMING_SNAKE_CASE =path.split(os.sep )[-1].rsplit('.', 1 )[0]
SCREAMING_SNAKE_CASE =F'{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}'
cva.imwrite(F'{file_root}.jpg', lowerCamelCase__, [cva.IMWRITE_JPEG_QUALITY, 85] )
print(F'Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}' )
SCREAMING_SNAKE_CASE =[]
for anno in new_annos:
SCREAMING_SNAKE_CASE =anno[3] - anno[1]
SCREAMING_SNAKE_CASE =anno[4] - anno[2]
SCREAMING_SNAKE_CASE =anno[1] + width / 2
SCREAMING_SNAKE_CASE =anno[2] + height / 2
SCREAMING_SNAKE_CASE =F'{anno[0]} {x_center} {y_center} {width} {height}'
annos_list.append(lowerCamelCase__ )
with open(F'{file_root}.txt', 'w' ) as outfile:
outfile.write('\n'.join(line for line in annos_list ) )
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE =[]
SCREAMING_SNAKE_CASE =[]
for label_file in glob.glob(os.path.join(lowerCamelCase__, '*.txt' ) ):
SCREAMING_SNAKE_CASE =label_file.split(os.sep )[-1].rsplit('.', 1 )[0]
with open(lowerCamelCase__ ) as in_file:
SCREAMING_SNAKE_CASE =in_file.readlines()
SCREAMING_SNAKE_CASE =os.path.join(lowerCamelCase__, F'{label_name}.jpg' )
SCREAMING_SNAKE_CASE =[]
for obj_list in obj_lists:
SCREAMING_SNAKE_CASE =obj_list.rstrip('\n' ).split(' ' )
SCREAMING_SNAKE_CASE =float(obj[1] ) - float(obj[3] ) / 2
SCREAMING_SNAKE_CASE =float(obj[2] ) - float(obj[4] ) / 2
SCREAMING_SNAKE_CASE =float(obj[1] ) + float(obj[3] ) / 2
SCREAMING_SNAKE_CASE =float(obj[2] ) + float(obj[4] ) / 2
boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] )
if not boxes:
continue
img_paths.append(lowerCamelCase__ )
labels.append(lowerCamelCase__ )
return img_paths, labels
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = 0.0, ):
"""simple docstring"""
SCREAMING_SNAKE_CASE =np.zeros([output_size[0], output_size[1], 3], dtype=np.uinta )
SCREAMING_SNAKE_CASE =scale_range[0] + random.random() * (scale_range[1] - scale_range[0])
SCREAMING_SNAKE_CASE =scale_range[0] + random.random() * (scale_range[1] - scale_range[0])
SCREAMING_SNAKE_CASE =int(scale_x * output_size[1] )
SCREAMING_SNAKE_CASE =int(scale_y * output_size[0] )
SCREAMING_SNAKE_CASE =[]
SCREAMING_SNAKE_CASE =[]
for i, index in enumerate(lowerCamelCase__ ):
SCREAMING_SNAKE_CASE =all_img_list[index]
path_list.append(lowerCamelCase__ )
SCREAMING_SNAKE_CASE =all_annos[index]
SCREAMING_SNAKE_CASE =cva.imread(lowerCamelCase__ )
if i == 0: # top-left
SCREAMING_SNAKE_CASE =cva.resize(lowerCamelCase__, (divid_point_x, divid_point_y) )
SCREAMING_SNAKE_CASE =img
for bbox in img_annos:
SCREAMING_SNAKE_CASE =bbox[1] * scale_x
SCREAMING_SNAKE_CASE =bbox[2] * scale_y
SCREAMING_SNAKE_CASE =bbox[3] * scale_x
SCREAMING_SNAKE_CASE =bbox[4] * scale_y
new_anno.append([bbox[0], xmin, ymin, xmax, ymax] )
elif i == 1: # top-right
SCREAMING_SNAKE_CASE =cva.resize(lowerCamelCase__, (output_size[1] - divid_point_x, divid_point_y) )
SCREAMING_SNAKE_CASE =img
for bbox in img_annos:
SCREAMING_SNAKE_CASE =scale_x + bbox[1] * (1 - scale_x)
SCREAMING_SNAKE_CASE =bbox[2] * scale_y
SCREAMING_SNAKE_CASE =scale_x + bbox[3] * (1 - scale_x)
SCREAMING_SNAKE_CASE =bbox[4] * scale_y
new_anno.append([bbox[0], xmin, ymin, xmax, ymax] )
elif i == 2: # bottom-left
SCREAMING_SNAKE_CASE =cva.resize(lowerCamelCase__, (divid_point_x, output_size[0] - divid_point_y) )
SCREAMING_SNAKE_CASE =img
for bbox in img_annos:
SCREAMING_SNAKE_CASE =bbox[1] * scale_x
SCREAMING_SNAKE_CASE =scale_y + bbox[2] * (1 - scale_y)
SCREAMING_SNAKE_CASE =bbox[3] * scale_x
SCREAMING_SNAKE_CASE =scale_y + bbox[4] * (1 - scale_y)
new_anno.append([bbox[0], xmin, ymin, xmax, ymax] )
else: # bottom-right
SCREAMING_SNAKE_CASE =cva.resize(
lowerCamelCase__, (output_size[1] - divid_point_x, output_size[0] - divid_point_y) )
SCREAMING_SNAKE_CASE =img
for bbox in img_annos:
SCREAMING_SNAKE_CASE =scale_x + bbox[1] * (1 - scale_x)
SCREAMING_SNAKE_CASE =scale_y + bbox[2] * (1 - scale_y)
SCREAMING_SNAKE_CASE =scale_x + bbox[3] * (1 - scale_x)
SCREAMING_SNAKE_CASE =scale_y + bbox[4] * (1 - scale_y)
new_anno.append([bbox[0], xmin, ymin, xmax, ymax] )
# Remove bounding box small than scale of filter
if filter_scale > 0:
SCREAMING_SNAKE_CASE =[
anno
for anno in new_anno
if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2])
]
return output_img, new_anno, path_list[0]
def snake_case__ ( lowerCAmelCase_ ):
"""simple docstring"""
assert number_char > 1, "The number of character should greater than 1"
SCREAMING_SNAKE_CASE =ascii_lowercase + digits
return "".join(random.choice(lowerCamelCase__ ) for _ in range(lowerCamelCase__ ) )
if __name__ == "__main__":
main()
print("DONE ✅")
| 710 |
from ..utils import DummyObject, requires_backends
class a_ ( metaclass=lowerCamelCase_ ):
"""simple docstring"""
__UpperCAmelCase = ['torch', 'scipy']
def __init__( self : Any ,*snake_case : Any ,**snake_case : str ):
requires_backends(self ,['torch', 'scipy'] )
@classmethod
def _lowerCAmelCase ( cls : Tuple ,*snake_case : Optional[Any] ,**snake_case : int ):
requires_backends(cls ,['torch', 'scipy'] )
@classmethod
def _lowerCAmelCase ( cls : Optional[int] ,*snake_case : int ,**snake_case : Dict ):
requires_backends(cls ,['torch', 'scipy'] )
| 252 | 0 |
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
lowercase_ = logging.get_logger(__name__)
lowercase_ = {
"""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 __UpperCamelCase ( lowerCAmelCase__ ):
"""simple docstring"""
lowerCAmelCase_ = '''mobilenet_v2'''
def __init__( self : int , _A : Dict=3 , _A : Optional[int]=224 , _A : int=1.0 , _A : List[Any]=8 , _A : Optional[int]=8 , _A : Any=6 , _A : Any=32 , _A : List[Any]=True , _A : Optional[int]=True , _A : int="relu6" , _A : str=True , _A : List[str]=0.8 , _A : str=0.02 , _A : Optional[Any]=0.0_01 , _A : Optional[Any]=255 , **_A : List[Any] , ):
"""simple docstring"""
super().__init__(**_A )
if depth_multiplier <= 0:
raise ValueError('''depth_multiplier must be greater than zero.''' )
__SCREAMING_SNAKE_CASE : Tuple = num_channels
__SCREAMING_SNAKE_CASE : List[str] = image_size
__SCREAMING_SNAKE_CASE : List[Any] = depth_multiplier
__SCREAMING_SNAKE_CASE : str = depth_divisible_by
__SCREAMING_SNAKE_CASE : Union[str, Any] = min_depth
__SCREAMING_SNAKE_CASE : int = expand_ratio
__SCREAMING_SNAKE_CASE : str = output_stride
__SCREAMING_SNAKE_CASE : Optional[int] = first_layer_is_expansion
__SCREAMING_SNAKE_CASE : Tuple = finegrained_output
__SCREAMING_SNAKE_CASE : Optional[Any] = hidden_act
__SCREAMING_SNAKE_CASE : Any = tf_padding
__SCREAMING_SNAKE_CASE : Any = classifier_dropout_prob
__SCREAMING_SNAKE_CASE : Optional[Any] = initializer_range
__SCREAMING_SNAKE_CASE : str = layer_norm_eps
__SCREAMING_SNAKE_CASE : Optional[Any] = semantic_loss_ignore_index
class __UpperCamelCase ( lowerCAmelCase__ ):
"""simple docstring"""
lowerCAmelCase_ = version.parse('''1.11''' )
@property
def UpperCAmelCase__ ( self : Optional[int] ):
"""simple docstring"""
return OrderedDict([('''pixel_values''', {0: '''batch'''})] )
@property
def UpperCAmelCase__ ( self : 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 UpperCAmelCase__ ( self : List[Any] ):
"""simple docstring"""
return 1e-4
| 74 |
"""simple docstring"""
import importlib
import inspect
import os
import re
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_config_docstrings.py
__A = "src/transformers"
# This is to make sure the transformers module imported is the one in the repo.
__A = importlib.util.spec_from_file_location(
"transformers",
os.path.join(PATH_TO_TRANSFORMERS, "__init__.py"),
submodule_search_locations=[PATH_TO_TRANSFORMERS],
)
__A = spec.loader.load_module()
__A = 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 = re.compile("\[(.+?)\]\((https://huggingface\.co/.+?)\)")
__A = {
"CLIPConfigMixin",
"DecisionTransformerConfigMixin",
"EncoderDecoderConfigMixin",
"RagConfigMixin",
"SpeechEncoderDecoderConfigMixin",
"VisionEncoderDecoderConfigMixin",
"VisionTextDualEncoderConfigMixin",
}
def a__ ( ) -> int:
__lowerCAmelCase: str = []
for config_class in list(CONFIG_MAPPING.values() ):
__lowerCAmelCase: List[Any] = False
# source code of `config_class`
__lowerCAmelCase: Any = inspect.getsource(__SCREAMING_SNAKE_CASE )
__lowerCAmelCase: List[str] = _re_checkpoint.findall(__SCREAMING_SNAKE_CASE )
for checkpoint in checkpoints:
# Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link.
# For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')`
__lowerCAmelCase , __lowerCAmelCase: List[str] = checkpoint
# verify the checkpoint name corresponds to the checkpoint link
__lowerCAmelCase: Tuple = F"https://huggingface.co/{ckpt_name}"
if ckpt_link == ckpt_link_from_name:
__lowerCAmelCase: str = True
break
__lowerCAmelCase: Optional[Any] = config_class.__name__
if not checkpoint_found and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK:
configs_without_checkpoint.append(__SCREAMING_SNAKE_CASE )
if len(__SCREAMING_SNAKE_CASE ) > 0:
__lowerCAmelCase: Union[str, Any] = "\n".join(sorted(__SCREAMING_SNAKE_CASE ) )
raise ValueError(F"The following configurations don't contain any valid checkpoint:\n{message}" )
if __name__ == "__main__":
check_config_docstrings_have_checkpoints()
| 346 | 0 |
'''simple docstring'''
import json
import os
import unittest
from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES, XLMTokenizer
from transformers.testing_utils import slow
from ...test_tokenization_common import TokenizerTesterMixin
class SCREAMING_SNAKE_CASE__ ( snake_case_ , unittest.TestCase):
lowerCAmelCase_ = XLMTokenizer
lowerCAmelCase_ = False
def UpperCAmelCase_ ( self )-> int:
'''simple docstring'''
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
UpperCamelCase = [
'l',
'o',
'w',
'e',
'r',
's',
't',
'i',
'd',
'n',
'w</w>',
'r</w>',
't</w>',
'lo',
'low',
'er</w>',
'low</w>',
'lowest</w>',
'newer</w>',
'wider</w>',
'<unk>',
]
UpperCamelCase = dict(zip(A_ , range(len(A_ ) ) ) )
UpperCamelCase = ['l o 123', 'lo w 1456', 'e r</w> 1789', '']
UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] )
UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] )
with open(self.vocab_file , 'w' ) as fp:
fp.write(json.dumps(A_ ) )
with open(self.merges_file , 'w' ) as fp:
fp.write('\n'.join(A_ ) )
def UpperCAmelCase_ ( self , A_ )-> List[str]:
'''simple docstring'''
UpperCamelCase = 'lower newer'
UpperCamelCase = 'lower newer'
return input_text, output_text
def UpperCAmelCase_ ( self )-> List[str]:
'''simple docstring'''
UpperCamelCase = XLMTokenizer(self.vocab_file , self.merges_file )
UpperCamelCase = 'lower'
UpperCamelCase = ['low', 'er</w>']
UpperCamelCase = tokenizer.tokenize(A_ )
self.assertListEqual(A_ , A_ )
UpperCamelCase = tokens + ['<unk>']
UpperCamelCase = [14, 15, 20]
self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , A_ )
@slow
def UpperCAmelCase_ ( self )-> int:
'''simple docstring'''
UpperCamelCase = XLMTokenizer.from_pretrained('xlm-mlm-en-2048' )
UpperCamelCase = tokenizer.encode('sequence builders' , add_special_tokens=A_ )
UpperCamelCase = tokenizer.encode('multi-sequence build' , add_special_tokens=A_ )
UpperCamelCase = tokenizer.build_inputs_with_special_tokens(A_ )
UpperCamelCase = tokenizer.build_inputs_with_special_tokens(A_ , A_ )
assert encoded_sentence == [0] + text + [1]
assert encoded_pair == [0] + text + [1] + text_a + [1]
| 716 |
'''simple docstring'''
lowerCAmelCase : Optional[Any] = '\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n'
lowerCAmelCase : Optional[int] = [{'type': 'code', 'content': INSTALL_CONTENT}]
lowerCAmelCase : Optional[int] = {
'{processor_class}': 'FakeProcessorClass',
'{model_class}': 'FakeModelClass',
'{object_class}': 'FakeObjectClass',
}
| 432 | 0 |
'''simple docstring'''
import socket
def _UpperCamelCase ( ) -> Optional[int]:
'''simple docstring'''
snake_case : Optional[Any] = socket.socket(socket.AF_INET , socket.SOCK_STREAM )
snake_case : Dict = socket.gethostname()
snake_case : Optional[Any] = 1_2312
sock.connect((host, port) )
sock.send(B'''Hello server!''' )
with open('''Received_file''' , '''wb''' ) as out_file:
print('''File opened''' )
print('''Receiving data...''' )
while True:
snake_case : List[Any] = sock.recv(1024 )
if not data:
break
out_file.write(SCREAMING_SNAKE_CASE__ )
print('''Successfully received the file''' )
sock.close()
print('''Connection closed''' )
if __name__ == "__main__":
main()
| 638 |
'''simple docstring'''
from .data_collator import (
DataCollatorForLanguageModeling,
DataCollatorForPermutationLanguageModeling,
DataCollatorForSeqaSeq,
DataCollatorForSOP,
DataCollatorForTokenClassification,
DataCollatorForWholeWordMask,
DataCollatorWithPadding,
DefaultDataCollator,
default_data_collator,
)
from .metrics import glue_compute_metrics, xnli_compute_metrics
from .processors import (
DataProcessor,
InputExample,
InputFeatures,
SingleSentenceClassificationProcessor,
SquadExample,
SquadFeatures,
SquadVaProcessor,
SquadVaProcessor,
glue_convert_examples_to_features,
glue_output_modes,
glue_processors,
glue_tasks_num_labels,
squad_convert_examples_to_features,
xnli_output_modes,
xnli_processors,
xnli_tasks_num_labels,
)
| 638 | 1 |
"""simple docstring"""
from typing import List
from ...configuration_utils import PretrainedConfig
from ...utils import logging
A__ : Any = logging.get_logger(__name__)
A__ : Optional[Any] = {
'snap-research/efficientformer-l1-300': (
'https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json'
),
}
class __magic_name__ ( SCREAMING_SNAKE_CASE__ ):
UpperCamelCase_ = '''efficientformer'''
def __init__( self , A_ = [3, 2, 6, 4] , A_ = [48, 96, 224, 448] , A_ = [True, True, True, True] , A_ = 448 , A_ = 32 , A_ = 4 , A_ = 7 , A_ = 5 , A_ = 8 , A_ = 4 , A_ = 0.0 , A_ = 16 , A_ = 3 , A_ = 3 , A_ = 3 , A_ = 2 , A_ = 1 , A_ = 0.0 , A_ = 1 , A_ = True , A_ = True , A_ = 1E-5 , A_ = "gelu" , A_ = 0.02 , A_ = 1E-12 , A_ = 224 , A_ = 1E-05 , **A_ , ) -> None:
"""simple docstring"""
super().__init__(**A_ )
_lowercase: Optional[int] = hidden_act
_lowercase: int = hidden_dropout_prob
_lowercase: List[str] = hidden_sizes
_lowercase: str = num_hidden_layers
_lowercase: Tuple = num_attention_heads
_lowercase: List[Any] = initializer_range
_lowercase: List[str] = layer_norm_eps
_lowercase: Union[str, Any] = patch_size
_lowercase: Any = num_channels
_lowercase: List[str] = depths
_lowercase: Tuple = mlp_expansion_ratio
_lowercase: List[str] = downsamples
_lowercase: str = dim
_lowercase: Optional[Any] = key_dim
_lowercase: Any = attention_ratio
_lowercase: Tuple = resolution
_lowercase: Tuple = pool_size
_lowercase: Optional[int] = downsample_patch_size
_lowercase: Any = downsample_stride
_lowercase: int = downsample_pad
_lowercase: Dict = drop_path_rate
_lowercase: str = num_metaad_blocks
_lowercase: Any = distillation
_lowercase: List[Any] = use_layer_scale
_lowercase: Any = layer_scale_init_value
_lowercase: Optional[int] = image_size
_lowercase: Dict = batch_norm_eps
| 707 |
"""simple docstring"""
import logging
import os
import sys
from pathlib import Path
from unittest.mock import patch
from parameterized import parameterized
from run_eval import run_generate
from run_eval_search import run_search
from transformers.testing_utils import CaptureStdout, TestCasePlus, slow
from utils import ROUGE_KEYS
logging.basicConfig(level=logging.DEBUG)
A__ : Any = logging.getLogger()
def _lowerCAmelCase ( _UpperCamelCase , _UpperCamelCase ):
"""simple docstring"""
_lowercase: Optional[int] = '''\n'''.join(_UpperCamelCase )
Path(_UpperCamelCase ).open('''w''' ).writelines(_UpperCamelCase )
A__ : int = 'patrickvonplaten/t5-tiny-random'
A__ : Tuple = 'sshleifer/bart-tiny-random'
A__ : Optional[Any] = 'sshleifer/tiny-mbart'
A__ : Optional[int] = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks
class __magic_name__ ( SCREAMING_SNAKE_CASE__ ):
def lowercase_ ( self , A_ ) -> List[Any]:
"""simple docstring"""
_lowercase: str = Path(self.get_auto_remove_tmp_dir() ) / '''utest_input.source'''
_lowercase: Tuple = input_file_name.parent / '''utest_output.txt'''
assert not output_file_name.exists()
_lowercase: List[str] = [''' New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County.''']
_dump_articles(A_ , A_ )
_lowercase: int = str(Path(self.get_auto_remove_tmp_dir() ) / '''scores.json''' )
_lowercase: Optional[Any] = '''translation_en_to_de''' if model == T5_TINY else '''summarization'''
_lowercase: str = f'''
run_eval_search.py
{model}
{input_file_name}
{output_file_name}
--score_path {score_path}
--task {task}
--num_beams 2
--length_penalty 2.0
'''.split()
with patch.object(A_ , '''argv''' , A_ ):
run_generate()
assert Path(A_ ).exists()
# os.remove(Path(output_file_name))
def lowercase_ ( self ) -> Any:
"""simple docstring"""
self.run_eval_tester(A_ )
@parameterized.expand([BART_TINY, MBART_TINY] )
@slow
def lowercase_ ( self , A_ ) -> Union[str, Any]:
"""simple docstring"""
self.run_eval_tester(A_ )
@parameterized.expand([T5_TINY, MBART_TINY] )
@slow
def lowercase_ ( self , A_ ) -> List[Any]:
"""simple docstring"""
_lowercase: Tuple = Path(self.get_auto_remove_tmp_dir() ) / '''utest_input.source'''
_lowercase: Dict = input_file_name.parent / '''utest_output.txt'''
assert not output_file_name.exists()
_lowercase: int = {
'''en''': ['''Machine learning is great, isn\'t it?''', '''I like to eat bananas''', '''Tomorrow is another great day!'''],
'''de''': [
'''Maschinelles Lernen ist großartig, oder?''',
'''Ich esse gerne Bananen''',
'''Morgen ist wieder ein toller Tag!''',
],
}
_lowercase: Tuple = Path(self.get_auto_remove_tmp_dir() )
_lowercase: Tuple = str(tmp_dir / '''scores.json''' )
_lowercase: List[str] = str(tmp_dir / '''val.target''' )
_dump_articles(A_ , text['''en'''] )
_dump_articles(A_ , text['''de'''] )
_lowercase: Tuple = '''translation_en_to_de''' if model == T5_TINY else '''summarization'''
_lowercase: Tuple = f'''
run_eval_search.py
{model}
{str(A_ )}
{str(A_ )}
--score_path {score_path}
--reference_path {reference_path}
--task {task}
'''.split()
testargs.extend(['''--search''', '''num_beams=1:2 length_penalty=0.9:1.0'''] )
with patch.object(A_ , '''argv''' , A_ ):
with CaptureStdout() as cs:
run_search()
_lowercase: List[str] = [''' num_beams | length_penalty''', model, '''Best score args''']
_lowercase: Union[str, Any] = ['''Info''']
if "translation" in task:
expected_strings.append('''bleu''' )
else:
expected_strings.extend(A_ )
for w in expected_strings:
assert w in cs.out
for w in un_expected_strings:
assert w not in cs.out
assert Path(A_ ).exists()
os.remove(Path(A_ ) )
| 272 | 0 |
import json
import os
from collections import Counter
import torch
import torchvision
import torchvision.transforms as transforms
from PIL import Image
from torch import nn
from torch.utils.data import Dataset
__A : Union[str, Any] = {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (5, 1), 6: (3, 2), 7: (7, 1), 8: (4, 2), 9: (3, 3)}
class lowerCamelCase( nn.Module ):
'''simple docstring'''
def __init__( self , snake_case_ ):
super().__init__()
_A = torchvision.models.resnetaaa(pretrained=snake_case_ )
_A = list(model.children() )[:-2]
_A = nn.Sequential(*snake_case_ )
_A = nn.AdaptiveAvgPoolad(POOLING_BREAKDOWN[args.num_image_embeds] )
def lowerCAmelCase__ ( self , snake_case_ ):
# Bx3x224x224 -> Bx2048x7x7 -> Bx2048xN -> BxNx2048
_A = self.pool(self.model(snake_case_ ) )
_A = torch.flatten(snake_case_ , start_dim=2 )
_A = out.transpose(1 , 2 ).contiguous()
return out # BxNx2048
class lowerCamelCase( __snake_case ):
'''simple docstring'''
def __init__( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ):
_A = [json.loads(snake_case_ ) for l in open(snake_case_ )]
_A = os.path.dirname(snake_case_ )
_A = tokenizer
_A = labels
_A = len(snake_case_ )
_A = max_seq_length
_A = transforms
def __len__( self ):
return len(self.data )
def __getitem__( self , snake_case_ ):
_A = torch.LongTensor(self.tokenizer.encode(self.data[index]['text'] , add_special_tokens=snake_case_ ) )
_A, _A, _A = sentence[0], sentence[1:-1], sentence[-1]
_A = sentence[: self.max_seq_length]
_A = torch.zeros(self.n_classes )
_A = 1
_A = Image.open(os.path.join(self.data_dir , self.data[index]['img'] ) ).convert('RGB' )
_A = self.transforms(snake_case_ )
return {
"image_start_token": start_token,
"image_end_token": end_token,
"sentence": sentence,
"image": image,
"label": label,
}
def lowerCAmelCase__ ( self ):
_A = Counter()
for row in self.data:
label_freqs.update(row['label'] )
return label_freqs
def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Any:
"""simple docstring"""
_A = [len(row['sentence'] ) for row in batch]
_A, _A = len(_SCREAMING_SNAKE_CASE ), max(_SCREAMING_SNAKE_CASE )
_A = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , dtype=torch.long )
_A = torch.zeros(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , dtype=torch.long )
for i_batch, (input_row, length) in enumerate(zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ):
_A = input_row['sentence']
_A = 1
_A = torch.stack([row['image'] for row in batch] )
_A = torch.stack([row['label'] for row in batch] )
_A = torch.stack([row['image_start_token'] for row in batch] )
_A = torch.stack([row['image_end_token'] for row in batch] )
return text_tensor, mask_tensor, img_tensor, img_start_token, img_end_token, tgt_tensor
def __lowerCAmelCase( ) -> Dict:
"""simple docstring"""
return [
"Crime",
"Drama",
"Thriller",
"Action",
"Comedy",
"Romance",
"Documentary",
"Short",
"Mystery",
"History",
"Family",
"Adventure",
"Fantasy",
"Sci-Fi",
"Western",
"Horror",
"Sport",
"War",
"Music",
"Musical",
"Animation",
"Biography",
"Film-Noir",
]
def __lowerCAmelCase( ) -> str:
"""simple docstring"""
return transforms.Compose(
[
transforms.Resize(256 ),
transforms.CenterCrop(224 ),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.4677_7044, 0.4453_1429, 0.4066_1017] , std=[0.1222_1994, 0.1214_5835, 0.1438_0469] , ),
] )
| 27 |
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,
)
snake_case_ : Tuple = {
"configuration_albert": ["ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "AlbertConfig", "AlbertOnnxConfig"],
}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case_ : Dict = ["AlbertTokenizer"]
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case_ : Union[str, Any] = ["AlbertTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case_ : Union[str, Any] = [
"ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
"AlbertForMaskedLM",
"AlbertForMultipleChoice",
"AlbertForPreTraining",
"AlbertForQuestionAnswering",
"AlbertForSequenceClassification",
"AlbertForTokenClassification",
"AlbertModel",
"AlbertPreTrainedModel",
"load_tf_weights_in_albert",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case_ : List[Any] = [
"TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFAlbertForMaskedLM",
"TFAlbertForMultipleChoice",
"TFAlbertForPreTraining",
"TFAlbertForQuestionAnswering",
"TFAlbertForSequenceClassification",
"TFAlbertForTokenClassification",
"TFAlbertMainLayer",
"TFAlbertModel",
"TFAlbertPreTrainedModel",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case_ : Optional[Any] = [
"FlaxAlbertForMaskedLM",
"FlaxAlbertForMultipleChoice",
"FlaxAlbertForPreTraining",
"FlaxAlbertForQuestionAnswering",
"FlaxAlbertForSequenceClassification",
"FlaxAlbertForTokenClassification",
"FlaxAlbertModel",
"FlaxAlbertPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_albert import ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, AlbertOnnxConfig
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_albert import AlbertTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_albert_fast import AlbertTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_albert import (
ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
AlbertForMaskedLM,
AlbertForMultipleChoice,
AlbertForPreTraining,
AlbertForQuestionAnswering,
AlbertForSequenceClassification,
AlbertForTokenClassification,
AlbertModel,
AlbertPreTrainedModel,
load_tf_weights_in_albert,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_albert import (
TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFAlbertForMaskedLM,
TFAlbertForMultipleChoice,
TFAlbertForPreTraining,
TFAlbertForQuestionAnswering,
TFAlbertForSequenceClassification,
TFAlbertForTokenClassification,
TFAlbertMainLayer,
TFAlbertModel,
TFAlbertPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_albert import (
FlaxAlbertForMaskedLM,
FlaxAlbertForMultipleChoice,
FlaxAlbertForPreTraining,
FlaxAlbertForQuestionAnswering,
FlaxAlbertForSequenceClassification,
FlaxAlbertForTokenClassification,
FlaxAlbertModel,
FlaxAlbertPreTrainedModel,
)
else:
import sys
snake_case_ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 488 | 0 |
'''simple docstring'''
import os
import tempfile
import unittest
from transformers import DistilBertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, 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 (
DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
DistilBertForMaskedLM,
DistilBertForMultipleChoice,
DistilBertForQuestionAnswering,
DistilBertForSequenceClassification,
DistilBertForTokenClassification,
DistilBertModel,
)
class UpperCAmelCase ( UpperCAmelCase_):
"""simple docstring"""
def __init__( self : Any , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str]=13 , UpperCamelCase__ : int=7 , UpperCamelCase__ : int=True , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : str=False , UpperCamelCase__ : str=True , UpperCamelCase__ : Tuple=99 , UpperCamelCase__ : List[str]=32 , UpperCamelCase__ : Optional[int]=5 , UpperCamelCase__ : Union[str, Any]=4 , UpperCamelCase__ : int=37 , UpperCamelCase__ : Union[str, Any]="gelu" , UpperCamelCase__ : Tuple=0.1 , UpperCamelCase__ : Optional[int]=0.1 , UpperCamelCase__ : Union[str, Any]=512 , UpperCamelCase__ : Optional[Any]=16 , UpperCamelCase__ : List[str]=2 , UpperCamelCase__ : int=0.02 , UpperCamelCase__ : str=3 , UpperCamelCase__ : Optional[int]=4 , UpperCamelCase__ : Optional[int]=None , ) -> List[Any]:
_UpperCamelCase =parent
_UpperCamelCase =batch_size
_UpperCamelCase =seq_length
_UpperCamelCase =is_training
_UpperCamelCase =use_input_mask
_UpperCamelCase =use_token_type_ids
_UpperCamelCase =use_labels
_UpperCamelCase =vocab_size
_UpperCamelCase =hidden_size
_UpperCamelCase =num_hidden_layers
_UpperCamelCase =num_attention_heads
_UpperCamelCase =intermediate_size
_UpperCamelCase =hidden_act
_UpperCamelCase =hidden_dropout_prob
_UpperCamelCase =attention_probs_dropout_prob
_UpperCamelCase =max_position_embeddings
_UpperCamelCase =type_vocab_size
_UpperCamelCase =type_sequence_label_size
_UpperCamelCase =initializer_range
_UpperCamelCase =num_labels
_UpperCamelCase =num_choices
_UpperCamelCase =scope
def UpperCamelCase__ ( self : Dict ) -> List[Any]:
_UpperCamelCase =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
_UpperCamelCase =None
if self.use_input_mask:
_UpperCamelCase =random_attention_mask([self.batch_size, self.seq_length] )
_UpperCamelCase =None
_UpperCamelCase =None
_UpperCamelCase =None
if self.use_labels:
_UpperCamelCase =ids_tensor([self.batch_size] , self.type_sequence_label_size )
_UpperCamelCase =ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
_UpperCamelCase =ids_tensor([self.batch_size] , self.num_choices )
_UpperCamelCase =self.get_config()
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
def UpperCamelCase__ ( self : Any ) -> Optional[int]:
return DistilBertConfig(
vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , )
def UpperCamelCase__ ( self : Dict , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[int] ) -> Dict:
_UpperCamelCase =DistilBertModel(config=_lowercase )
model.to(_lowercase )
model.eval()
_UpperCamelCase =model(_lowercase , _lowercase )
_UpperCamelCase =model(_lowercase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def UpperCamelCase__ ( self : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : str , UpperCamelCase__ : List[str] , UpperCamelCase__ : Optional[int] ) -> Dict:
_UpperCamelCase =DistilBertForMaskedLM(config=_lowercase )
model.to(_lowercase )
model.eval()
_UpperCamelCase =model(_lowercase , attention_mask=_lowercase , labels=_lowercase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def UpperCamelCase__ ( self : Any , UpperCamelCase__ : str , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str] , UpperCamelCase__ : Optional[Any] ) -> List[Any]:
_UpperCamelCase =DistilBertForQuestionAnswering(config=_lowercase )
model.to(_lowercase )
model.eval()
_UpperCamelCase =model(
_lowercase , attention_mask=_lowercase , start_positions=_lowercase , end_positions=_lowercase )
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 UpperCamelCase__ ( self : Any , UpperCamelCase__ : List[str] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : int , UpperCamelCase__ : Dict ) -> Optional[int]:
_UpperCamelCase =self.num_labels
_UpperCamelCase =DistilBertForSequenceClassification(_lowercase )
model.to(_lowercase )
model.eval()
_UpperCamelCase =model(_lowercase , attention_mask=_lowercase , labels=_lowercase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def UpperCamelCase__ ( self : Optional[int] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : int , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str] ) -> int:
_UpperCamelCase =self.num_labels
_UpperCamelCase =DistilBertForTokenClassification(config=_lowercase )
model.to(_lowercase )
model.eval()
_UpperCamelCase =model(_lowercase , attention_mask=_lowercase , labels=_lowercase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def UpperCamelCase__ ( self : List[Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : Tuple , UpperCamelCase__ : Any , UpperCamelCase__ : Union[str, Any] ) -> Union[str, Any]:
_UpperCamelCase =self.num_choices
_UpperCamelCase =DistilBertForMultipleChoice(config=_lowercase )
model.to(_lowercase )
model.eval()
_UpperCamelCase =input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
_UpperCamelCase =input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
_UpperCamelCase =model(
_lowercase , attention_mask=_lowercase , labels=_lowercase , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def UpperCamelCase__ ( self : int ) -> Dict:
_UpperCamelCase =self.prepare_config_and_inputs()
((_UpperCamelCase) , (_UpperCamelCase) , (_UpperCamelCase) , (_UpperCamelCase) , (_UpperCamelCase) , (_UpperCamelCase)) =config_and_inputs
_UpperCamelCase ={'''input_ids''': input_ids, '''attention_mask''': input_mask}
return config, inputs_dict
@require_torch
class UpperCAmelCase ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase):
"""simple docstring"""
lowerCAmelCase_ = (
(
DistilBertModel,
DistilBertForMaskedLM,
DistilBertForMultipleChoice,
DistilBertForQuestionAnswering,
DistilBertForSequenceClassification,
DistilBertForTokenClassification,
)
if is_torch_available()
else None
)
lowerCAmelCase_ = (
{
"""feature-extraction""": DistilBertModel,
"""fill-mask""": DistilBertForMaskedLM,
"""question-answering""": DistilBertForQuestionAnswering,
"""text-classification""": DistilBertForSequenceClassification,
"""token-classification""": DistilBertForTokenClassification,
"""zero-shot""": DistilBertForSequenceClassification,
}
if is_torch_available()
else {}
)
lowerCAmelCase_ = True
lowerCAmelCase_ = True
lowerCAmelCase_ = True
lowerCAmelCase_ = True
def UpperCamelCase__ ( self : Dict ) -> Optional[Any]:
_UpperCamelCase =DistilBertModelTester(self )
_UpperCamelCase =ConfigTester(self , config_class=_lowercase , dim=37 )
def UpperCamelCase__ ( self : int ) -> Union[str, Any]:
self.config_tester.run_common_tests()
def UpperCamelCase__ ( self : List[Any] ) -> Any:
_UpperCamelCase =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_model(*_lowercase )
def UpperCamelCase__ ( self : str ) -> str:
_UpperCamelCase =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_masked_lm(*_lowercase )
def UpperCamelCase__ ( self : Any ) -> Optional[Any]:
_UpperCamelCase =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_question_answering(*_lowercase )
def UpperCamelCase__ ( self : int ) -> List[Any]:
_UpperCamelCase =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_sequence_classification(*_lowercase )
def UpperCamelCase__ ( self : str ) -> Optional[int]:
_UpperCamelCase =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_token_classification(*_lowercase )
def UpperCamelCase__ ( self : str ) -> List[Any]:
_UpperCamelCase =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_multiple_choice(*_lowercase )
@slow
def UpperCamelCase__ ( self : Tuple ) -> Tuple:
for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_UpperCamelCase =DistilBertModel.from_pretrained(_lowercase )
self.assertIsNotNone(_lowercase )
@slow
@require_torch_gpu
def UpperCamelCase__ ( self : Optional[int] ) -> Union[str, Any]:
_UpperCamelCase , _UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
# BertForMultipleChoice behaves incorrectly in JIT environments.
if model_class == DistilBertForMultipleChoice:
return
_UpperCamelCase =True
_UpperCamelCase =model_class(config=_lowercase )
_UpperCamelCase =self._prepare_for_class(_lowercase , _lowercase )
_UpperCamelCase =torch.jit.trace(
_lowercase , (inputs_dict['''input_ids'''].to('''cpu''' ), inputs_dict['''attention_mask'''].to('''cpu''' )) )
with tempfile.TemporaryDirectory() as tmp:
torch.jit.save(_lowercase , os.path.join(_lowercase , '''traced_model.pt''' ) )
_UpperCamelCase =torch.jit.load(os.path.join(_lowercase , '''traced_model.pt''' ) , map_location=_lowercase )
loaded(inputs_dict['''input_ids'''].to(_lowercase ) , inputs_dict['''attention_mask'''].to(_lowercase ) )
@require_torch
class UpperCAmelCase ( unittest.TestCase):
"""simple docstring"""
@slow
def UpperCamelCase__ ( self : int ) -> int:
_UpperCamelCase =DistilBertModel.from_pretrained('''distilbert-base-uncased''' )
_UpperCamelCase =torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] )
_UpperCamelCase =torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
with torch.no_grad():
_UpperCamelCase =model(_lowercase , attention_mask=_lowercase )[0]
_UpperCamelCase =torch.Size((1, 11, 768) )
self.assertEqual(output.shape , _lowercase )
_UpperCamelCase =torch.tensor(
[[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]] )
self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _lowercase , atol=1E-4 ) )
| 703 |
'''simple docstring'''
from __future__ import absolute_import, division, print_function, unicode_literals
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss
from transformers import RobertaConfig
from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.models.roberta.modeling_roberta import (
ROBERTA_INPUTS_DOCSTRING,
ROBERTA_START_DOCSTRING,
RobertaEmbeddings,
)
from .modeling_highway_bert import BertPreTrainedModel, DeeBertModel, HighwayException, entropy
@add_start_docstrings(
"""The RoBERTa Model transformer with early exiting (DeeRoBERTa). """ , lowercase_ , )
class UpperCAmelCase ( lowercase_):
"""simple docstring"""
lowerCAmelCase_ = RobertaConfig
lowerCAmelCase_ = """roberta"""
def __init__( self : Dict , UpperCamelCase__ : List[str] ) -> List[Any]:
super().__init__(UpperCamelCase__ )
_UpperCamelCase =RobertaEmbeddings(UpperCamelCase__ )
self.init_weights()
@add_start_docstrings(
"""RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top,
also takes care of multi-layer training. """ , lowercase_ , )
class UpperCAmelCase ( lowercase_):
"""simple docstring"""
lowerCAmelCase_ = RobertaConfig
lowerCAmelCase_ = """roberta"""
def __init__( self : Tuple , UpperCamelCase__ : Any ) -> Dict:
super().__init__(UpperCamelCase__ )
_UpperCamelCase =config.num_labels
_UpperCamelCase =config.num_hidden_layers
_UpperCamelCase =DeeRobertaModel(UpperCamelCase__ )
_UpperCamelCase =nn.Dropout(config.hidden_dropout_prob )
_UpperCamelCase =nn.Linear(config.hidden_size , self.config.num_labels )
@add_start_docstrings_to_model_forward(UpperCamelCase__ )
def UpperCamelCase__ ( self : List[Any] , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : List[str]=None , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : int=None , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : Tuple=None , UpperCamelCase__ : Union[str, Any]=-1 , UpperCamelCase__ : Dict=False , ) -> Union[str, Any]:
_UpperCamelCase =self.num_layers
try:
_UpperCamelCase =self.roberta(
UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , position_ids=UpperCamelCase__ , head_mask=UpperCamelCase__ , inputs_embeds=UpperCamelCase__ , )
_UpperCamelCase =outputs[1]
_UpperCamelCase =self.dropout(UpperCamelCase__ )
_UpperCamelCase =self.classifier(UpperCamelCase__ )
_UpperCamelCase =(logits,) + outputs[2:] # add hidden states and attention if they are here
except HighwayException as e:
_UpperCamelCase =e.message
_UpperCamelCase =e.exit_layer
_UpperCamelCase =outputs[0]
if not self.training:
_UpperCamelCase =entropy(UpperCamelCase__ )
_UpperCamelCase =[]
_UpperCamelCase =[]
if labels is not None:
if self.num_labels == 1:
# We are doing regression
_UpperCamelCase =MSELoss()
_UpperCamelCase =loss_fct(logits.view(-1 ) , labels.view(-1 ) )
else:
_UpperCamelCase =CrossEntropyLoss()
_UpperCamelCase =loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) )
# work with highway exits
_UpperCamelCase =[]
for highway_exit in outputs[-1]:
_UpperCamelCase =highway_exit[0]
if not self.training:
highway_logits_all.append(UpperCamelCase__ )
highway_entropy.append(highway_exit[2] )
if self.num_labels == 1:
# We are doing regression
_UpperCamelCase =MSELoss()
_UpperCamelCase =loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) )
else:
_UpperCamelCase =CrossEntropyLoss()
_UpperCamelCase =loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) )
highway_losses.append(UpperCamelCase__ )
if train_highway:
_UpperCamelCase =(sum(highway_losses[:-1] ),) + outputs
# exclude the final highway, of course
else:
_UpperCamelCase =(loss,) + outputs
if not self.training:
_UpperCamelCase =outputs + ((original_entropy, highway_entropy), exit_layer)
if output_layer >= 0:
_UpperCamelCase =(
(outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:]
) # use the highway of the last layer
return outputs # (loss), logits, (hidden_states), (attentions), entropy
| 271 | 0 |
import os
import pytest
import yaml
from datasets.features.features import Features, Value
from datasets.info import DatasetInfo, DatasetInfosDict
@pytest.mark.parametrize(
"""files""" , [
["""full:README.md""", """dataset_infos.json"""],
["""empty:README.md""", """dataset_infos.json"""],
["""dataset_infos.json"""],
["""full:README.md"""],
] , )
def __lowerCAmelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[Any] ) -> Tuple:
__lowerCAmelCase =tmp_path_factory.mktemp("""dset_infos_dir""" )
if "full:README.md" in files:
with open(dataset_infos_dir / """README.md""" , """w""" ) as f:
f.write("""---\ndataset_info:\n dataset_size: 42\n---""" )
if "empty:README.md" in files:
with open(dataset_infos_dir / """README.md""" , """w""" ) as f:
f.write("""""" )
# we want to support dataset_infos.json for backward compatibility
if "dataset_infos.json" in files:
with open(dataset_infos_dir / """dataset_infos.json""" , """w""" ) as f:
f.write("""{\"default\": {\"dataset_size\": 42}}""" )
__lowerCAmelCase =DatasetInfosDict.from_directory(__lowerCamelCase )
assert dataset_infos
assert dataset_infos["default"].dataset_size == 42
@pytest.mark.parametrize(
"""dataset_info""" , [
DatasetInfo(),
DatasetInfo(
description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=42 , ),
] , )
def __lowerCAmelCase ( __lowerCamelCase : Optional[int] , __lowerCamelCase : DatasetInfo ) -> Dict:
__lowerCAmelCase =str(__lowerCamelCase )
dataset_info.write_to_directory(__lowerCamelCase )
__lowerCAmelCase =DatasetInfo.from_directory(__lowerCamelCase )
assert dataset_info == reloaded
assert os.path.exists(os.path.join(__lowerCamelCase , """dataset_info.json""" ) )
def __lowerCAmelCase ( ) -> Optional[int]:
__lowerCAmelCase =DatasetInfo(
description="""foo""" , citation="""bar""" , homepage="""https://foo.bar""" , license="""CC0""" , features=Features({"""a""": Value("""int32""" )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train""", """num_examples""": 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , )
__lowerCAmelCase =dataset_info._to_yaml_dict()
assert sorted(__lowerCamelCase ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML )
for key in DatasetInfo._INCLUDED_INFO_IN_YAML:
assert key in dataset_info_yaml_dict
assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) )
__lowerCAmelCase =yaml.safe_dump(__lowerCamelCase )
__lowerCAmelCase =yaml.safe_load(__lowerCamelCase )
assert dataset_info_yaml_dict == reloaded
def __lowerCAmelCase ( ) -> Optional[int]:
__lowerCAmelCase =DatasetInfo()
__lowerCAmelCase =dataset_info._to_yaml_dict()
assert dataset_info_yaml_dict == {}
@pytest.mark.parametrize(
"""dataset_infos_dict""" , [
DatasetInfosDict(),
DatasetInfosDict({"""default""": DatasetInfo()} ),
DatasetInfosDict({"""my_config_name""": DatasetInfo()} ),
DatasetInfosDict(
{
"""default""": DatasetInfo(
description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=42 , )
} ),
DatasetInfosDict(
{
"""v1""": DatasetInfo(dataset_size=42 ),
"""v2""": DatasetInfo(dataset_size=1337 ),
} ),
] , )
def __lowerCAmelCase ( __lowerCamelCase : Any , __lowerCamelCase : DatasetInfosDict ) -> Dict:
__lowerCAmelCase =str(__lowerCamelCase )
dataset_infos_dict.write_to_directory(__lowerCamelCase )
__lowerCAmelCase =DatasetInfosDict.from_directory(__lowerCamelCase )
# the config_name of the dataset_infos_dict take over the attribute
for config_name, dataset_info in dataset_infos_dict.items():
__lowerCAmelCase =config_name
# the yaml representation doesn't include fields like description or citation
# so we just test that we can recover what we can from the yaml
__lowerCAmelCase =DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() )
assert dataset_infos_dict == reloaded
if dataset_infos_dict:
assert os.path.exists(os.path.join(__lowerCamelCase , """README.md""" ) )
| 354 |
import unittest
from transformers import is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_tf,
require_torch,
require_vision,
slow,
)
from .test_pipelines_common import ANY
if is_vision_available():
from PIL import Image
else:
class __a :
@staticmethod
def UpperCamelCase ( *snake_case_ : Any , **snake_case_ : str)-> int:
pass
@is_pipeline_test
@require_vision
class __a ( unittest.TestCase ):
@require_torch
def UpperCamelCase ( self : Dict)-> List[str]:
__lowerCAmelCase =pipeline(
model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification""" , )
__lowerCAmelCase =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
__lowerCAmelCase =image_classifier(snake_case_ , candidate_labels=["""a""", """b""", """c"""])
# The floating scores are so close, we enter floating error approximation and the order is not guaranteed across
# python and torch versions.
self.assertIn(
nested_simplify(snake_case_) , [
[{"""score""": 0.3_3_3, """label""": """a"""}, {"""score""": 0.3_3_3, """label""": """b"""}, {"""score""": 0.3_3_3, """label""": """c"""}],
[{"""score""": 0.3_3_3, """label""": """a"""}, {"""score""": 0.3_3_3, """label""": """c"""}, {"""score""": 0.3_3_3, """label""": """b"""}],
] , )
__lowerCAmelCase =image_classifier([image] * 5 , candidate_labels=["""A""", """B""", """C"""] , batch_size=2)
self.assertEqual(
nested_simplify(snake_case_) , [
[
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
],
[
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
],
[
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
],
[
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
],
[
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
],
] , )
@require_tf
def UpperCamelCase ( self : Dict)-> Optional[Any]:
__lowerCAmelCase =pipeline(
model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification""" , framework="""tf""")
__lowerCAmelCase =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
__lowerCAmelCase =image_classifier(snake_case_ , candidate_labels=["""a""", """b""", """c"""])
self.assertEqual(
nested_simplify(snake_case_) , [{"""score""": 0.3_3_3, """label""": """a"""}, {"""score""": 0.3_3_3, """label""": """b"""}, {"""score""": 0.3_3_3, """label""": """c"""}] , )
__lowerCAmelCase =image_classifier([image] * 5 , candidate_labels=["""A""", """B""", """C"""] , batch_size=2)
self.assertEqual(
nested_simplify(snake_case_) , [
[
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
],
[
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
],
[
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
],
[
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
],
[
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
{"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
],
] , )
@slow
@require_torch
def UpperCamelCase ( self : Any)-> Dict:
__lowerCAmelCase =pipeline(
task="""zero-shot-image-classification""" , model="""openai/clip-vit-base-patch32""" , )
# This is an image of 2 cats with remotes and no planes
__lowerCAmelCase =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
__lowerCAmelCase =image_classifier(snake_case_ , candidate_labels=["""cat""", """plane""", """remote"""])
self.assertEqual(
nested_simplify(snake_case_) , [
{"""score""": 0.5_1_1, """label""": """remote"""},
{"""score""": 0.4_8_5, """label""": """cat"""},
{"""score""": 0.0_0_4, """label""": """plane"""},
] , )
__lowerCAmelCase =image_classifier([image] * 5 , candidate_labels=["""cat""", """plane""", """remote"""] , batch_size=2)
self.assertEqual(
nested_simplify(snake_case_) , [
[
{"""score""": 0.5_1_1, """label""": """remote"""},
{"""score""": 0.4_8_5, """label""": """cat"""},
{"""score""": 0.0_0_4, """label""": """plane"""},
],
]
* 5 , )
@slow
@require_tf
def UpperCamelCase ( self : Optional[int])-> int:
__lowerCAmelCase =pipeline(
task="""zero-shot-image-classification""" , model="""openai/clip-vit-base-patch32""" , framework="""tf""")
# This is an image of 2 cats with remotes and no planes
__lowerCAmelCase =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
__lowerCAmelCase =image_classifier(snake_case_ , candidate_labels=["""cat""", """plane""", """remote"""])
self.assertEqual(
nested_simplify(snake_case_) , [
{"""score""": 0.5_1_1, """label""": """remote"""},
{"""score""": 0.4_8_5, """label""": """cat"""},
{"""score""": 0.0_0_4, """label""": """plane"""},
] , )
__lowerCAmelCase =image_classifier([image] * 5 , candidate_labels=["""cat""", """plane""", """remote"""] , batch_size=2)
self.assertEqual(
nested_simplify(snake_case_) , [
[
{"""score""": 0.5_1_1, """label""": """remote"""},
{"""score""": 0.4_8_5, """label""": """cat"""},
{"""score""": 0.0_0_4, """label""": """plane"""},
],
]
* 5 , )
| 354 | 1 |
"""simple docstring"""
import pprint
import requests
SCREAMING_SNAKE_CASE_ = '''https://zenquotes.io/api'''
def A__ ( ) -> list:
'''simple docstring'''
return requests.get(API_ENDPOINT_URL + "/today" ).json()
def A__ ( ) -> list:
'''simple docstring'''
return requests.get(API_ENDPOINT_URL + "/random" ).json()
if __name__ == "__main__":
SCREAMING_SNAKE_CASE_ = random_quotes()
pprint.pprint(response)
| 579 |
"""simple docstring"""
def A__ ( A__ ) -> str:
'''simple docstring'''
_UpperCAmelCase = ""
for ch in key:
if ch == " " or ch not in key_no_dups and ch.isalpha():
key_no_dups += ch
return key_no_dups
def A__ ( A__ ) -> dict[str, str]:
'''simple docstring'''
_UpperCAmelCase = [chr(i + 65 ) for i in range(26 )]
# Remove duplicate characters from key
_UpperCAmelCase = remove_duplicates(key.upper() )
_UpperCAmelCase = len(A__ )
# First fill cipher with key characters
_UpperCAmelCase = {alphabet[i]: char for i, char in enumerate(A__ )}
# Then map remaining characters in alphabet to
# the alphabet from the beginning
for i in range(len(A__ ) , 26 ):
_UpperCAmelCase = alphabet[i - offset]
# Ensure we are not mapping letters to letters previously mapped
while char in key:
offset -= 1
_UpperCAmelCase = alphabet[i - offset]
_UpperCAmelCase = char
return cipher_alphabet
def A__ ( A__ , A__ ) -> str:
'''simple docstring'''
return "".join(cipher_map.get(A__ , A__ ) for ch in message.upper() )
def A__ ( A__ , A__ ) -> str:
'''simple docstring'''
_UpperCAmelCase = {v: k for k, v in cipher_map.items()}
return "".join(rev_cipher_map.get(A__ , A__ ) for ch in message.upper() )
def A__ ( ) -> None:
'''simple docstring'''
_UpperCAmelCase = input("Enter message to encode or decode: " ).strip()
_UpperCAmelCase = input("Enter keyword: " ).strip()
_UpperCAmelCase = input("Encipher or decipher? E/D:" ).strip()[0].lower()
try:
_UpperCAmelCase = {"e": encipher, "d": decipher}[option]
except KeyError:
raise KeyError("invalid input option" )
_UpperCAmelCase = create_cipher_map(A__ )
print(func(A__ , A__ ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 579 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.