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 |
|---|---|---|---|---|
"""simple docstring"""
import argparse
import dataclasses
import json
import logging
import os
import shutil
from typing import List, Optional
import datasets
from accelerate import Accelerator
from datasets import load_dataset
from finetuning import finetune
from tqdm.auto import tqdm
import transformers
from transformers import AutoConfig, set_seed
from transformers.trainer_utils import IntervalStrategy
_SCREAMING_SNAKE_CASE = logging.getLogger(__name__)
_SCREAMING_SNAKE_CASE = """pytorch_model.bin"""
@dataclasses.dataclass
class __magic_name__ :
_SCREAMING_SNAKE_CASE : str = dataclasses.field(
metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models.'} )
_SCREAMING_SNAKE_CASE : Optional[str] = dataclasses.field(
default=lowercase__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co.'} , )
@dataclasses.dataclass
class __magic_name__ :
_SCREAMING_SNAKE_CASE : str = dataclasses.field(metadata={'help': 'A csv or a json file containing the training data.'} )
_SCREAMING_SNAKE_CASE : str = dataclasses.field(metadata={'help': 'A csv or a json file containing the data to predict on.'} )
_SCREAMING_SNAKE_CASE : Optional[str] = dataclasses.field(
default=lowercase__ , metadata={'help': 'A csv or a json file containing the validation data.'} )
_SCREAMING_SNAKE_CASE : Optional[str] = dataclasses.field(
default=lowercase__ , metadata={'help': 'The name of the task to train on.'} , )
_SCREAMING_SNAKE_CASE : Optional[List[str]] = dataclasses.field(
default=lowercase__ , metadata={'help': 'The list of labels for the task.'} )
@dataclasses.dataclass
class __magic_name__ :
_SCREAMING_SNAKE_CASE : str = dataclasses.field(
metadata={'help': 'The output directory where the model predictions and checkpoints will be written.'} )
_SCREAMING_SNAKE_CASE : Optional[str] = dataclasses.field(
default='accuracy' , metadata={'help': 'The evaluation metric used for the task.'} )
_SCREAMING_SNAKE_CASE : Optional[str] = dataclasses.field(
default='no' , metadata={
'help': 'The evaluation strategy to adopt during training. Possible values are: ["no", "step", "epoch]'
} , )
_SCREAMING_SNAKE_CASE : Optional[int] = dataclasses.field(
default=10 , metadata={'help': 'Number of evaluation calls with no improvement after which training will be stopped.'} , )
_SCREAMING_SNAKE_CASE : Optional[float] = dataclasses.field(
default=0.0 , metadata={
'help': 'How much the specified evaluation metric must improve to satisfy early stopping conditions.'
} , )
_SCREAMING_SNAKE_CASE : Optional[bool] = dataclasses.field(
default=lowercase__ , metadata={'help': 'Whether to filter the pseudo-labeled data based on the confidence score.'} , )
_SCREAMING_SNAKE_CASE : Optional[bool] = dataclasses.field(
default=lowercase__ , metadata={'help': 'Whether to filter the pseudo-labeled data based on the validation performance.'} , )
_SCREAMING_SNAKE_CASE : Optional[bool] = dataclasses.field(
default=lowercase__ , metadata={'help': 'Whether to fine-tune on labeled data after pseudo training.'} , )
_SCREAMING_SNAKE_CASE : Optional[float] = dataclasses.field(
default=0.0 , metadata={'help': 'Confidence threshold for pseudo-labeled data filtering.'} , )
_SCREAMING_SNAKE_CASE : Optional[int] = dataclasses.field(
default=100 , metadata={'help': 'Number of evaluation calls with no improvement after which training will be stopped.'} , )
_SCREAMING_SNAKE_CASE : Optional[int] = dataclasses.field(
default=lowercase__ , metadata={'help': 'Random seed for initialization.'} , )
def __UpperCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]:
"""simple docstring"""
__snake_case = datasets.concatenate_datasets([infer_input, infer_output] , axis=1 )
if args.do_filter_by_confidence:
__snake_case = dataset.filter(lambda SCREAMING_SNAKE_CASE : example["probability"] > args.confidence_threshold )
if args.do_filter_by_val_performance:
assert eval_result >= 0.0 and eval_result <= 1.0
__snake_case = int(eval_result * len(SCREAMING_SNAKE_CASE ) )
print(SCREAMING_SNAKE_CASE )
__snake_case = dataset.sort("probability" , reverse=SCREAMING_SNAKE_CASE )
__snake_case = dataset.select(range(SCREAMING_SNAKE_CASE ) )
__snake_case = dataset.remove_columns(["label", "probability"] )
__snake_case = dataset.rename_column("prediction" , "label" )
__snake_case = dataset.map(lambda SCREAMING_SNAKE_CASE : {"label": idalabel[example["label"]]} )
__snake_case = dataset.shuffle(seed=args.seed )
__snake_case = os.path.join(SCREAMING_SNAKE_CASE , F'''train_pseudo.{args.data_file_extension}''' )
if args.data_file_extension == "csv":
dataset.to_csv(SCREAMING_SNAKE_CASE , index=SCREAMING_SNAKE_CASE )
else:
dataset.to_json(SCREAMING_SNAKE_CASE )
def __UpperCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Optional[Any]:
"""simple docstring"""
__snake_case = 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 , )
logger.info(accelerator.state )
# 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()
__snake_case = STModelArguments(model_name_or_path=SCREAMING_SNAKE_CASE )
__snake_case = STDataArguments(train_file=SCREAMING_SNAKE_CASE , infer_file=SCREAMING_SNAKE_CASE )
__snake_case = STTrainingArguments(output_dir=SCREAMING_SNAKE_CASE )
__snake_case = argparse.Namespace()
for arg_class in (model_args, data_args, training_args):
for key, value in vars(SCREAMING_SNAKE_CASE ).items():
setattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
for key, value in kwargs.items():
if hasattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
setattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
# Sanity checks
__snake_case = {}
__snake_case = None
# You need to provide the training data and the data to predict on
assert args.train_file is not None
assert args.infer_file is not None
__snake_case = args.train_file
__snake_case = args.infer_file
if args.evaluation_strategy != IntervalStrategy.NO.value:
assert args.eval_file is not None
__snake_case = args.eval_file
for key in data_files:
__snake_case = data_files[key].split("." )[-1]
assert extension in ["csv", "json"], F'''`{key}_file` should be a csv or a json file.'''
if args.data_file_extension is None:
__snake_case = extension
else:
assert extension == args.data_file_extension, F'''`{key}_file` should be a {args.data_file_extension} file`.'''
assert (
args.eval_metric in datasets.list_metrics()
), F'''{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.'''
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed )
logger.info("Creating the initial data directory for self-training..." )
__snake_case = F'''{args.output_dir}/self-train_iter-{{}}'''.format
__snake_case = data_dir_format(0 )
if accelerator.is_main_process:
if args.output_dir is not None:
os.makedirs(args.output_dir , exist_ok=SCREAMING_SNAKE_CASE )
os.makedirs(SCREAMING_SNAKE_CASE , exist_ok=SCREAMING_SNAKE_CASE )
accelerator.wait_for_everyone()
__snake_case = None
__snake_case = None
__snake_case = 0
__snake_case = False
# Show the progress bar
__snake_case = tqdm(range(args.max_selftrain_iterations ) , disable=not accelerator.is_local_main_process )
# Self-train
for iteration in range(0 , int(args.max_selftrain_iterations ) ):
__snake_case = data_dir_format(SCREAMING_SNAKE_CASE )
assert os.path.exists(SCREAMING_SNAKE_CASE )
# Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for
# iteration > 0
__snake_case = os.path.join(SCREAMING_SNAKE_CASE , "stage-1" )
__snake_case = {
"accelerator": accelerator,
"model_name_or_path": args.model_name_or_path,
"cache_dir": args.cache_dir,
"do_train": True,
"train_file": data_files["train"] if iteration == 0 else data_files["train_pseudo"],
"do_eval": True if args.eval_file is not None else False,
"eval_file": data_files["eval"],
"do_predict": True,
"infer_file": data_files["infer"],
"task_name": args.task_name,
"label_list": args.label_list,
"output_dir": current_output_dir,
"eval_metric": args.eval_metric,
"evaluation_strategy": args.evaluation_strategy,
"early_stopping_patience": args.early_stopping_patience,
"early_stopping_threshold": args.early_stopping_threshold,
"seed": args.seed,
}
# Add additional training arguments
for key, value in kwargs.items():
if key not in arguments_dict and not hasattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
arguments_dict.update({key: value} )
__snake_case = os.path.join(SCREAMING_SNAKE_CASE , "best-checkpoint" , SCREAMING_SNAKE_CASE )
if os.path.exists(SCREAMING_SNAKE_CASE ):
logger.info(
"Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1." , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , )
else:
logger.info("***** Running self-training: iteration: %d, stage: 1 *****" , SCREAMING_SNAKE_CASE )
finetune(**SCREAMING_SNAKE_CASE )
accelerator.wait_for_everyone()
assert os.path.exists(SCREAMING_SNAKE_CASE )
logger.info("Self-training job completed: iteration: %d, stage: 1." , SCREAMING_SNAKE_CASE )
if iteration > 0 and args.finetune_on_labeled_data:
# Stage 2 (optional): fine-tuning on the original labeled data
__snake_case = os.path.join(SCREAMING_SNAKE_CASE , "best-checkpoint" )
__snake_case = os.path.join(SCREAMING_SNAKE_CASE , "stage-2" )
# Update arguments_dict
__snake_case = model_path
__snake_case = data_files["train"]
__snake_case = current_output_dir
__snake_case = os.path.join(SCREAMING_SNAKE_CASE , "best-checkpoint" , SCREAMING_SNAKE_CASE )
if os.path.exists(SCREAMING_SNAKE_CASE ):
logger.info(
"Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2." , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , )
else:
logger.info("***** Running self-training: iteration: %d, stage: 2 *****" , SCREAMING_SNAKE_CASE )
finetune(**SCREAMING_SNAKE_CASE )
accelerator.wait_for_everyone()
assert os.path.exists(SCREAMING_SNAKE_CASE )
logger.info("Self-training job completed: iteration: %d, stage: 2." , SCREAMING_SNAKE_CASE )
__snake_case = iteration
__snake_case = data_dir_format(iteration + 1 )
__snake_case = AutoConfig.from_pretrained(os.path.join(SCREAMING_SNAKE_CASE , "best-checkpoint" ) )
__snake_case = config.idalabel
__snake_case = os.path.join(SCREAMING_SNAKE_CASE , "eval_results_best-checkpoint.json" )
__snake_case = os.path.join(SCREAMING_SNAKE_CASE , "test_results_best-checkpoint.json" )
assert os.path.exists(SCREAMING_SNAKE_CASE )
with open(SCREAMING_SNAKE_CASE , "r" ) as f:
__snake_case = float(json.load(SCREAMING_SNAKE_CASE )[args.eval_metric] )
__snake_case = os.path.join(SCREAMING_SNAKE_CASE , "infer_output_best-checkpoint.csv" )
assert os.path.exists(SCREAMING_SNAKE_CASE )
# Loading the dataset from local csv or json files.
__snake_case = load_dataset(args.data_file_extension , data_files={"data": data_files["infer"]} )["data"]
__snake_case = load_dataset("csv" , data_files={"data": infer_output_file} )["data"]
if accelerator.is_main_process:
os.makedirs(SCREAMING_SNAKE_CASE , exist_ok=SCREAMING_SNAKE_CASE )
shutil.copy(SCREAMING_SNAKE_CASE , os.path.join(SCREAMING_SNAKE_CASE , F'''eval_results_iter-{iteration}.json''' ) )
if os.path.exists(SCREAMING_SNAKE_CASE ):
shutil.copy(SCREAMING_SNAKE_CASE , os.path.join(SCREAMING_SNAKE_CASE , F'''test_results_iter-{iteration}.json''' ) )
create_pseudo_labeled_data(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
accelerator.wait_for_everyone()
__snake_case = os.path.join(SCREAMING_SNAKE_CASE , F'''train_pseudo.{args.data_file_extension}''' )
if args.evaluation_strategy != IntervalStrategy.NO.value:
__snake_case = eval_result
if best_iteration is None:
__snake_case = new_iteration
__snake_case = new_eval_result
else:
if new_eval_result - best_eval_result > args.early_stopping_threshold:
__snake_case = new_iteration
__snake_case = new_eval_result
__snake_case = 0
else:
if new_eval_result == best_eval_result:
__snake_case = new_iteration
__snake_case = new_eval_result
early_stopping_patience_counter += 1
if early_stopping_patience_counter >= args.early_stopping_patience:
__snake_case = True
progress_bar.update(1 )
if should_training_stop:
break
if best_iteration is not None:
# Save the best iteration
logger.info("Best iteration: %d" , SCREAMING_SNAKE_CASE )
logger.info("Best evaluation result: %s = %f" , args.eval_metric , SCREAMING_SNAKE_CASE )
accelerator.wait_for_everyone()
if accelerator.is_main_process:
shutil.copy(
os.path.join(SCREAMING_SNAKE_CASE , F'''eval_results_iter-{iteration}.json''' ) , os.path.join(SCREAMING_SNAKE_CASE , "eval_results_best-iteration.json" ) , )
else:
# Assume that the last iteration is the best
logger.info("Best iteration: %d" , args.max_selftrain_iterations - 1 )
logger.info("Best evaluation result: %s = %f" , args.eval_metric , SCREAMING_SNAKE_CASE )
accelerator.wait_for_everyone()
if accelerator.is_main_process:
shutil.copy(
os.path.join(SCREAMING_SNAKE_CASE , F'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ) , os.path.join(SCREAMING_SNAKE_CASE , "eval_results_best-iteration.json" ) , )
| 163 |
"""simple docstring"""
import warnings
from ...utils import logging
from .image_processing_mobilevit import MobileViTImageProcessor
_SCREAMING_SNAKE_CASE = logging.get_logger(__name__)
class __magic_name__ ( lowercase__ ):
def __init__( self : int , *snake_case_ : Optional[Any] , **snake_case_ : Optional[Any] ):
warnings.warn(
"The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers."
" Please use MobileViTImageProcessor instead." , snake_case_ , )
super().__init__(*snake_case_ , **snake_case_ )
| 163 | 1 |
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 lowercase_ (lowerCamelCase__ , unittest.TestCase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : str = ShapEPipeline
SCREAMING_SNAKE_CASE : Optional[Any] = ['prompt']
SCREAMING_SNAKE_CASE : Tuple = ['prompt']
SCREAMING_SNAKE_CASE : int = [
'num_images_per_prompt',
'num_inference_steps',
'generator',
'latents',
'guidance_scale',
'frame_size',
'output_type',
'return_dict',
]
SCREAMING_SNAKE_CASE : Optional[int] = False
@property
def SCREAMING_SNAKE_CASE ( self : Tuple ):
return 3_2
@property
def SCREAMING_SNAKE_CASE ( self : str ):
return 3_2
@property
def SCREAMING_SNAKE_CASE ( self : Optional[int] ):
return self.time_input_dim * 4
@property
def SCREAMING_SNAKE_CASE ( self : List[Any] ):
return 8
@property
def SCREAMING_SNAKE_CASE ( self : Any ):
__lowercase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' )
return tokenizer
@property
def SCREAMING_SNAKE_CASE ( self : List[Any] ):
torch.manual_seed(0 )
__lowercase = 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=3_7 ,layer_norm_eps=1e-0_5 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1_0_0_0 ,)
return CLIPTextModelWithProjection(lowercase__ )
@property
def SCREAMING_SNAKE_CASE ( self : Optional[Any] ):
torch.manual_seed(0 )
__lowercase = {
'''num_attention_heads''': 2,
'''attention_head_dim''': 1_6,
'''embedding_dim''': self.time_input_dim,
'''num_embeddings''': 3_2,
'''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,
}
__lowercase = PriorTransformer(**lowercase__ )
return model
@property
def SCREAMING_SNAKE_CASE ( self : List[str] ):
torch.manual_seed(0 )
__lowercase = {
'''param_shapes''': (
(self.renderer_dim, 9_3),
(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''': 1_2,
'''background''': (
0.1,
0.1,
0.1,
),
}
__lowercase = ShapERenderer(**lowercase__ )
return model
def SCREAMING_SNAKE_CASE ( self : int ):
__lowercase = self.dummy_prior
__lowercase = self.dummy_text_encoder
__lowercase = self.dummy_tokenizer
__lowercase = self.dummy_renderer
__lowercase = HeunDiscreteScheduler(
beta_schedule='''exp''' ,num_train_timesteps=1_0_2_4 ,prediction_type='''sample''' ,use_karras_sigmas=lowercase__ ,clip_sample=lowercase__ ,clip_sample_range=1.0 ,)
__lowercase = {
'''prior''': prior,
'''text_encoder''': text_encoder,
'''tokenizer''': tokenizer,
'''renderer''': renderer,
'''scheduler''': scheduler,
}
return components
def SCREAMING_SNAKE_CASE ( self : Tuple ,lowercase__ : Tuple ,lowercase__ : Tuple=0 ):
if str(lowercase__ ).startswith('''mps''' ):
__lowercase = torch.manual_seed(lowercase__ )
else:
__lowercase = torch.Generator(device=lowercase__ ).manual_seed(lowercase__ )
__lowercase = {
'''prompt''': '''horse''',
'''generator''': generator,
'''num_inference_steps''': 1,
'''frame_size''': 3_2,
'''output_type''': '''np''',
}
return inputs
def SCREAMING_SNAKE_CASE ( self : List[Any] ):
__lowercase = '''cpu'''
__lowercase = self.get_dummy_components()
__lowercase = self.pipeline_class(**lowercase__ )
__lowercase = pipe.to(lowercase__ )
pipe.set_progress_bar_config(disable=lowercase__ )
__lowercase = pipe(**self.get_dummy_inputs(lowercase__ ) )
__lowercase = output.images[0]
__lowercase = image[0, -3:, -3:, -1]
assert image.shape == (2_0, 3_2, 3_2, 3)
__lowercase = np.array(
[
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def SCREAMING_SNAKE_CASE ( self : str ):
# NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
self._test_inference_batch_consistent(batch_sizes=[1, 2] )
def SCREAMING_SNAKE_CASE ( self : Dict ):
__lowercase = torch_device == '''cpu'''
__lowercase = True
self._test_inference_batch_single_identical(
batch_size=2 ,test_max_difference=lowercase__ ,relax_max_difference=lowercase__ ,)
def SCREAMING_SNAKE_CASE ( self : Optional[int] ):
__lowercase = self.get_dummy_components()
__lowercase = self.pipeline_class(**lowercase__ )
__lowercase = pipe.to(lowercase__ )
pipe.set_progress_bar_config(disable=lowercase__ )
__lowercase = 1
__lowercase = 2
__lowercase = self.get_dummy_inputs(lowercase__ )
for key in inputs.keys():
if key in self.batch_params:
__lowercase = batch_size * [inputs[key]]
__lowercase = pipe(**lowercase__ ,num_images_per_prompt=lowercase__ )[0]
assert images.shape[0] == batch_size * num_images_per_prompt
@slow
@require_torch_gpu
class lowercase_ (unittest.TestCase ):
"""simple docstring"""
def SCREAMING_SNAKE_CASE ( self : int ):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def SCREAMING_SNAKE_CASE ( self : int ):
__lowercase = load_numpy(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/shap_e/test_shap_e_np_out.npy''' )
__lowercase = ShapEPipeline.from_pretrained('''openai/shap-e''' )
__lowercase = pipe.to(lowercase__ )
pipe.set_progress_bar_config(disable=lowercase__ )
__lowercase = torch.Generator(device=lowercase__ ).manual_seed(0 )
__lowercase = pipe(
'''a shark''' ,generator=lowercase__ ,guidance_scale=1_5.0 ,num_inference_steps=6_4 ,frame_size=6_4 ,output_type='''np''' ,).images[0]
assert images.shape == (2_0, 6_4, 6_4, 3)
assert_mean_pixel_difference(lowercase__ ,lowercase__ )
| 710 |
'''simple docstring'''
import glob
import os
import random
from string import ascii_lowercase, digits
import cva
import numpy as np
# Parrameters
lowerCAmelCase__ = (720, 1280) # Height, Width
lowerCAmelCase__ = (0.4, 0.6) # if height or width lower than this scale, drop it.
lowerCAmelCase__ = 1 / 100
lowerCAmelCase__ = ''''''
lowerCAmelCase__ = ''''''
lowerCAmelCase__ = ''''''
lowerCAmelCase__ = 250
def _A ( ):
"""simple docstring"""
__lowercase , __lowercase = get_dataset(A__ , A__ )
for index in range(A__ ):
__lowercase = random.sample(range(len(A__ ) ) , 4 )
__lowercase , __lowercase , __lowercase = update_image_and_anno(
A__ , A__ , A__ , A__ , A__ , filter_scale=A__ , )
# Get random string code: '7b7ad245cdff75241935e4dd860f3bad'
__lowercase = random_chars(32 )
__lowercase = path.split(os.sep )[-1].rsplit('''.''' , 1 )[0]
__lowercase = F"{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}"
cva.imwrite(F"{file_root}.jpg" , A__ , [cva.IMWRITE_JPEG_QUALITY, 85] )
print(F"Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}" )
__lowercase = []
for anno in new_annos:
__lowercase = anno[3] - anno[1]
__lowercase = anno[4] - anno[2]
__lowercase = anno[1] + width / 2
__lowercase = anno[2] + height / 2
__lowercase = F"{anno[0]} {x_center} {y_center} {width} {height}"
annos_list.append(A__ )
with open(F"{file_root}.txt" , '''w''' ) as outfile:
outfile.write('''\n'''.join(line for line in annos_list ) )
def _A ( A__ , A__ ):
"""simple docstring"""
__lowercase = []
__lowercase = []
for label_file in glob.glob(os.path.join(A__ , '''*.txt''' ) ):
__lowercase = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0]
with open(A__ ) as in_file:
__lowercase = in_file.readlines()
__lowercase = os.path.join(A__ , F"{label_name}.jpg" )
__lowercase = []
for obj_list in obj_lists:
__lowercase = obj_list.rstrip('''\n''' ).split(''' ''' )
__lowercase = float(obj[1] ) - float(obj[3] ) / 2
__lowercase = float(obj[2] ) - float(obj[4] ) / 2
__lowercase = float(obj[1] ) + float(obj[3] ) / 2
__lowercase = float(obj[2] ) + float(obj[4] ) / 2
boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] )
if not boxes:
continue
img_paths.append(A__ )
labels.append(A__ )
return img_paths, labels
def _A ( A__ , A__ , A__ , A__ , A__ , A__ = 0.0 , ):
"""simple docstring"""
__lowercase = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta )
__lowercase = scale_range[0] + random.random() * (scale_range[1] - scale_range[0])
__lowercase = scale_range[0] + random.random() * (scale_range[1] - scale_range[0])
__lowercase = int(scale_x * output_size[1] )
__lowercase = int(scale_y * output_size[0] )
__lowercase = []
__lowercase = []
for i, index in enumerate(A__ ):
__lowercase = all_img_list[index]
path_list.append(A__ )
__lowercase = all_annos[index]
__lowercase = cva.imread(A__ )
if i == 0: # top-left
__lowercase = cva.resize(A__ , (divid_point_x, divid_point_y) )
__lowercase = img
for bbox in img_annos:
__lowercase = bbox[1] * scale_x
__lowercase = bbox[2] * scale_y
__lowercase = bbox[3] * scale_x
__lowercase = bbox[4] * scale_y
new_anno.append([bbox[0], xmin, ymin, xmax, ymax] )
elif i == 1: # top-right
__lowercase = cva.resize(A__ , (output_size[1] - divid_point_x, divid_point_y) )
__lowercase = img
for bbox in img_annos:
__lowercase = scale_x + bbox[1] * (1 - scale_x)
__lowercase = bbox[2] * scale_y
__lowercase = scale_x + bbox[3] * (1 - scale_x)
__lowercase = bbox[4] * scale_y
new_anno.append([bbox[0], xmin, ymin, xmax, ymax] )
elif i == 2: # bottom-left
__lowercase = cva.resize(A__ , (divid_point_x, output_size[0] - divid_point_y) )
__lowercase = img
for bbox in img_annos:
__lowercase = bbox[1] * scale_x
__lowercase = scale_y + bbox[2] * (1 - scale_y)
__lowercase = bbox[3] * scale_x
__lowercase = scale_y + bbox[4] * (1 - scale_y)
new_anno.append([bbox[0], xmin, ymin, xmax, ymax] )
else: # bottom-right
__lowercase = cva.resize(
A__ , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) )
__lowercase = img
for bbox in img_annos:
__lowercase = scale_x + bbox[1] * (1 - scale_x)
__lowercase = scale_y + bbox[2] * (1 - scale_y)
__lowercase = scale_x + bbox[3] * (1 - scale_x)
__lowercase = 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:
__lowercase = [
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 _A ( A__ ):
"""simple docstring"""
assert number_char > 1, "The number of character should greater than 1"
__lowercase = ascii_lowercase + digits
return "".join(random.choice(A__ ) for _ in range(A__ ) )
if __name__ == "__main__":
main()
print('''DONE ✅''')
| 624 | 0 |
'''simple docstring'''
import inspect
import warnings
from typing import Any, Dict, Optional, Union
from packaging import version
def UpperCamelCase__ ( *__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=2 ) -> Any:
from .. import __version__
snake_case__ : Optional[Any] = take_from
snake_case__ : Optional[int] = ()
if not isinstance(args[0] , __SCREAMING_SNAKE_CASE ):
snake_case__ : Any = (args,)
for attribute, version_name, message in args:
if version.parse(version.parse(__SCREAMING_SNAKE_CASE ).base_version ) >= version.parse(__SCREAMING_SNAKE_CASE ):
raise ValueError(
f"The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers'"
f" version {__version__} is >= {version_name}" )
snake_case__ : Optional[Any] = None
if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and attribute in deprecated_kwargs:
values += (deprecated_kwargs.pop(__SCREAMING_SNAKE_CASE ),)
snake_case__ : List[str] = f"The `{attribute}` argument is deprecated and will be removed in version {version_name}."
elif hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
values += (getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ),)
snake_case__ : Dict = f"The `{attribute}` attribute is deprecated and will be removed in version {version_name}."
elif deprecated_kwargs is None:
snake_case__ : List[str] = f"`{attribute}` is deprecated and will be removed in version {version_name}."
if warning is not None:
snake_case__ : Tuple = warning + ' ' if standard_warn else ''
warnings.warn(warning + message , __SCREAMING_SNAKE_CASE , stacklevel=__SCREAMING_SNAKE_CASE )
if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and len(__SCREAMING_SNAKE_CASE ) > 0:
snake_case__ : Optional[Any] = inspect.getouterframes(inspect.currentframe() )[1]
snake_case__ : Dict = call_frame.filename
snake_case__ : Optional[Any] = call_frame.lineno
snake_case__ : int = call_frame.function
snake_case__ , snake_case__ : List[str] = next(iter(deprecated_kwargs.items() ) )
raise TypeError(f"{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`" )
if len(__SCREAMING_SNAKE_CASE ) == 0:
return
elif len(__SCREAMING_SNAKE_CASE ) == 1:
return values[0]
return values
| 270 |
'''simple docstring'''
from typing import Dict, List, Optional, Union
import numpy as np
from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin
from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy
A_ = logging.get_logger(__name__)
class lowercase_ ( lowerCAmelCase_ ):
def __init__( self : Union[str, Any] , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : float , **__lowerCamelCase : Optional[int] ):
snake_case__ : int = feature_size
snake_case__ : List[str] = sampling_rate
snake_case__ : Any = padding_value
snake_case__ : Union[str, Any] = kwargs.pop('padding_side' , 'right' )
snake_case__ : List[Any] = kwargs.pop('return_attention_mask' , __lowerCamelCase )
super().__init__(**__lowerCamelCase )
def _lowerCAmelCase ( self : Dict , __lowerCamelCase : Union[
BatchFeature,
List[BatchFeature],
Dict[str, BatchFeature],
Dict[str, List[BatchFeature]],
List[Dict[str, BatchFeature]],
] , __lowerCamelCase : Union[bool, str, PaddingStrategy] = True , __lowerCamelCase : Optional[int] = None , __lowerCamelCase : bool = False , __lowerCamelCase : Optional[int] = None , __lowerCamelCase : Optional[bool] = None , __lowerCamelCase : Optional[Union[str, TensorType]] = None , ):
# If we have a list of dicts, let's convert it in a dict of lists
# We do this to allow using this method as a collate_fn function in PyTorch Dataloader
if isinstance(__lowerCamelCase , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ):
snake_case__ : int = {
key: [example[key] for example in processed_features] for key in processed_features[0].keys()
}
# The model's main input name, usually `input_values`, has be passed for padding
if self.model_input_names[0] not in processed_features:
raise ValueError(
'You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`'
F" to this method that includes {self.model_input_names[0]}, but you provided"
F" {list(processed_features.keys() )}" )
snake_case__ : Tuple = processed_features[self.model_input_names[0]]
snake_case__ : Union[str, Any] = (
return_attention_mask if return_attention_mask is not None else self.return_attention_mask
)
if len(__lowerCamelCase ) == 0:
if return_attention_mask:
snake_case__ : str = []
return processed_features
# If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays
# and rebuild them afterwards if no return_tensors is specified
# Note that we lose the specific device the tensor may be on for PyTorch
snake_case__ : Dict = required_input[0]
if isinstance(__lowerCamelCase , (list, tuple) ):
# first_element might be an empty list/tuple in some edge cases so we grab the first non empty element.
snake_case__ : List[Any] = 0
while len(required_input[index] ) == 0:
index += 1
if index < len(__lowerCamelCase ):
snake_case__ : List[Any] = required_input[index][0]
if return_tensors is None:
if is_tf_tensor(__lowerCamelCase ):
snake_case__ : int = 'tf'
elif is_torch_tensor(__lowerCamelCase ):
snake_case__ : str = 'pt'
elif isinstance(__lowerCamelCase , (int, float, list, tuple, np.ndarray) ):
snake_case__ : Any = 'np'
else:
raise ValueError(
F"type of {first_element} unknown: {type(__lowerCamelCase )}. "
'Should be one of a python, numpy, pytorch or tensorflow object.' )
for key, value in processed_features.items():
if isinstance(value[0] , (int, float) ):
snake_case__ : List[Any] = to_numpy(__lowerCamelCase )
else:
snake_case__ : List[str] = [to_numpy(__lowerCamelCase ) for v in value]
# Convert padding_strategy in PaddingStrategy
snake_case__ : str = self._get_padding_strategies(padding=__lowerCamelCase , max_length=__lowerCamelCase )
snake_case__ : List[Any] = processed_features[self.model_input_names[0]]
snake_case__ : Tuple = len(__lowerCamelCase )
if not all(len(__lowerCamelCase ) == batch_size for v in processed_features.values() ):
raise ValueError('Some items in the output dictionary have a different batch size than others.' )
snake_case__ : str = []
for i in range(__lowerCamelCase ):
snake_case__ : str = {k: v[i] for k, v in processed_features.items()}
# truncation
snake_case__ : Optional[Any] = self._truncate(
__lowerCamelCase , max_length=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , truncation=__lowerCamelCase , )
truncated_inputs.append(__lowerCamelCase )
if padding_strategy == PaddingStrategy.LONGEST:
# make sure that `max_length` cannot be longer than the longest truncated length
snake_case__ : Any = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs )
snake_case__ : Union[str, Any] = PaddingStrategy.MAX_LENGTH
snake_case__ : List[Any] = {}
for i in range(__lowerCamelCase ):
# padding
snake_case__ : Tuple = self._pad(
truncated_inputs[i] , max_length=__lowerCamelCase , padding_strategy=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , )
for key, value in outputs.items():
if key not in batch_outputs:
snake_case__ : Union[str, Any] = []
if value.dtype is np.dtype(np.floataa ):
snake_case__ : int = value.astype(np.floataa )
batch_outputs[key].append(__lowerCamelCase )
return BatchFeature(__lowerCamelCase , tensor_type=__lowerCamelCase )
def _lowerCAmelCase ( self : Optional[int] , __lowerCamelCase : Union[Dict[str, np.ndarray], BatchFeature] , __lowerCamelCase : Optional[int] = None , __lowerCamelCase : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , __lowerCamelCase : Optional[int] = None , __lowerCamelCase : Optional[bool] = None , ):
snake_case__ : Optional[int] = processed_features[self.model_input_names[0]]
if padding_strategy == PaddingStrategy.LONGEST:
snake_case__ : Tuple = len(__lowerCamelCase )
if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
snake_case__ : Dict = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
snake_case__ : List[str] = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(__lowerCamelCase ) < max_length
if return_attention_mask and "attention_mask" not in processed_features:
snake_case__ : Optional[int] = np.ones(len(__lowerCamelCase ) , dtype=np.intaa )
if needs_to_be_padded:
snake_case__ : List[Any] = max_length - len(__lowerCamelCase )
if self.padding_side == "right":
if return_attention_mask:
snake_case__ : List[str] = np.pad(
processed_features['attention_mask'] , (0, difference) )
snake_case__ : List[Any] = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference)
snake_case__ : int = np.pad(
__lowerCamelCase , __lowerCamelCase , 'constant' , constant_values=self.padding_value )
elif self.padding_side == "left":
if return_attention_mask:
snake_case__ : str = np.pad(
processed_features['attention_mask'] , (difference, 0) )
snake_case__ : int = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0)
snake_case__ : int = np.pad(
__lowerCamelCase , __lowerCamelCase , 'constant' , constant_values=self.padding_value )
else:
raise ValueError('Invalid padding strategy:' + str(self.padding_side ) )
return processed_features
def _lowerCAmelCase ( self : int , __lowerCamelCase : Union[Dict[str, np.ndarray], BatchFeature] , __lowerCamelCase : Optional[int] = None , __lowerCamelCase : Optional[int] = None , __lowerCamelCase : Optional[bool] = None , ):
if not truncation:
return processed_features
elif truncation and max_length is None:
raise ValueError('When setting ``truncation=True``, make sure that ``max_length`` is defined.' )
snake_case__ : Optional[int] = processed_features[self.model_input_names[0]]
# find `max_length` that fits `pad_to_multiple_of`
if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
snake_case__ : List[str] = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
snake_case__ : str = len(__lowerCamelCase ) > max_length
if needs_to_be_truncated:
snake_case__ : Optional[int] = processed_features[self.model_input_names[0]][:max_length]
if "attention_mask" in processed_features:
snake_case__ : List[Any] = processed_features['attention_mask'][:max_length]
return processed_features
def _lowerCAmelCase ( self : Dict , __lowerCamelCase : Optional[int]=False , __lowerCamelCase : Optional[Any]=None ):
# Get padding strategy
if padding is not False:
if padding is True:
snake_case__ : int = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch
elif not isinstance(__lowerCamelCase , __lowerCamelCase ):
snake_case__ : str = PaddingStrategy(__lowerCamelCase )
elif isinstance(__lowerCamelCase , __lowerCamelCase ):
snake_case__ : str = padding
else:
snake_case__ : Union[str, Any] = PaddingStrategy.DO_NOT_PAD
# Set max length if needed
if max_length is None:
if padding_strategy == PaddingStrategy.MAX_LENGTH:
raise ValueError(
F"When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined" )
# Test if we have a padding value
if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None):
raise ValueError(
'Asking to pad but the feature_extractor does not have a padding value. Please select a value to use'
' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.' )
return padding_strategy
| 270 | 1 |
import sys
__a: List[str] = (
'''73167176531330624919225119674426574742355349194934'''
'''96983520312774506326239578318016984801869478851843'''
'''85861560789112949495459501737958331952853208805511'''
'''12540698747158523863050715693290963295227443043557'''
'''66896648950445244523161731856403098711121722383113'''
'''62229893423380308135336276614282806444486645238749'''
'''30358907296290491560440772390713810515859307960866'''
'''70172427121883998797908792274921901699720888093776'''
'''65727333001053367881220235421809751254540594752243'''
'''52584907711670556013604839586446706324415722155397'''
'''53697817977846174064955149290862569321978468622482'''
'''83972241375657056057490261407972968652414535100474'''
'''82166370484403199890008895243450658541227588666881'''
'''16427171479924442928230863465674813919123162824586'''
'''17866458359124566529476545682848912883142607690042'''
'''24219022671055626321111109370544217506941658960408'''
'''07198403850962455444362981230987879927244284909188'''
'''84580156166097919133875499200524063689912560717606'''
'''05886116467109405077541002256983155200055935729725'''
'''71636269561882670428252483600823257530420752963450'''
)
def _SCREAMING_SNAKE_CASE ( __snake_case ) -> int:
_UpperCAmelCase = 1
for digit in s:
product *= int(__snake_case )
return product
def _SCREAMING_SNAKE_CASE ( __snake_case = N ) -> int:
_UpperCAmelCase = -sys.maxsize - 1
_UpperCAmelCase = n[:1_3]
_UpperCAmelCase = 1_3
while cur_index < len(__snake_case ) - 1_3:
if int(n[cur_index] ) >= int(substr[0] ):
_UpperCAmelCase = substr[1:] + n[cur_index]
cur_index += 1
else:
_UpperCAmelCase = max(__snake_case , str_eval(__snake_case ) )
_UpperCAmelCase = n[cur_index : cur_index + 1_3]
cur_index += 1_3
return largest_product
if __name__ == "__main__":
print(F"{solution() = }") | 402 |
def _SCREAMING_SNAKE_CASE ( __snake_case ) -> list[int]:
_UpperCAmelCase = [0 for i in range(len(__snake_case ) )]
# initialize interval's left pointer and right pointer
_UpperCAmelCase , _UpperCAmelCase = 0, 0
for i in range(1 , len(__snake_case ) ):
# case when current index is inside the interval
if i <= right_pointer:
_UpperCAmelCase = min(right_pointer - i + 1 , z_result[i - left_pointer] )
_UpperCAmelCase = min_edge
while go_next(__snake_case , __snake_case , __snake_case ):
z_result[i] += 1
# if new index's result gives us more right interval,
# we've to update left_pointer and right_pointer
if i + z_result[i] - 1 > right_pointer:
_UpperCAmelCase , _UpperCAmelCase = i, i + z_result[i] - 1
return z_result
def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case ) -> bool:
return i + z_result[i] < len(__snake_case ) and s[z_result[i]] == s[i + z_result[i]]
def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ) -> int:
_UpperCAmelCase = 0
# concatenate 'pattern' and 'input_str' and call z_function
# with concatenated string
_UpperCAmelCase = z_function(pattern + input_str )
for val in z_result:
# if value is greater then length of the pattern string
# that means this index is starting position of substring
# which is equal to pattern string
if val >= len(__snake_case ):
answer += 1
return answer
if __name__ == "__main__":
import doctest
doctest.testmod() | 402 | 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_mvp import MvpTokenizer
lowerCAmelCase : List[str] = logging.get_logger(__name__)
lowerCAmelCase : int = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'}
# See all MVP models at https://huggingface.co/models?filter=mvp
lowerCAmelCase : int = {
'vocab_file': {
'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json',
},
'added_tokens.json': {
'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json',
},
'merges_file': {
'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt',
},
'tokenizer_file': {
'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/tokenizer.json',
},
}
lowerCAmelCase : str = {
'RUCAIBox/mvp': 10_24,
}
class _A ( __magic_name__):
SCREAMING_SNAKE_CASE : Optional[Any] = VOCAB_FILES_NAMES
SCREAMING_SNAKE_CASE : Optional[int] = PRETRAINED_VOCAB_FILES_MAP
SCREAMING_SNAKE_CASE : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
SCREAMING_SNAKE_CASE : Tuple = ['''input_ids''', '''attention_mask''']
SCREAMING_SNAKE_CASE : Union[str, Any] = MvpTokenizer
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 , ):
"""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 , )
SCREAMING_SNAKE_CASE_ : List[str] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
if pre_tok_state.get('add_prefix_space' , _SCREAMING_SNAKE_CASE ) != add_prefix_space:
SCREAMING_SNAKE_CASE_ : int = getattr(_SCREAMING_SNAKE_CASE , pre_tok_state.pop('type' ) )
SCREAMING_SNAKE_CASE_ : Dict = add_prefix_space
SCREAMING_SNAKE_CASE_ : int = pre_tok_class(**_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ : Dict = add_prefix_space
# the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
SCREAMING_SNAKE_CASE_ : str = 'post_processor'
SCREAMING_SNAKE_CASE_ : List[str] = getattr(self.backend_tokenizer , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if tokenizer_component_instance:
SCREAMING_SNAKE_CASE_ : List[Any] = 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:
SCREAMING_SNAKE_CASE_ : Optional[Any] = tuple(state['sep'] )
if "cls" in state:
SCREAMING_SNAKE_CASE_ : Any = tuple(state['cls'] )
SCREAMING_SNAKE_CASE_ : str = False
if state.get('add_prefix_space' , _SCREAMING_SNAKE_CASE ) != add_prefix_space:
SCREAMING_SNAKE_CASE_ : Optional[Any] = add_prefix_space
SCREAMING_SNAKE_CASE_ : Any = True
if state.get('trim_offsets' , _SCREAMING_SNAKE_CASE ) != trim_offsets:
SCREAMING_SNAKE_CASE_ : Optional[Any] = trim_offsets
SCREAMING_SNAKE_CASE_ : Tuple = True
if changes_to_apply:
SCREAMING_SNAKE_CASE_ : Tuple = getattr(_SCREAMING_SNAKE_CASE , state.pop('type' ) )
SCREAMING_SNAKE_CASE_ : Dict = component_class(**_SCREAMING_SNAKE_CASE )
setattr(self.backend_tokenizer , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
@property
def UpperCAmelCase ( self ):
"""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 UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Any = AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else value
SCREAMING_SNAKE_CASE_ : Tuple = value
def UpperCAmelCase ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Optional[int] = kwargs.get('is_split_into_words' , _SCREAMING_SNAKE_CASE )
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
'to use it with pretokenized inputs.' )
return super()._batch_encode_plus(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
def UpperCAmelCase ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Any = 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 UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Dict = self._tokenizer.model.save(_SCREAMING_SNAKE_CASE , name=_SCREAMING_SNAKE_CASE )
return tuple(_SCREAMING_SNAKE_CASE )
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Optional[int] = [self.bos_token_id] + token_ids_a + [self.eos_token_id]
if token_ids_a is None:
return output
return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : List[Any] = [self.sep_token_id]
SCREAMING_SNAKE_CASE_ : Union[str, Any] = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
| 511 |
import argparse
import torch
from transformers import GPTaLMHeadModel, RobertaForMaskedLM
if __name__ == "__main__":
lowerCAmelCase : Optional[int] = argparse.ArgumentParser(
description=(
'Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel for Transfer Learned'
' Distillation'
)
)
parser.add_argument('--model_type', default='roberta', choices=['roberta', 'gpt2'])
parser.add_argument('--model_name', default='roberta-large', type=str)
parser.add_argument('--dump_checkpoint', default='serialization_dir/tf_roberta_048131723.pth', type=str)
parser.add_argument('--vocab_transform', action='store_true')
lowerCAmelCase : Union[str, Any] = parser.parse_args()
if args.model_type == "roberta":
lowerCAmelCase : Optional[Any] = RobertaForMaskedLM.from_pretrained(args.model_name)
lowerCAmelCase : Dict = 'roberta'
elif args.model_type == "gpt2":
lowerCAmelCase : List[Any] = GPTaLMHeadModel.from_pretrained(args.model_name)
lowerCAmelCase : Union[str, Any] = 'transformer'
lowerCAmelCase : int = model.state_dict()
lowerCAmelCase : Tuple = {}
# Embeddings #
if args.model_type == "gpt2":
for param_name in ["wte.weight", "wpe.weight"]:
lowerCAmelCase : Union[str, Any] = state_dict[F'{prefix}.{param_name}']
else:
for w in ["word_embeddings", "position_embeddings", "token_type_embeddings"]:
lowerCAmelCase : Any = F'{prefix}.embeddings.{w}.weight'
lowerCAmelCase : Optional[int] = state_dict[param_name]
for w in ["weight", "bias"]:
lowerCAmelCase : Optional[Any] = F'{prefix}.embeddings.LayerNorm.{w}'
lowerCAmelCase : str = state_dict[param_name]
# Transformer Blocks #
lowerCAmelCase : List[Any] = 0
for teacher_idx in [0, 2, 4, 7, 9, 11]:
if args.model_type == "gpt2":
for layer in ["ln_1", "attn.c_attn", "attn.c_proj", "ln_2", "mlp.c_fc", "mlp.c_proj"]:
for w in ["weight", "bias"]:
lowerCAmelCase : List[str] = state_dict[
F'{prefix}.h.{teacher_idx}.{layer}.{w}'
]
lowerCAmelCase : Union[str, Any] = state_dict[F'{prefix}.h.{teacher_idx}.attn.bias']
else:
for layer in [
"attention.self.query",
"attention.self.key",
"attention.self.value",
"attention.output.dense",
"attention.output.LayerNorm",
"intermediate.dense",
"output.dense",
"output.LayerNorm",
]:
for w in ["weight", "bias"]:
lowerCAmelCase : Union[str, Any] = state_dict[
F'{prefix}.encoder.layer.{teacher_idx}.{layer}.{w}'
]
std_idx += 1
# Language Modeling Head ###s
if args.model_type == "roberta":
for layer in ["lm_head.decoder.weight", "lm_head.bias"]:
lowerCAmelCase : Union[str, Any] = state_dict[F'{layer}']
if args.vocab_transform:
for w in ["weight", "bias"]:
lowerCAmelCase : Union[str, Any] = state_dict[F'lm_head.dense.{w}']
lowerCAmelCase : List[str] = state_dict[F'lm_head.layer_norm.{w}']
elif args.model_type == "gpt2":
for w in ["weight", "bias"]:
lowerCAmelCase : str = state_dict[F'{prefix}.ln_f.{w}']
lowerCAmelCase : int = state_dict['lm_head.weight']
print(F'N layers selected for distillation: {std_idx}')
print(F'Number of params transferred for distillation: {len(compressed_sd.keys())}')
print(F'Save transferred checkpoint to {args.dump_checkpoint}.')
torch.save(compressed_sd, args.dump_checkpoint)
| 511 | 1 |
from __future__ import annotations
def UpperCAmelCase_ ( __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase ):
if (direction == 1 and array[indexa] > array[indexa]) or (
direction == 0 and array[indexa] < array[indexa]
):
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ =array[indexa], array[indexa]
def UpperCAmelCase_ ( __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase ):
if length > 1:
SCREAMING_SNAKE_CASE__ =int(length / 2 )
for i in range(__UpperCamelCase, low + middle ):
comp_and_swap(__UpperCamelCase, __UpperCamelCase, i + middle, __UpperCamelCase )
bitonic_merge(__UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase )
bitonic_merge(__UpperCamelCase, low + middle, __UpperCamelCase, __UpperCamelCase )
def UpperCAmelCase_ ( __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase ):
if length > 1:
SCREAMING_SNAKE_CASE__ =int(length / 2 )
bitonic_sort(__UpperCamelCase, __UpperCamelCase, __UpperCamelCase, 1 )
bitonic_sort(__UpperCamelCase, low + middle, __UpperCamelCase, 0 )
bitonic_merge(__UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase )
if __name__ == "__main__":
lowerCamelCase_ = input("Enter numbers separated by a comma:\n").strip()
lowerCamelCase_ = [int(item.strip()) for item in user_input.split(",")]
bitonic_sort(unsorted, 0, len(unsorted), 1)
print("\nSorted array in ascending order is: ", end="")
print(*unsorted, sep=", ")
bitonic_merge(unsorted, 0, len(unsorted), 0)
print("Sorted array in descending order is: ", end="")
print(*unsorted, sep=", ")
| 588 |
import argparse
import fairseq
import torch
from torch import nn
from transformers import (
MBartaaTokenizer,
MBartConfig,
MBartForCausalLM,
SpeechEncoderDecoderConfig,
SpeechEncoderDecoderModel,
WavaVecaConfig,
WavaVecaFeatureExtractor,
WavaVecaModel,
logging,
)
logging.set_verbosity_info()
lowerCamelCase_ = logging.get_logger(__name__)
lowerCamelCase_ = {
"post_extract_proj": "feature_projection.projection",
"encoder.pos_conv.0": "encoder.pos_conv_embed.conv",
"self_attn.k_proj": "encoder.layers.*.attention.k_proj",
"self_attn.v_proj": "encoder.layers.*.attention.v_proj",
"self_attn.q_proj": "encoder.layers.*.attention.q_proj",
"self_attn.out_proj": "encoder.layers.*.attention.out_proj",
"self_attn_layer_norm": "encoder.layers.*.layer_norm",
"fc1": "encoder.layers.*.feed_forward.intermediate_dense",
"fc2": "encoder.layers.*.feed_forward.output_dense",
"final_layer_norm": "encoder.layers.*.final_layer_norm",
"encoder.layer_norm": "encoder.layer_norm",
"w2v_model.layer_norm": "feature_projection.layer_norm",
"quantizer.weight_proj": "quantizer.weight_proj",
"quantizer.vars": "quantizer.codevectors",
"project_q": "project_q",
"final_proj": "project_hid",
"w2v_encoder.proj": "lm_head",
"mask_emb": "masked_spec_embed",
}
lowerCamelCase_ = [
"lm_head",
"quantizer.weight_proj",
"quantizer.codevectors",
"project_q",
"project_hid",
]
def UpperCAmelCase_ ( __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase ):
for attribute in key.split(""".""" ):
SCREAMING_SNAKE_CASE__ =getattr(__UpperCamelCase, __UpperCamelCase )
if weight_type is not None:
SCREAMING_SNAKE_CASE__ =getattr(__UpperCamelCase, __UpperCamelCase ).shape
else:
SCREAMING_SNAKE_CASE__ =hf_pointer.shape
assert hf_shape == value.shape, (
f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be"""
f""" {value.shape} for {full_name}"""
)
if weight_type == "weight":
SCREAMING_SNAKE_CASE__ =value
elif weight_type == "weight_g":
SCREAMING_SNAKE_CASE__ =value
elif weight_type == "weight_v":
SCREAMING_SNAKE_CASE__ =value
elif weight_type == "bias":
SCREAMING_SNAKE_CASE__ =value
else:
SCREAMING_SNAKE_CASE__ =value
logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" )
def UpperCAmelCase_ ( __UpperCamelCase, __UpperCamelCase ):
SCREAMING_SNAKE_CASE__ =[]
SCREAMING_SNAKE_CASE__ =fairseq_model.state_dict()
SCREAMING_SNAKE_CASE__ =hf_model.feature_extractor
SCREAMING_SNAKE_CASE__ =hf_model.adapter
for name, value in fairseq_dict.items():
SCREAMING_SNAKE_CASE__ =False
if "conv_layers" in name:
load_conv_layer(
__UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, hf_model.config.feat_extract_norm == """group""", )
SCREAMING_SNAKE_CASE__ =True
elif any(x in name for x in ["""adaptor""", """w2v_encoder.proj.""", """w2v_proj_ln."""] ):
load_adapter(__UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase )
SCREAMING_SNAKE_CASE__ =True
else:
for key, mapped_key in MAPPING.items():
if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]:
SCREAMING_SNAKE_CASE__ =True
if "*" in mapped_key:
SCREAMING_SNAKE_CASE__ =name.split(__UpperCamelCase )[0].split(""".""" )[-2]
SCREAMING_SNAKE_CASE__ =mapped_key.replace("""*""", __UpperCamelCase )
if "weight_g" in name:
SCREAMING_SNAKE_CASE__ ="""weight_g"""
elif "weight_v" in name:
SCREAMING_SNAKE_CASE__ ="""weight_v"""
elif "bias" in name:
SCREAMING_SNAKE_CASE__ ="""bias"""
elif "weight" in name:
SCREAMING_SNAKE_CASE__ ="""weight"""
else:
SCREAMING_SNAKE_CASE__ =None
set_recursively(__UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase )
continue
if not is_used:
unused_weights.append(__UpperCamelCase )
logger.warning(f"""Unused weights: {unused_weights}""" )
def UpperCAmelCase_ ( __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase ):
SCREAMING_SNAKE_CASE__ =full_name.split("""conv_layers.""" )[-1]
SCREAMING_SNAKE_CASE__ =name.split(""".""" )
SCREAMING_SNAKE_CASE__ =int(items[0] )
SCREAMING_SNAKE_CASE__ =int(items[1] )
if type_id == 0:
if "bias" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
f"""{full_name} has size {value.shape}, but"""
f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found."""
)
SCREAMING_SNAKE_CASE__ =value
logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" )
elif "weight" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
f"""{full_name} has size {value.shape}, but"""
f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found."""
)
SCREAMING_SNAKE_CASE__ =value
logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" )
elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
if "bias" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was"""
" found."
)
SCREAMING_SNAKE_CASE__ =value
logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" )
elif "weight" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
f"""{full_name} has size {value.shape}, but"""
f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found."""
)
SCREAMING_SNAKE_CASE__ =value
logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" )
else:
unused_weights.append(__UpperCamelCase )
def UpperCAmelCase_ ( __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase ):
SCREAMING_SNAKE_CASE__ =full_name.split("""adaptor.""" )[-1]
SCREAMING_SNAKE_CASE__ =name.split(""".""" )
if items[1].isdigit():
SCREAMING_SNAKE_CASE__ =int(items[1] )
else:
SCREAMING_SNAKE_CASE__ =None
if "adaptor" not in full_name:
if "proj_ln" in full_name:
# has to be layer norm
if "bias" in name:
assert (
value.shape == adapter.proj_layer_norm.bias.data.shape
), f"""{full_name} has size {value.shape}, but {adapter.proj_layer_norm.bias.data.shape} was found."""
SCREAMING_SNAKE_CASE__ =value
logger.info(f"""Adapter proj layer norm bias was initialized from {full_name}.""" )
if "weight" in name:
assert (
value.shape == adapter.proj_layer_norm.weight.data.shape
), f"""{full_name} has size {value.shape}, but {adapter.proj_layer_norm.weight.data.shape} was found."""
SCREAMING_SNAKE_CASE__ =value
else:
# has to be projection layer
if "bias" in name:
assert (
value.shape == adapter.proj.bias.data.shape
), f"""{full_name} has size {value.shape}, but {adapter.proj.bias.data.shape} was found."""
SCREAMING_SNAKE_CASE__ =value
logger.info(f"""Adapter proj layer bias was initialized from {full_name}.""" )
if "weight" in name:
assert (
value.shape == adapter.proj.weight.data.shape
), f"""{full_name} has size {value.shape}, but {adapter.proj.weight.data.shape} was found."""
SCREAMING_SNAKE_CASE__ =value
logger.info(f"""Adapter proj layer weight was initialized from {full_name}.""" )
elif isinstance(__UpperCamelCase, __UpperCamelCase ):
if "bias" in name:
assert (
value.shape == adapter.layers[layer_id].conv.bias.data.shape
), f"""{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.bias.data.shape} was found."""
SCREAMING_SNAKE_CASE__ =value
logger.info(f"""Adapter layer {layer_id} bias was initialized from {full_name}.""" )
elif "weight" in name:
assert (
value.shape == adapter.layers[layer_id].conv.weight.data.shape
), f"""{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.weight.data.shape} was found."""
SCREAMING_SNAKE_CASE__ =value
logger.info(f"""Adapter layer {layer_id} bias was initialized from {full_name}.""" )
else:
unused_weights.append(__UpperCamelCase )
def UpperCAmelCase_ ( __UpperCamelCase ):
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ =emb.weight.shape
SCREAMING_SNAKE_CASE__ =nn.Linear(__UpperCamelCase, __UpperCamelCase, bias=__UpperCamelCase )
SCREAMING_SNAKE_CASE__ =emb.weight.data
return lin_layer
@torch.no_grad()
def UpperCAmelCase_ ( __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, ):
SCREAMING_SNAKE_CASE__ =WavaVecaConfig.from_pretrained(
__UpperCamelCase, add_adapter=__UpperCamelCase, adapter_stride=__UpperCamelCase, adapter_kernel_size=__UpperCamelCase, use_auth_token=__UpperCamelCase, output_hidden_size=__UpperCamelCase, )
SCREAMING_SNAKE_CASE__ =MBartConfig.from_pretrained(__UpperCamelCase )
# load model
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ =fairseq.checkpoint_utils.load_model_ensemble_and_task(
[checkpoint_path], arg_overrides={
"""config_yaml""": config_yaml_path,
"""data""": """/""".join(dict_path.split("""/""" )[:-1] ),
"""w2v_path""": checkpoint_path,
"""load_pretrained_decoder_from""": None,
}, )
SCREAMING_SNAKE_CASE__ =model[0].eval()
# load feature extractor
SCREAMING_SNAKE_CASE__ =WavaVecaFeatureExtractor.from_pretrained(__UpperCamelCase, use_auth_token=__UpperCamelCase )
# set weights for wav2vec2 encoder
SCREAMING_SNAKE_CASE__ =WavaVecaModel(__UpperCamelCase )
recursively_load_weights_wavaveca(model.encoder, __UpperCamelCase )
# load decoder weights
SCREAMING_SNAKE_CASE__ =MBartForCausalLM(__UpperCamelCase )
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ =hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict(), strict=__UpperCamelCase )
logger.warning(f"""The following keys are missing when loading the decoder weights: {missing_keys}""" )
logger.warning(f"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" )
SCREAMING_SNAKE_CASE__ =SpeechEncoderDecoderModel(encoder=__UpperCamelCase, decoder=__UpperCamelCase )
SCREAMING_SNAKE_CASE__ =False
SCREAMING_SNAKE_CASE__ =MBartaaTokenizer(__UpperCamelCase )
tokenizer.save_pretrained(__UpperCamelCase )
SCREAMING_SNAKE_CASE__ =hf_wavavec.config.to_dict()
SCREAMING_SNAKE_CASE__ =tokenizer.pad_token_id
SCREAMING_SNAKE_CASE__ =tokenizer.bos_token_id
SCREAMING_SNAKE_CASE__ =tokenizer.eos_token_id
SCREAMING_SNAKE_CASE__ ="""mbart50"""
SCREAMING_SNAKE_CASE__ ="""wav2vec2"""
SCREAMING_SNAKE_CASE__ =tokenizer.eos_token_id
SCREAMING_SNAKE_CASE__ =250_004
SCREAMING_SNAKE_CASE__ =tokenizer.eos_token_id
SCREAMING_SNAKE_CASE__ =SpeechEncoderDecoderConfig.from_dict(__UpperCamelCase )
hf_wavavec.save_pretrained(__UpperCamelCase )
feature_extractor.save_pretrained(__UpperCamelCase )
if __name__ == "__main__":
lowerCamelCase_ = argparse.ArgumentParser()
parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint")
parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model")
parser.add_argument("--config_yaml_path", default=None, type=str, help="Path to yaml file of fine-tuned model")
parser.add_argument(
"--encoder_config_path",
default="facebook/wav2vec2-xls-r-1b",
type=str,
help="Path to hf encoder wav2vec2 checkpoint config",
)
parser.add_argument(
"--decoder_config_path",
default="facebook/mbart-large-50-one-to-many-mmt",
type=str,
help="Path to hf decoder checkpoint config",
)
parser.add_argument("--add_adapter", default=True, type=bool, help="whethere to add model adapter layers")
parser.add_argument("--adapter_stride", default=2, type=int, help="stride of adapter layers")
parser.add_argument("--adapter_kernel_size", default=3, type=int, help="kernel size of adapter layers")
parser.add_argument("--encoder_output_dim", default=1024, type=int, help="encoder output dim")
parser.add_argument("--start_token_id", default=250004, type=int, help="`decoder_start_token_id` of model config")
lowerCamelCase_ = parser.parse_args()
convert_wavaveca_checkpoint(
args.checkpoint_path,
args.pytorch_dump_folder_path,
args.dict_path,
args.config_yaml_path,
encoder_config_path=args.encoder_config_path,
decoder_config_path=args.decoder_config_path,
add_adapter=args.add_adapter,
adapter_kernel_size=args.adapter_kernel_size,
adapter_stride=args.adapter_stride,
decoder_start_token_id=args.start_token_id,
encoder_output_dim=args.encoder_output_dim,
)
| 588 | 1 |
def __snake_case ( __magic_name__ = 1000 ):
'''simple docstring'''
lowercase , lowercase = 1, 1
lowercase = []
for i in range(1 , n + 1 ):
lowercase = prev_numerator + 2 * prev_denominator
lowercase = prev_numerator + prev_denominator
if len(str(_lowercase ) ) > len(str(_lowercase ) ):
result.append(_lowercase )
lowercase = numerator
lowercase = denominator
return len(_lowercase )
if __name__ == "__main__":
print(F"{solution() = }")
| 441 |
"""simple docstring"""
import json
import os
import unittest
from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import (
VOCAB_FILES_NAMES,
GPTSanJapaneseTokenizer,
)
from transformers.testing_utils import require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class __a ( __snake_case , unittest.TestCase ):
lowerCamelCase : Any =GPTSanJapaneseTokenizer
lowerCamelCase : List[str] =False
lowerCamelCase : List[str] ={'do_clean_text': False, 'add_prefix_space': False}
def lowerCamelCase_ ( self ):
'''simple docstring'''
super().setUp()
# fmt: off
lowerCAmelCase_ = ['''こん''', '''こんに''', '''にちは''', '''ばんは''', '''世界,㔺界''', '''、''', '''。''', '''<BR>''', '''<SP>''', '''<TAB>''', '''<URL>''', '''<EMAIL>''', '''<TEL>''', '''<DATE>''', '''<PRICE>''', '''<BLOCK>''', '''<KIGOU>''', '''<U2000U2BFF>''', '''<|emoji1|>''', '''<unk>''', '''<|bagoftoken|>''', '''<|endoftext|>''']
# fmt: on
lowerCAmelCase_ = {'''emoji''': {'''\ud83d\ude00''': '''<|emoji1|>'''}, '''emoji_inv''': {'''<|emoji1|>''': '''\ud83d\ude00'''}} # 😀
lowerCAmelCase_ = {'''unk_token''': '''<unk>'''}
lowerCAmelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
lowerCAmelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''emoji_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer:
vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) )
with open(self.emoji_file , '''w''' ) as emoji_writer:
emoji_writer.write(json.dumps(UpperCAmelCase ) )
def lowerCamelCase_ ( self , **UpperCAmelCase ):
'''simple docstring'''
kwargs.update(self.special_tokens_map )
return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase )
def lowerCamelCase_ ( self , UpperCAmelCase ):
'''simple docstring'''
lowerCAmelCase_ = '''こんにちは、世界。 \nこんばんは、㔺界。😀'''
lowerCAmelCase_ = '''こんにちは、世界。 \nこんばんは、世界。😀'''
return input_text, output_text
def lowerCamelCase_ ( self , UpperCAmelCase ):
'''simple docstring'''
lowerCAmelCase_ , lowerCAmelCase_ = self.get_input_output_texts(UpperCAmelCase )
lowerCAmelCase_ = tokenizer.encode(UpperCAmelCase , add_special_tokens=UpperCAmelCase )
lowerCAmelCase_ = tokenizer.decode(UpperCAmelCase , clean_up_tokenization_spaces=UpperCAmelCase )
return text, ids
def lowerCamelCase_ ( self ):
'''simple docstring'''
pass # TODO add if relevant
def lowerCamelCase_ ( self ):
'''simple docstring'''
pass # TODO add if relevant
def lowerCamelCase_ ( self ):
'''simple docstring'''
pass # TODO add if relevant
def lowerCamelCase_ ( self ):
'''simple docstring'''
lowerCAmelCase_ = self.get_tokenizer()
# Testing tokenization
lowerCAmelCase_ = '''こんにちは、世界。 こんばんは、㔺界。'''
lowerCAmelCase_ = ['''こん''', '''にちは''', '''、''', '''世界''', '''。''', '''<SP>''', '''こん''', '''ばんは''', '''、''', '''㔺界''', '''。''']
lowerCAmelCase_ = tokenizer.tokenize(UpperCAmelCase )
self.assertListEqual(UpperCAmelCase , UpperCAmelCase )
# Testing conversion to ids without special tokens
lowerCAmelCase_ = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6]
lowerCAmelCase_ = tokenizer.convert_tokens_to_ids(UpperCAmelCase )
self.assertListEqual(UpperCAmelCase , UpperCAmelCase )
# Testing conversion to ids with special tokens
lowerCAmelCase_ = tokens + [tokenizer.unk_token]
lowerCAmelCase_ = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19]
lowerCAmelCase_ = tokenizer.convert_tokens_to_ids(UpperCAmelCase )
self.assertListEqual(UpperCAmelCase , UpperCAmelCase )
def lowerCamelCase_ ( self ):
'''simple docstring'''
lowerCAmelCase_ = self.get_tokenizer()
# Testing tokenization
lowerCAmelCase_ = '''こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。'''
lowerCAmelCase_ = '''こんにちは、、、、世界。こんばんは、、、、世界。'''
lowerCAmelCase_ = tokenizer.encode(UpperCAmelCase )
lowerCAmelCase_ = tokenizer.decode(UpperCAmelCase )
self.assertEqual(UpperCAmelCase , UpperCAmelCase )
@slow
def lowerCamelCase_ ( self ):
'''simple docstring'''
lowerCAmelCase_ = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' )
# Testing tokenization
lowerCAmelCase_ = '''こんにちは、世界。'''
lowerCAmelCase_ = '''こんばんは、㔺界。😀'''
lowerCAmelCase_ = '''こんにちは、世界。こんばんは、世界。😀'''
lowerCAmelCase_ = tokenizer.encode(prefix_text + input_text )
lowerCAmelCase_ = tokenizer.encode('''''' , prefix_text=prefix_text + input_text )
lowerCAmelCase_ = tokenizer.encode(UpperCAmelCase , prefix_text=UpperCAmelCase )
lowerCAmelCase_ = tokenizer.decode(UpperCAmelCase )
lowerCAmelCase_ = tokenizer.decode(UpperCAmelCase )
lowerCAmelCase_ = tokenizer.decode(UpperCAmelCase )
self.assertEqual(UpperCAmelCase , UpperCAmelCase )
self.assertEqual(UpperCAmelCase , UpperCAmelCase )
self.assertEqual(UpperCAmelCase , UpperCAmelCase )
@slow
def lowerCamelCase_ ( self ):
'''simple docstring'''
lowerCAmelCase_ = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' )
# Testing tokenization
lowerCAmelCase_ = '''こんにちは、世界。'''
lowerCAmelCase_ = '''こんばんは、㔺界。😀'''
lowerCAmelCase_ = len(tokenizer.encode(UpperCAmelCase ) ) - 2
lowerCAmelCase_ = len(tokenizer.encode(UpperCAmelCase ) ) - 2
lowerCAmelCase_ = [1] + [0] * (len_prefix + len_text + 1)
lowerCAmelCase_ = [1] * (len_prefix + len_text + 1) + [0]
lowerCAmelCase_ = [1] + [1] * (len_prefix) + [0] * (len_text + 1)
lowerCAmelCase_ = tokenizer(prefix_text + input_text ).token_type_ids
lowerCAmelCase_ = tokenizer('''''' , prefix_text=prefix_text + input_text ).token_type_ids
lowerCAmelCase_ = tokenizer(UpperCAmelCase , prefix_text=UpperCAmelCase ).token_type_ids
self.assertListEqual(UpperCAmelCase , UpperCAmelCase )
self.assertListEqual(UpperCAmelCase , UpperCAmelCase )
self.assertListEqual(UpperCAmelCase , UpperCAmelCase )
@slow
def lowerCamelCase_ ( self ):
'''simple docstring'''
lowerCAmelCase_ = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' )
lowerCAmelCase_ = tokenizer.encode('''あンいワ''' )
lowerCAmelCase_ = tokenizer.encode('''''' , prefix_text='''あンいワ''' )
lowerCAmelCase_ = tokenizer.encode('''いワ''' , prefix_text='''あン''' )
self.assertEqual(tokenizer.decode(UpperCAmelCase ) , tokenizer.decode(UpperCAmelCase ) )
self.assertEqual(tokenizer.decode(UpperCAmelCase ) , tokenizer.decode(UpperCAmelCase ) )
self.assertNotEqual(UpperCAmelCase , UpperCAmelCase )
self.assertNotEqual(UpperCAmelCase , UpperCAmelCase )
self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token
self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token
@slow
def lowerCamelCase_ ( self ):
'''simple docstring'''
lowerCAmelCase_ = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' )
lowerCAmelCase_ = [['''武田信玄''', '''は、'''], ['''織田信長''', '''の配下の、''']]
lowerCAmelCase_ = tokenizer(UpperCAmelCase , padding=UpperCAmelCase )
lowerCAmelCase_ = tokenizer.batch_encode_plus(UpperCAmelCase , padding=UpperCAmelCase )
# fmt: off
lowerCAmelCase_ = [[3_5993, 8640, 2_5948, 3_5998, 3_0647, 3_5675, 3_5999, 3_5999], [3_5993, 1_0382, 9868, 3_5998, 3_0646, 9459, 3_0646, 3_5675]]
lowerCAmelCase_ = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]]
lowerCAmelCase_ = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]]
# fmt: on
self.assertListEqual(x_token.input_ids , UpperCAmelCase )
self.assertListEqual(x_token.token_type_ids , UpperCAmelCase )
self.assertListEqual(x_token.attention_mask , UpperCAmelCase )
self.assertListEqual(x_token_a.input_ids , UpperCAmelCase )
self.assertListEqual(x_token_a.token_type_ids , UpperCAmelCase )
self.assertListEqual(x_token_a.attention_mask , UpperCAmelCase )
def lowerCamelCase_ ( self ):
'''simple docstring'''
pass
def lowerCamelCase_ ( self ):
'''simple docstring'''
pass | 552 | 0 |
def __magic_name__ ( lowercase_ ) -> float:
'''simple docstring'''
if not nums: # Makes sure that the list is not empty
raise ValueError("List is empty" )
UpperCamelCase = sum(lowercase_ ) / len(lowercase_ ) # Calculate the average
return sum(abs(x - average ) for x in nums ) / len(lowercase_ )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 414 |
from typing import Union
from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging
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_VISUAL_QUESTION_ANSWERING_MAPPING
__a : Dict = logging.get_logger(__name__)
@add_end_docstrings(snake_case__ )
class __UpperCAmelCase ( snake_case__ ):
"""simple docstring"""
def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Optional[int]:
"""simple docstring"""
super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
self.check_model_type(SCREAMING_SNAKE_CASE )
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , **SCREAMING_SNAKE_CASE ) -> List[str]:
"""simple docstring"""
UpperCamelCase , UpperCamelCase = {}, {}
if padding is not None:
UpperCamelCase = padding
if truncation is not None:
UpperCamelCase = truncation
if top_k is not None:
UpperCamelCase = top_k
return preprocess_params, {}, postprocess_params
def __call__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE ) -> Optional[int]:
"""simple docstring"""
if isinstance(SCREAMING_SNAKE_CASE , (Image.Image, str) ) and isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
UpperCamelCase = {"image": image, "question": question}
else:
UpperCamelCase = image
UpperCamelCase = super().__call__(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
return results
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False ) -> Any:
"""simple docstring"""
UpperCamelCase = load_image(inputs["image"] )
UpperCamelCase = self.tokenizer(
inputs["question"] , return_tensors=self.framework , padding=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE )
UpperCamelCase = self.image_processor(images=SCREAMING_SNAKE_CASE , return_tensors=self.framework )
model_inputs.update(SCREAMING_SNAKE_CASE )
return model_inputs
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> List[str]:
"""simple docstring"""
UpperCamelCase = self.model(**SCREAMING_SNAKE_CASE )
return model_outputs
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=5 ) -> str:
"""simple docstring"""
if top_k > self.model.config.num_labels:
UpperCamelCase = self.model.config.num_labels
if self.framework == "pt":
UpperCamelCase = model_outputs.logits.sigmoid()[0]
UpperCamelCase , UpperCamelCase = probs.topk(SCREAMING_SNAKE_CASE )
else:
raise ValueError(f'''Unsupported framework: {self.framework}''' )
UpperCamelCase = scores.tolist()
UpperCamelCase = ids.tolist()
return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )]
| 414 | 1 |
'''simple docstring'''
from __future__ import annotations
import unittest
from transformers import LEDConfig, is_tf_available
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TFLEDForConditionalGeneration, TFLEDModel
@require_tf
class UpperCAmelCase__ :
"""simple docstring"""
__UpperCAmelCase : int = LEDConfig
__UpperCAmelCase : Union[str, Any] = {}
__UpperCAmelCase : Dict = '''gelu'''
def __init__( self : Optional[Any] ,_a : str ,_a : List[str]=13 ,_a : List[str]=7 ,_a : Optional[Any]=True ,_a : Dict=False ,_a : str=99 ,_a : List[Any]=32 ,_a : int=2 ,_a : str=4 ,_a : List[Any]=37 ,_a : Union[str, Any]=0.1 ,_a : Tuple=0.1 ,_a : str=20 ,_a : List[Any]=2 ,_a : Optional[Any]=1 ,_a : int=0 ,_a : Dict=4 ,):
'''simple docstring'''
_a : Dict = parent
_a : List[Any] = batch_size
_a : str = seq_length
_a : Dict = is_training
_a : Tuple = use_labels
_a : List[str] = vocab_size
_a : Union[str, Any] = hidden_size
_a : Union[str, Any] = num_hidden_layers
_a : Any = num_attention_heads
_a : Union[str, Any] = intermediate_size
_a : Any = hidden_dropout_prob
_a : Optional[Any] = attention_probs_dropout_prob
_a : Optional[Any] = max_position_embeddings
_a : Dict = eos_token_id
_a : Tuple = pad_token_id
_a : Optional[int] = bos_token_id
_a : Tuple = attention_window
# `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size
# [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention
# returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1]
# because its local attention only attends to `self.attention_window` and one before and one after
_a : List[str] = self.attention_window + 2
# because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for
# the `test_attention_outputs` and `test_hidden_states_output` tests
_a : Optional[Any] = (
self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window
)
def __lowercase ( self : Dict ):
'''simple docstring'''
_a : List[str] = ids_tensor([self.batch_size, self.seq_length - 1] ,self.vocab_size )
_a : Any = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) ,1 )
_a : List[Any] = tf.concat([input_ids, eos_tensor] ,axis=1 )
_a : Tuple = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size )
_a : str = self.config_cls(
vocab_size=self.vocab_size ,d_model=self.hidden_size ,encoder_layers=self.num_hidden_layers ,decoder_layers=self.num_hidden_layers ,encoder_attention_heads=self.num_attention_heads ,decoder_attention_heads=self.num_attention_heads ,encoder_ffn_dim=self.intermediate_size ,decoder_ffn_dim=self.intermediate_size ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,eos_token_ids=[2] ,bos_token_id=self.bos_token_id ,pad_token_id=self.pad_token_id ,decoder_start_token_id=self.pad_token_id ,attention_window=self.attention_window ,**self.config_updates ,)
_a : Dict = prepare_led_inputs_dict(_a ,_a ,_a )
_a : Dict = tf.concat(
[tf.zeros_like(_a )[:, :-1], tf.ones_like(_a )[:, -1:]] ,axis=-1 ,)
_a : int = global_attention_mask
return config, inputs_dict
def __lowercase ( self : int ,_a : Tuple ,_a : Union[str, Any] ):
'''simple docstring'''
_a : int = TFLEDModel(config=_a ).get_decoder()
_a : Union[str, Any] = inputs_dict['input_ids']
_a : str = input_ids[:1, :]
_a : Optional[int] = inputs_dict['attention_mask'][:1, :]
_a : Dict = 1
# first forward pass
_a : Tuple = model(_a ,attention_mask=_a ,use_cache=_a )
_a, _a : List[Any] = outputs.to_tuple()
# create hypothetical next token and extent to next_input_ids
_a : List[Any] = ids_tensor((self.batch_size, 3) ,config.vocab_size )
_a : Union[str, Any] = tf.cast(ids_tensor((self.batch_size, 3) ,2 ) ,tf.inta )
# append to next input_ids and
_a : Any = tf.concat([input_ids, next_tokens] ,axis=-1 )
_a : Optional[Any] = tf.concat([attention_mask, next_attn_mask] ,axis=-1 )
_a : Tuple = model(_a ,attention_mask=_a )[0]
_a : List[Any] = model(_a ,attention_mask=_a ,past_key_values=_a )[0]
self.parent.assertEqual(next_tokens.shape[1] ,output_from_past.shape[1] )
# select random slice
_a : List[str] = int(ids_tensor((1,) ,output_from_past.shape[-1] ) )
_a : Dict = output_from_no_past[:, -3:, random_slice_idx]
_a : Any = output_from_past[:, :, random_slice_idx]
# test that outputs are equal for slice
tf.debugging.assert_near(_a ,_a ,rtol=1E-3 )
def UpperCAmelCase_ (__a : Union[str, Any] , __a : List[Any] , __a : Union[str, Any] , __a : Optional[int]=None , __a : Any=None , __a : Tuple=None , __a : List[str]=None , ):
"""simple docstring"""
if attention_mask is None:
_a : str = tf.cast(tf.math.not_equal(__a , config.pad_token_id ) , tf.inta )
if decoder_attention_mask is None:
_a : Any = tf.concat(
[
tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ),
tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ),
] , axis=-1 , )
if head_mask is None:
_a : str = tf.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
_a : List[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
return {
"input_ids": input_ids,
"attention_mask": attention_mask,
"decoder_input_ids": decoder_input_ids,
"decoder_attention_mask": decoder_attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
}
@require_tf
class UpperCAmelCase__ ( lowercase__ , lowercase__ , unittest.TestCase ):
"""simple docstring"""
__UpperCAmelCase : List[Any] = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else ()
__UpperCAmelCase : str = (TFLEDForConditionalGeneration,) if is_tf_available() else ()
__UpperCAmelCase : Union[str, Any] = (
{
'''conversational''': TFLEDForConditionalGeneration,
'''feature-extraction''': TFLEDModel,
'''summarization''': TFLEDForConditionalGeneration,
'''text2text-generation''': TFLEDForConditionalGeneration,
'''translation''': TFLEDForConditionalGeneration,
}
if is_tf_available()
else {}
)
__UpperCAmelCase : Optional[Any] = True
__UpperCAmelCase : Optional[int] = False
__UpperCAmelCase : List[Any] = False
__UpperCAmelCase : str = False
def __lowercase ( self : Optional[Any] ):
'''simple docstring'''
_a : List[Any] = TFLEDModelTester(self )
_a : Optional[int] = ConfigTester(self ,config_class=_a )
def __lowercase ( self : Any ):
'''simple docstring'''
self.config_tester.run_common_tests()
def __lowercase ( self : Optional[int] ):
'''simple docstring'''
_a : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*_a )
def __lowercase ( self : Tuple ):
'''simple docstring'''
_a, _a : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common()
_a : Tuple = tf.zeros_like(inputs_dict['attention_mask'] )
_a : List[Any] = 2
_a : Dict = tf.where(
tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices ,1 ,inputs_dict['global_attention_mask'] ,)
_a : Tuple = True
_a : List[Any] = self.model_tester.seq_length
_a : str = self.model_tester.encoder_seq_length
def check_decoder_attentions_output(_a : str ):
_a : Union[str, Any] = outputs.decoder_attentions
self.assertEqual(len(_a ) ,self.model_tester.num_hidden_layers )
self.assertListEqual(
list(decoder_attentions[0].shape[-3:] ) ,[self.model_tester.num_attention_heads, seq_length, seq_length] ,)
def check_encoder_attentions_output(_a : Tuple ):
_a : Optional[Any] = [t.numpy() for t in outputs.encoder_attentions]
_a : Optional[Any] = [t.numpy() for t in outputs.encoder_global_attentions]
self.assertEqual(len(_a ) ,self.model_tester.num_hidden_layers )
self.assertEqual(len(_a ) ,self.model_tester.num_hidden_layers )
self.assertListEqual(
list(attentions[0].shape[-3:] ) ,[self.model_tester.num_attention_heads, seq_length, seq_length] ,)
self.assertListEqual(
list(global_attentions[0].shape[-3:] ) ,[self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] ,)
for model_class in self.all_model_classes:
_a : Union[str, Any] = True
_a : Union[str, Any] = False
_a : Tuple = False
_a : Union[str, Any] = model_class(_a )
_a : Union[str, Any] = model(self._prepare_for_class(_a ,_a ) )
_a : Dict = len(_a )
self.assertEqual(config.output_hidden_states ,_a )
check_encoder_attentions_output(_a )
if self.is_encoder_decoder:
_a : Any = model_class(_a )
_a : Tuple = model(self._prepare_for_class(_a ,_a ) )
self.assertEqual(config.output_hidden_states ,_a )
check_decoder_attentions_output(_a )
# Check that output attentions can also be changed via the config
del inputs_dict["output_attentions"]
_a : str = True
_a : Optional[Any] = model_class(_a )
_a : Dict = model(self._prepare_for_class(_a ,_a ) )
self.assertEqual(config.output_hidden_states ,_a )
check_encoder_attentions_output(_a )
# Check attention is always last and order is fine
_a : Dict = True
_a : Dict = True
_a : Optional[int] = model_class(_a )
_a : Union[str, Any] = model(self._prepare_for_class(_a ,_a ) )
self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) ,len(_a ) )
self.assertEqual(model.config.output_hidden_states ,_a )
check_encoder_attentions_output(_a )
@unittest.skip('LED keeps using potentially symbolic tensors in conditionals and breaks tracing.' )
def __lowercase ( self : Any ):
'''simple docstring'''
pass
def __lowercase ( self : str ):
'''simple docstring'''
pass
def UpperCAmelCase_ (__a : Union[str, Any] ):
"""simple docstring"""
return tf.constant(__a , dtype=tf.intaa )
__lowerCAmelCase = 1e-4
@slow
@require_tf
class UpperCAmelCase__ ( unittest.TestCase ):
"""simple docstring"""
def __lowercase ( self : Optional[Any] ):
'''simple docstring'''
_a : Tuple = TFLEDForConditionalGeneration.from_pretrained('allenai/led-base-16384' ).led
# change to intended input here
_a : Optional[int] = _long_tensor([512 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] )
_a : str = _long_tensor([128 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] )
_a : Tuple = prepare_led_inputs_dict(model.config ,_a ,_a )
_a : Optional[int] = model(**_a )[0]
_a : List[Any] = (1, 1024, 768)
self.assertEqual(output.shape ,_a )
# change to expected output here
_a : Optional[int] = tf.convert_to_tensor(
[[2.3050, 2.8279, 0.6531], [-1.8457, -0.1455, -3.5661], [-1.0186, 0.4586, -2.2043]] ,)
tf.debugging.assert_near(output[:, :3, :3] ,_a ,atol=1E-3 )
def __lowercase ( self : Optional[int] ):
'''simple docstring'''
_a : int = TFLEDForConditionalGeneration.from_pretrained('allenai/led-base-16384' )
# change to intended input here
_a : Dict = _long_tensor([512 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] )
_a : List[str] = _long_tensor([128 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] )
_a : Union[str, Any] = prepare_led_inputs_dict(model.config ,_a ,_a )
_a : Union[str, Any] = model(**_a )[0]
_a : Optional[Any] = (1, 1024, model.config.vocab_size)
self.assertEqual(output.shape ,_a )
# change to expected output here
_a : Optional[Any] = tf.convert_to_tensor(
[[33.6507, 6.4572, 16.8089], [5.8739, -2.4238, 11.2902], [-3.2139, -4.3149, 4.2783]] ,)
tf.debugging.assert_near(output[:, :3, :3] ,_a ,atol=1E-3 ,rtol=1E-3 )
| 229 |
'''simple docstring'''
from __future__ import annotations
from functools import lru_cache
from math import ceil
__lowerCAmelCase = 1_0_0
__lowerCAmelCase = set(range(3, NUM_PRIMES, 2))
primes.add(2)
__lowerCAmelCase = 42
for prime in range(3, ceil(NUM_PRIMES**0.5), 2):
if prime not in primes:
continue
primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime)))
@lru_cache(maxsize=1_0_0 )
def UpperCAmelCase_ (__a : int ):
"""simple docstring"""
if number_to_partition < 0:
return set()
elif number_to_partition == 0:
return {1}
_a : set[int] = set()
_a : int
_a : int
for prime in primes:
if prime > number_to_partition:
continue
for sub in partition(number_to_partition - prime ):
ret.add(sub * prime )
return ret
def UpperCAmelCase_ (__a : int = 5_0_0_0 ):
"""simple docstring"""
for number_to_partition in range(1 , __a ):
if len(partition(__a ) ) > number_unique_partitions:
return number_to_partition
return None
if __name__ == "__main__":
print(f'''{solution() = }''')
| 229 | 1 |
"""simple docstring"""
from math import sqrt
def A_ ( UpperCAmelCase__ ) -> bool:
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ) and (
number >= 0
), "'number' must been an int and positive"
a : Tuple = True
# 0 and 1 are none primes.
if number <= 1:
a : Dict = False
for divisor in range(2 , int(round(sqrt(UpperCamelCase__ ) ) ) + 1 ):
# if 'number' divisible by 'divisor' then sets 'status'
# of false and break up the loop.
if number % divisor == 0:
a : List[str] = False
break
# precondition
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ), "'status' must been from type bool"
return status
def A_ ( UpperCAmelCase__ ) -> Optional[int]:
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ) and (n > 2), "'N' must been an int and > 2"
# beginList: contains all natural numbers from 2 up to N
a : Tuple = list(range(2 , n + 1 ) )
a : int = [] # this list will be returns.
# actual sieve of erathostenes
for i in range(len(UpperCamelCase__ ) ):
for j in range(i + 1 , len(UpperCamelCase__ ) ):
if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):
a : Dict = 0
# filters actual prime numbers.
a : Tuple = [x for x in begin_list if x != 0]
# precondition
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ), "'ans' must been from type list"
return ans
def A_ ( UpperCAmelCase__ ) -> List[str]:
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ) and (n > 2), "'N' must been an int and > 2"
a : Union[str, Any] = []
# iterates over all numbers between 2 up to N+1
# if a number is prime then appends to list 'ans'
for number in range(2 , n + 1 ):
if is_prime(UpperCamelCase__ ):
ans.append(UpperCamelCase__ )
# precondition
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ), "'ans' must been from type list"
return ans
def A_ ( UpperCAmelCase__ ) -> Optional[int]:
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ) and number >= 0, "'number' must been an int and >= 0"
a : List[Any] = [] # this list will be returns of the function.
# potential prime number factors.
a : Optional[int] = 2
a : Tuple = number
if number == 0 or number == 1:
ans.append(UpperCamelCase__ )
# if 'number' not prime then builds the prime factorization of 'number'
elif not is_prime(UpperCamelCase__ ):
while quotient != 1:
if is_prime(UpperCamelCase__ ) and (quotient % factor == 0):
ans.append(UpperCamelCase__ )
quotient /= factor
else:
factor += 1
else:
ans.append(UpperCamelCase__ )
# precondition
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ), "'ans' must been from type list"
return ans
def A_ ( UpperCAmelCase__ ) -> Optional[int]:
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ) and (
number >= 0
), "'number' bust been an int and >= 0"
a : List[Any] = 0
# prime factorization of 'number'
a : Dict = prime_factorization(UpperCamelCase__ )
a : List[str] = max(UpperCamelCase__ )
# precondition
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ), "'ans' must been from type int"
return ans
def A_ ( UpperCAmelCase__ ) -> Union[str, Any]:
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ) and (
number >= 0
), "'number' bust been an int and >= 0"
a : Optional[Any] = 0
# prime factorization of 'number'
a : List[str] = prime_factorization(UpperCamelCase__ )
a : Optional[Any] = min(UpperCamelCase__ )
# precondition
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ), "'ans' must been from type int"
return ans
def A_ ( UpperCAmelCase__ ) -> List[str]:
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ), "'number' must been an int"
assert isinstance(number % 2 == 0 , UpperCamelCase__ ), "compare bust been from type bool"
return number % 2 == 0
def A_ ( UpperCAmelCase__ ) -> str:
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ), "'number' must been an int"
assert isinstance(number % 2 != 0 , UpperCamelCase__ ), "compare bust been from type bool"
return number % 2 != 0
def A_ ( UpperCAmelCase__ ) -> int:
assert (
isinstance(UpperCamelCase__ , UpperCamelCase__ ) and (number > 2) and is_even(UpperCamelCase__ )
), "'number' must been an int, even and > 2"
a : List[Any] = [] # this list will returned
# creates a list of prime numbers between 2 up to 'number'
a : List[str] = get_prime_numbers(UpperCamelCase__ )
a : Union[str, Any] = len(UpperCamelCase__ )
# run variable for while-loops.
a : List[Any] = 0
a : Tuple = None
# exit variable. for break up the loops
a : Tuple = True
while i < len_pn and loop:
a : Any = i + 1
while j < len_pn and loop:
if prime_numbers[i] + prime_numbers[j] == number:
a : Tuple = False
ans.append(prime_numbers[i] )
ans.append(prime_numbers[j] )
j += 1
i += 1
# precondition
assert (
isinstance(UpperCamelCase__ , UpperCamelCase__ )
and (len(UpperCamelCase__ ) == 2)
and (ans[0] + ans[1] == number)
and is_prime(ans[0] )
and is_prime(ans[1] )
), "'ans' must contains two primes. And sum of elements must been eq 'number'"
return ans
def A_ ( UpperCAmelCase__ , UpperCAmelCase__ ) -> Tuple:
assert (
isinstance(UpperCamelCase__ , UpperCamelCase__ )
and isinstance(UpperCamelCase__ , UpperCamelCase__ )
and (numbera >= 0)
and (numbera >= 0)
), "'number1' and 'number2' must been positive integer."
a : Tuple = 0
while numbera != 0:
a : List[str] = numbera % numbera
a : Optional[int] = numbera
a : Optional[int] = rest
# precondition
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ) and (
numbera >= 0
), "'number' must been from type int and positive"
return numbera
def A_ ( UpperCAmelCase__ , UpperCAmelCase__ ) -> Any:
assert (
isinstance(UpperCamelCase__ , UpperCamelCase__ )
and isinstance(UpperCamelCase__ , UpperCamelCase__ )
and (numbera >= 1)
and (numbera >= 1)
), "'number1' and 'number2' must been positive integer."
a : str = 1 # actual answer that will be return.
# for kgV (x,1)
if numbera > 1 and numbera > 1:
# builds the prime factorization of 'number1' and 'number2'
a : Any = prime_factorization(UpperCamelCase__ )
a : List[str] = prime_factorization(UpperCamelCase__ )
elif numbera == 1 or numbera == 1:
a : str = []
a : str = []
a : Optional[int] = max(UpperCamelCase__ , UpperCamelCase__ )
a : Optional[Any] = 0
a : Dict = 0
a : Optional[int] = [] # captured numbers int both 'primeFac1' and 'primeFac2'
# iterates through primeFac1
for n in prime_fac_a:
if n not in done:
if n in prime_fac_a:
a : Any = prime_fac_a.count(UpperCamelCase__ )
a : Tuple = prime_fac_a.count(UpperCamelCase__ )
for _ in range(max(UpperCamelCase__ , UpperCamelCase__ ) ):
ans *= n
else:
a : Dict = prime_fac_a.count(UpperCamelCase__ )
for _ in range(UpperCamelCase__ ):
ans *= n
done.append(UpperCamelCase__ )
# iterates through primeFac2
for n in prime_fac_a:
if n not in done:
a : Tuple = prime_fac_a.count(UpperCamelCase__ )
for _ in range(UpperCamelCase__ ):
ans *= n
done.append(UpperCamelCase__ )
# precondition
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ) and (
ans >= 0
), "'ans' must been from type int and positive"
return ans
def A_ ( UpperCAmelCase__ ) -> Dict:
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ) and (n >= 0), "'number' must been a positive int"
a : List[str] = 0
a : Optional[int] = 2 # this variable holds the answer
while index < n:
index += 1
ans += 1 # counts to the next number
# if ans not prime then
# runs to the next prime number.
while not is_prime(UpperCamelCase__ ):
ans += 1
# precondition
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ) and is_prime(
UpperCamelCase__ ), "'ans' must been a prime number and from type int"
return ans
def A_ ( UpperCAmelCase__ , UpperCAmelCase__ ) -> Any:
assert (
is_prime(UpperCamelCase__ ) and is_prime(UpperCamelCase__ ) and (p_number_a < p_number_a)
), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'"
a : List[str] = p_number_a + 1 # jump to the next number
a : Dict = [] # this list will be returns.
# if number is not prime then
# fetch the next prime number.
while not is_prime(UpperCamelCase__ ):
number += 1
while number < p_number_a:
ans.append(UpperCamelCase__ )
number += 1
# fetch the next prime number.
while not is_prime(UpperCamelCase__ ):
number += 1
# precondition
assert (
isinstance(UpperCamelCase__ , UpperCamelCase__ )
and ans[0] != p_number_a
and ans[len(UpperCamelCase__ ) - 1] != p_number_a
), "'ans' must been a list without the arguments"
# 'ans' contains not 'pNumber1' and 'pNumber2' !
return ans
def A_ ( UpperCAmelCase__ ) -> Dict:
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ) and (n >= 1), "'n' must been int and >= 1"
a : Optional[Any] = [] # will be returned.
for divisor in range(1 , n + 1 ):
if n % divisor == 0:
ans.append(UpperCamelCase__ )
# precondition
assert ans[0] == 1 and ans[len(UpperCamelCase__ ) - 1] == n, "Error in function getDivisiors(...)"
return ans
def A_ ( UpperCAmelCase__ ) -> Any:
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ) and (
number > 1
), "'number' must been an int and >= 1"
a : int = get_divisors(UpperCamelCase__ )
# precondition
assert (
isinstance(UpperCamelCase__ , UpperCamelCase__ )
and (divisors[0] == 1)
and (divisors[len(UpperCamelCase__ ) - 1] == number)
), "Error in help-function getDivisiors(...)"
# summed all divisors up to 'number' (exclusive), hence [:-1]
return sum(divisors[:-1] ) == number
def A_ ( UpperCAmelCase__ , UpperCAmelCase__ ) -> int:
assert (
isinstance(UpperCamelCase__ , UpperCamelCase__ )
and isinstance(UpperCamelCase__ , UpperCamelCase__ )
and (denominator != 0)
), "The arguments must been from type int and 'denominator' != 0"
# build the greatest common divisor of numerator and denominator.
a : Union[str, Any] = gcd(abs(UpperCamelCase__ ) , abs(UpperCamelCase__ ) )
# precondition
assert (
isinstance(UpperCamelCase__ , UpperCamelCase__ )
and (numerator % gcd_of_fraction == 0)
and (denominator % gcd_of_fraction == 0)
), "Error in function gcd(...,...)"
return (numerator // gcd_of_fraction, denominator // gcd_of_fraction)
def A_ ( UpperCAmelCase__ ) -> int:
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ) and (n >= 0), "'n' must been a int and >= 0"
a : int = 1 # this will be return.
for factor in range(1 , n + 1 ):
ans *= factor
return ans
def A_ ( UpperCAmelCase__ ) -> str:
assert isinstance(UpperCamelCase__ , UpperCamelCase__ ) and (n >= 0), "'n' must been an int and >= 0"
a : int = 0
a : List[Any] = 1
a : Optional[int] = 1 # this will be return
for _ in range(n - 1 ):
a : Union[str, Any] = ans
ans += fiba
a : Optional[Any] = tmp
return ans
| 703 |
"""simple docstring"""
from io import BytesIO
from typing import List, Union
import requests
from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_decord_available():
import numpy as np
from decord import VideoReader
if is_torch_available():
from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING
SCREAMING_SNAKE_CASE__ : Union[str, Any] = logging.get_logger(__name__)
@add_end_docstrings(_UpperCAmelCase )
class A_ ( _UpperCAmelCase ):
"""simple docstring"""
def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict:
super().__init__(*__UpperCAmelCase , **__UpperCAmelCase )
requires_backends(self , 'decord' )
self.check_model_type(__UpperCAmelCase )
def lowercase_ ( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=None ) -> List[str]:
a : List[str] = {}
if frame_sampling_rate is not None:
a : Tuple = frame_sampling_rate
if num_frames is not None:
a : List[Any] = num_frames
a : Optional[int] = {}
if top_k is not None:
a : int = top_k
return preprocess_params, {}, postprocess_params
def __call__( self , __UpperCAmelCase , **__UpperCAmelCase ) -> Any:
return super().__call__(__UpperCAmelCase , **__UpperCAmelCase )
def lowercase_ ( self , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=1 ) -> Dict:
if num_frames is None:
a : int = self.model.config.num_frames
if video.startswith('http://' ) or video.startswith('https://' ):
a : int = BytesIO(requests.get(__UpperCAmelCase ).content )
a : Optional[Any] = VideoReader(__UpperCAmelCase )
videoreader.seek(0 )
a : Tuple = 0
a : Dict = num_frames * frame_sampling_rate - 1
a : Optional[Any] = np.linspace(__UpperCAmelCase , __UpperCAmelCase , num=__UpperCAmelCase , dtype=np.intaa )
a : str = videoreader.get_batch(__UpperCAmelCase ).asnumpy()
a : Dict = list(__UpperCAmelCase )
a : Tuple = self.image_processor(__UpperCAmelCase , return_tensors=self.framework )
return model_inputs
def lowercase_ ( self , __UpperCAmelCase ) -> Union[str, Any]:
a : Union[str, Any] = self.model(**__UpperCAmelCase )
return model_outputs
def lowercase_ ( self , __UpperCAmelCase , __UpperCAmelCase=5 ) -> Union[str, Any]:
if top_k > self.model.config.num_labels:
a : Union[str, Any] = self.model.config.num_labels
if self.framework == "pt":
a : List[Any] = model_outputs.logits.softmax(-1 )[0]
a , a : Union[str, Any] = probs.topk(__UpperCAmelCase )
else:
raise ValueError(f'Unsupported framework: {self.framework}' )
a : Tuple = scores.tolist()
a : Any = ids.tolist()
return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(__UpperCAmelCase , __UpperCAmelCase )]
| 509 | 0 |
"""simple docstring"""
from ..utils import DummyObject, requires_backends
class _snake_case ( metaclass=A_ ):
snake_case__ = ['''flax''', '''transformers''']
def __init__( self : str , *UpperCAmelCase : List[str] , **UpperCAmelCase : List[Any] ):
requires_backends(self , ["flax", "transformers"] )
@classmethod
def lowerCamelCase__ ( cls : Optional[Any] , *UpperCAmelCase : List[Any] , **UpperCAmelCase : List[str] ):
requires_backends(cls , ["flax", "transformers"] )
@classmethod
def lowerCamelCase__ ( cls : List[Any] , *UpperCAmelCase : Dict , **UpperCAmelCase : Dict ):
requires_backends(cls , ["flax", "transformers"] )
class _snake_case ( metaclass=A_ ):
snake_case__ = ['''flax''', '''transformers''']
def __init__( self : List[str] , *UpperCAmelCase : Any , **UpperCAmelCase : List[str] ):
requires_backends(self , ["flax", "transformers"] )
@classmethod
def lowerCamelCase__ ( cls : str , *UpperCAmelCase : Tuple , **UpperCAmelCase : Dict ):
requires_backends(cls , ["flax", "transformers"] )
@classmethod
def lowerCamelCase__ ( cls : Union[str, Any] , *UpperCAmelCase : Optional[int] , **UpperCAmelCase : Tuple ):
requires_backends(cls , ["flax", "transformers"] )
class _snake_case ( metaclass=A_ ):
snake_case__ = ['''flax''', '''transformers''']
def __init__( self : str , *UpperCAmelCase : List[str] , **UpperCAmelCase : Dict ):
requires_backends(self , ["flax", "transformers"] )
@classmethod
def lowerCamelCase__ ( cls : int , *UpperCAmelCase : List[str] , **UpperCAmelCase : Tuple ):
requires_backends(cls , ["flax", "transformers"] )
@classmethod
def lowerCamelCase__ ( cls : Tuple , *UpperCAmelCase : Union[str, Any] , **UpperCAmelCase : List[str] ):
requires_backends(cls , ["flax", "transformers"] )
class _snake_case ( metaclass=A_ ):
snake_case__ = ['''flax''', '''transformers''']
def __init__( self : Tuple , *UpperCAmelCase : str , **UpperCAmelCase : Union[str, Any] ):
requires_backends(self , ["flax", "transformers"] )
@classmethod
def lowerCamelCase__ ( cls : Tuple , *UpperCAmelCase : Union[str, Any] , **UpperCAmelCase : Union[str, Any] ):
requires_backends(cls , ["flax", "transformers"] )
@classmethod
def lowerCamelCase__ ( cls : Dict , *UpperCAmelCase : str , **UpperCAmelCase : str ):
requires_backends(cls , ["flax", "transformers"] ) | 646 |
# Lint as: python3
import itertools
import os
import re
_lowercase = re.compile(r'''([A-Z]+)([A-Z][a-z])''')
_lowercase = re.compile(r'''([a-z\d])([A-Z])''')
_lowercase = re.compile(r'''(?<!_)_(?!_)''')
_lowercase = re.compile(r'''(_{2,})''')
_lowercase = r'''^\w+(\.\w+)*$'''
_lowercase = r'''<>:/\|?*'''
def _A (UpperCamelCase : str ) ->str:
'''simple docstring'''
lowerCamelCase__ : List[str] = _uppercase_uppercase_re.sub(r"""\1_\2""" , UpperCamelCase )
lowerCamelCase__ : Optional[int] = _lowercase_uppercase_re.sub(r"""\1_\2""" , UpperCamelCase )
return name.lower()
def _A (UpperCamelCase : Union[str, Any] ) ->int:
'''simple docstring'''
lowerCamelCase__ : Optional[int] = _single_underscore_re.split(UpperCamelCase )
lowerCamelCase__ : int = [_multiple_underscores_re.split(UpperCamelCase ) for n in name]
return "".join(n.capitalize() for n in itertools.chain.from_iterable(UpperCamelCase ) if n != """""" )
def _A (UpperCamelCase : Any ) ->Optional[Any]:
'''simple docstring'''
if os.path.basename(UpperCamelCase ) != name:
raise ValueError(f"Should be a dataset name, not a path: {name}" )
return camelcase_to_snakecase(UpperCamelCase )
def _A (UpperCamelCase : int , UpperCamelCase : Dict ) ->List[Any]:
'''simple docstring'''
if os.path.basename(UpperCamelCase ) != name:
raise ValueError(f"Should be a dataset name, not a path: {name}" )
if not re.match(_split_re , UpperCamelCase ):
raise ValueError(f"Split name should match '{_split_re}'' but got '{split}'." )
return f"{filename_prefix_for_name(UpperCamelCase )}-{split}"
def _A (UpperCamelCase : int , UpperCamelCase : Tuple , UpperCamelCase : List[str] , UpperCamelCase : Optional[int]=None ) ->List[Any]:
'''simple docstring'''
lowerCamelCase__ : Any = filename_prefix_for_split(UpperCamelCase , UpperCamelCase )
if filetype_suffix:
prefix += f".{filetype_suffix}"
lowerCamelCase__ : List[Any] = os.path.join(UpperCamelCase , UpperCamelCase )
return f"{filepath}*"
def _A (UpperCamelCase : Optional[Any] , UpperCamelCase : Optional[int] , UpperCamelCase : Optional[int] , UpperCamelCase : Optional[int]=None , UpperCamelCase : Dict=None ) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__ : List[Any] = filename_prefix_for_split(UpperCamelCase , UpperCamelCase )
lowerCamelCase__ : Tuple = os.path.join(UpperCamelCase , UpperCamelCase )
if shard_lengths:
lowerCamelCase__ : Optional[int] = len(UpperCamelCase )
lowerCamelCase__ : List[Any] = [f"{prefix}-{shard_id:05d}-of-{num_shards:05d}" for shard_id in range(UpperCamelCase )]
if filetype_suffix:
lowerCamelCase__ : Tuple = [filename + f".{filetype_suffix}" for filename in filenames]
return filenames
else:
lowerCamelCase__ : List[str] = prefix
if filetype_suffix:
filename += f".{filetype_suffix}"
return [filename]
| 157 | 0 |
'''simple docstring'''
import json
import sys
import tempfile
import unittest
from pathlib import Path
import transformers
from transformers import (
CONFIG_MAPPING,
IMAGE_PROCESSOR_MAPPING,
AutoConfig,
AutoImageProcessor,
CLIPConfig,
CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER
sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils"""))
from test_module.custom_configuration import CustomConfig # noqa E402
from test_module.custom_image_processing import CustomImageProcessor # noqa E402
class __UpperCamelCase ( unittest.TestCase ):
def __A ( self : Optional[int] ):
'''simple docstring'''
UpperCAmelCase_ = 0
def __A ( self : Tuple ):
'''simple docstring'''
UpperCAmelCase_ = AutoImageProcessor.from_pretrained("openai/clip-vit-base-patch32" )
self.assertIsInstance(lowerCAmelCase , lowerCAmelCase )
def __A ( self : int ):
'''simple docstring'''
with tempfile.TemporaryDirectory() as tmpdirname:
UpperCAmelCase_ = Path(lowerCAmelCase ) / "preprocessor_config.json"
UpperCAmelCase_ = Path(lowerCAmelCase ) / "config.json"
json.dump(
{"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(lowerCAmelCase , "w" ) , )
json.dump({"model_type": "clip"} , open(lowerCAmelCase , "w" ) )
UpperCAmelCase_ = AutoImageProcessor.from_pretrained(lowerCAmelCase )
self.assertIsInstance(lowerCAmelCase , lowerCAmelCase )
def __A ( self : Optional[int] ):
'''simple docstring'''
with tempfile.TemporaryDirectory() as tmpdirname:
UpperCAmelCase_ = Path(lowerCAmelCase ) / "preprocessor_config.json"
UpperCAmelCase_ = Path(lowerCAmelCase ) / "config.json"
json.dump(
{"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} , open(lowerCAmelCase , "w" ) , )
json.dump({"model_type": "clip"} , open(lowerCAmelCase , "w" ) )
UpperCAmelCase_ = AutoImageProcessor.from_pretrained(lowerCAmelCase )
self.assertIsInstance(lowerCAmelCase , lowerCAmelCase )
def __A ( self : Any ):
'''simple docstring'''
with tempfile.TemporaryDirectory() as tmpdirname:
UpperCAmelCase_ = CLIPConfig()
# Create a dummy config file with image_proceesor_type
UpperCAmelCase_ = Path(lowerCAmelCase ) / "preprocessor_config.json"
UpperCAmelCase_ = Path(lowerCAmelCase ) / "config.json"
json.dump(
{"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(lowerCAmelCase , "w" ) , )
json.dump({"model_type": "clip"} , open(lowerCAmelCase , "w" ) )
# remove image_processor_type to make sure config.json alone is enough to load image processor locally
UpperCAmelCase_ = AutoImageProcessor.from_pretrained(lowerCAmelCase ).to_dict()
config_dict.pop("image_processor_type" )
UpperCAmelCase_ = CLIPImageProcessor(**lowerCAmelCase )
# save in new folder
model_config.save_pretrained(lowerCAmelCase )
config.save_pretrained(lowerCAmelCase )
UpperCAmelCase_ = AutoImageProcessor.from_pretrained(lowerCAmelCase )
# make sure private variable is not incorrectly saved
UpperCAmelCase_ = json.loads(config.to_json_string() )
self.assertTrue("_processor_class" not in dict_as_saved )
self.assertIsInstance(lowerCAmelCase , lowerCAmelCase )
def __A ( self : int ):
'''simple docstring'''
with tempfile.TemporaryDirectory() as tmpdirname:
UpperCAmelCase_ = Path(lowerCAmelCase ) / "preprocessor_config.json"
json.dump(
{"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(lowerCAmelCase , "w" ) , )
UpperCAmelCase_ = AutoImageProcessor.from_pretrained(lowerCAmelCase )
self.assertIsInstance(lowerCAmelCase , lowerCAmelCase )
def __A ( self : Tuple ):
'''simple docstring'''
with self.assertRaisesRegex(
lowerCAmelCase , "clip-base is not a local folder and is not a valid model identifier" ):
UpperCAmelCase_ = AutoImageProcessor.from_pretrained("clip-base" )
def __A ( self : Dict ):
'''simple docstring'''
with self.assertRaisesRegex(
lowerCAmelCase , R"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ):
UpperCAmelCase_ = AutoImageProcessor.from_pretrained(lowerCAmelCase , revision="aaaaaa" )
def __A ( self : Dict ):
'''simple docstring'''
with self.assertRaisesRegex(
lowerCAmelCase , "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json." , ):
UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/config-no-model" )
def __A ( self : int ):
'''simple docstring'''
with self.assertRaises(lowerCAmelCase ):
UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" )
# If remote code is disabled, we can't load this config.
with self.assertRaises(lowerCAmelCase ):
UpperCAmelCase_ = AutoImageProcessor.from_pretrained(
"hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=lowerCAmelCase )
UpperCAmelCase_ = AutoImageProcessor.from_pretrained(
"hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=lowerCAmelCase )
self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" )
# Test image processor can be reloaded.
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(lowerCAmelCase )
UpperCAmelCase_ = AutoImageProcessor.from_pretrained(lowerCAmelCase , trust_remote_code=lowerCAmelCase )
self.assertEqual(reloaded_image_processor.__class__.__name__ , "NewImageProcessor" )
def __A ( self : Optional[Any] ):
'''simple docstring'''
try:
AutoConfig.register("custom" , lowerCAmelCase )
AutoImageProcessor.register(lowerCAmelCase , lowerCAmelCase )
# Trying to register something existing in the Transformers library will raise an error
with self.assertRaises(lowerCAmelCase ):
AutoImageProcessor.register(lowerCAmelCase , lowerCAmelCase )
with tempfile.TemporaryDirectory() as tmpdirname:
UpperCAmelCase_ = Path(lowerCAmelCase ) / "preprocessor_config.json"
UpperCAmelCase_ = Path(lowerCAmelCase ) / "config.json"
json.dump(
{"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} , open(lowerCAmelCase , "w" ) , )
json.dump({"model_type": "clip"} , open(lowerCAmelCase , "w" ) )
UpperCAmelCase_ = CustomImageProcessor.from_pretrained(lowerCAmelCase )
# Now that the config is registered, it can be used as any other config with the auto-API
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(lowerCAmelCase )
UpperCAmelCase_ = AutoImageProcessor.from_pretrained(lowerCAmelCase )
self.assertIsInstance(lowerCAmelCase , lowerCAmelCase )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
def __A ( self : Optional[Any] ):
'''simple docstring'''
class __UpperCamelCase ( lowercase ):
SCREAMING_SNAKE_CASE__ = True
try:
AutoConfig.register("custom" , lowerCAmelCase )
AutoImageProcessor.register(lowerCAmelCase , lowerCAmelCase )
# If remote code is not set, the default is to use local
UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" )
self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" )
self.assertTrue(image_processor.is_local )
# If remote code is disabled, we load the local one.
UpperCAmelCase_ = AutoImageProcessor.from_pretrained(
"hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=lowerCAmelCase )
self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" )
self.assertTrue(image_processor.is_local )
# If remote is enabled, we load from the Hub
UpperCAmelCase_ = AutoImageProcessor.from_pretrained(
"hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=lowerCAmelCase )
self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" )
self.assertTrue(not hasattr(lowerCAmelCase , "is_local" ) )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] | 708 |
import gzip
import hashlib
import json
import multiprocessing
import os
import re
import shutil
import time
from pathlib import Path
import numpy as np
from arguments import PreprocessingArguments
from datasets import load_dataset
from minhash_deduplication import deduplicate_dataset
from transformers import AutoTokenizer, HfArgumentParser
_a: Optional[int] = re.compile(r"""\s+""")
def __lowerCAmelCase ( A ):
return {"hash": hashlib.mda(re.sub(A , "" , example["content"] ).encode("utf-8" ) ).hexdigest()}
def __lowerCAmelCase ( A ):
UpperCAmelCase_ = [len(A ) for line in example["content"].splitlines()]
return {"line_mean": np.mean(A ), "line_max": max(A )}
def __lowerCAmelCase ( A ):
UpperCAmelCase_ = np.mean([c.isalnum() for c in example["content"]] )
return {"alpha_frac": alpha_frac}
def __lowerCAmelCase ( A , A ):
if example["hash"] in uniques:
uniques.remove(example["hash"] )
return True
else:
return False
def __lowerCAmelCase ( A , A=5 ):
UpperCAmelCase_ = ["auto-generated", "autogenerated", "automatically generated"]
UpperCAmelCase_ = example["content"].splitlines()
for _, line in zip(range(A ) , A ):
for keyword in keywords:
if keyword in line.lower():
return {"autogenerated": True}
else:
return {"autogenerated": False}
def __lowerCAmelCase ( A , A=5 , A=0.05 ):
UpperCAmelCase_ = ["unit tests", "test file", "configuration file"]
UpperCAmelCase_ = example["content"].splitlines()
UpperCAmelCase_ = 0
UpperCAmelCase_ = 0
# first test
for _, line in zip(range(A ) , A ):
for keyword in keywords:
if keyword in line.lower():
return {"config_or_test": True}
# second test
UpperCAmelCase_ = example["content"].count("\n" )
UpperCAmelCase_ = int(coeff * nlines )
for line in lines:
count_config += line.lower().count("config" )
count_test += line.lower().count("test" )
if count_config > threshold or count_test > threshold:
return {"config_or_test": True}
return {"config_or_test": False}
def __lowerCAmelCase ( A ):
UpperCAmelCase_ = ["def ", "class ", "for ", "while "]
UpperCAmelCase_ = example["content"].splitlines()
for line in lines:
for keyword in keywords:
if keyword in line.lower():
return {"has_no_keywords": False}
return {"has_no_keywords": True}
def __lowerCAmelCase ( A , A=4 ):
UpperCAmelCase_ = example["content"].splitlines()
UpperCAmelCase_ = 0
for line in lines:
counter += line.lower().count("=" )
if counter > minimum:
return {"has_few_assignments": False}
return {"has_few_assignments": True}
def __lowerCAmelCase ( A ):
UpperCAmelCase_ = tokenizer(example["content"] , truncation=A )["input_ids"]
UpperCAmelCase_ = len(example["content"] ) / len(A )
return {"ratio": ratio}
def __lowerCAmelCase ( A ):
UpperCAmelCase_ = {}
results.update(get_hash(A ) )
results.update(line_stats(A ) )
results.update(alpha_stats(A ) )
results.update(char_token_ratio(A ) )
results.update(is_autogenerated(A ) )
results.update(is_config_or_test(A ) )
results.update(has_no_keywords(A ) )
results.update(has_few_assignments(A ) )
return results
def __lowerCAmelCase ( A , A , A ):
if not check_uniques(A , A ):
return False
elif example["autogenerated"]:
return False
elif example["line_max"] > args.line_max:
return False
elif example["line_mean"] > args.line_mean:
return False
elif example["alpha_frac"] < args.alpha_frac:
return False
elif example["ratio"] < args.min_token_ratio:
return False
elif example["config_or_test"] and np.random.rand() <= args.filter_proba:
return False
elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba:
return False
elif example["has_few_assignments"]:
return False
else:
return True
def __lowerCAmelCase ( A ):
with open(A , "rb" ) as f_in:
with gzip.open(str(A ) + ".gz" , "wb" , compresslevel=6 ) as f_out:
shutil.copyfileobj(A , A )
os.unlink(A )
# Settings
_a: str = HfArgumentParser(PreprocessingArguments)
_a: Any = parser.parse_args()
if args.num_workers is None:
_a: Tuple = multiprocessing.cpu_count()
_a: str = AutoTokenizer.from_pretrained(args.tokenizer_dir)
# Load dataset
_a: Union[str, Any] = time.time()
_a: List[str] = load_dataset(args.dataset_name, split="""train""")
print(F'Time to load dataset: {time.time()-t_start:.2f}')
# Run preprocessing
_a: List[str] = time.time()
_a: List[Any] = ds.map(preprocess, num_proc=args.num_workers)
print(F'Time to preprocess dataset: {time.time()-t_start:.2f}')
# Deduplicate hashes
_a: Union[str, Any] = set(ds.unique("""hash"""))
_a: Dict = len(uniques) / len(ds)
print(F'Fraction of duplicates: {1-frac:.2%}')
# Deduplicate data and apply heuristics
_a: Optional[Any] = time.time()
_a: Any = ds.filter(filter, fn_kwargs={"""uniques""": uniques, """args""": args})
print(F'Time to filter dataset: {time.time()-t_start:.2f}')
print(F'Size of filtered dataset: {len(ds_filter)}')
# Deduplicate with minhash and jaccard similarity
if args.near_deduplication:
_a: Tuple = time.time()
_a , _a: Dict = deduplicate_dataset(ds_filter, args.jaccard_threshold)
print(F'Time to deduplicate dataset: {time.time()-t_start:.2f}')
print(F'Size of deduplicate dataset: {len(ds_filter)}')
# Save data in batches of samples_per_file
_a: List[str] = Path(args.output_dir)
output_dir.mkdir(exist_ok=True)
# save duplicate_clusters in the output_dir as artifacts
# not sure it is the right place the save it
if args.near_deduplication:
with open(output_dir / """duplicate_clusters.json""", """w""") as f:
json.dump(duplicate_clusters, f)
_a: int = output_dir / """data"""
data_dir.mkdir(exist_ok=True)
_a: Dict = time.time()
for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)):
_a: int = str(data_dir / F'file-{file_number+1:012}.json')
_a: int = min(len(ds_filter), index + args.samples_per_file)
ds_filter.select(list(range(index, end_index))).to_json(file_path)
compress_file(file_path)
print(F'Time to save dataset: {time.time()-t_start:.2f}') | 268 | 0 |
'''simple docstring'''
from arguments import InitializationArguments
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, HfArgumentParser
# Configuration
_UpperCamelCase = HfArgumentParser(InitializationArguments)
_UpperCamelCase = parser.parse_args()
# Load codeparrot tokenizer trained for Python code tokenization
_UpperCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name)
# Config: "scale_attn_by_layer_idx" and "reorder_and_upcast_attn" are Mistral stability tweaks
_UpperCamelCase = {
'vocab_size': len(tokenizer),
'scale_attn_by_inverse_layer_idx': True,
'reorder_and_upcast_attn': True,
}
# Load model config (GPT-2 large in this case)
_UpperCamelCase = AutoConfig.from_pretrained(args.config_name, **config_kwargs)
# Initialize new model with config
_UpperCamelCase = AutoModelForCausalLM.from_config(config)
# Save model to the hub
model.save_pretrained(args.model_name, push_to_hub=args.push_to_hub)
| 459 |
'''simple docstring'''
import os
import tempfile
import unittest
from transformers import NezhaConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
MODEL_FOR_PRETRAINING_MAPPING,
NezhaForMaskedLM,
NezhaForMultipleChoice,
NezhaForNextSentencePrediction,
NezhaForPreTraining,
NezhaForQuestionAnswering,
NezhaForSequenceClassification,
NezhaForTokenClassification,
NezhaModel,
)
from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST
class lowerCamelCase_ :
"""simple docstring"""
def __init__( self : str , _a : Dict , _a : List[str]=13 , _a : List[str]=7 , _a : Union[str, Any]=True , _a : List[Any]=True , _a : Optional[Any]=True , _a : Any=True , _a : Optional[Any]=99 , _a : List[str]=32 , _a : Optional[Any]=5 , _a : str=4 , _a : str=37 , _a : List[Any]="gelu" , _a : List[Any]=0.1 , _a : Optional[int]=0.1 , _a : Optional[Any]=128 , _a : Tuple=32 , _a : List[Any]=16 , _a : Optional[int]=2 , _a : List[str]=0.02 , _a : List[str]=3 , _a : Any=4 , _a : List[str]=None , ) -> Any:
__lowerCamelCase : Optional[Any] = parent
__lowerCamelCase : Optional[int] = batch_size
__lowerCamelCase : List[str] = seq_length
__lowerCamelCase : List[str] = is_training
__lowerCamelCase : Dict = use_input_mask
__lowerCamelCase : Optional[int] = use_token_type_ids
__lowerCamelCase : Union[str, Any] = use_labels
__lowerCamelCase : Tuple = vocab_size
__lowerCamelCase : Any = hidden_size
__lowerCamelCase : Tuple = num_hidden_layers
__lowerCamelCase : List[str] = num_attention_heads
__lowerCamelCase : str = intermediate_size
__lowerCamelCase : Tuple = hidden_act
__lowerCamelCase : List[str] = hidden_dropout_prob
__lowerCamelCase : List[Any] = attention_probs_dropout_prob
__lowerCamelCase : List[str] = max_position_embeddings
__lowerCamelCase : str = type_vocab_size
__lowerCamelCase : Optional[Any] = type_sequence_label_size
__lowerCamelCase : Optional[Any] = initializer_range
__lowerCamelCase : Tuple = num_labels
__lowerCamelCase : Tuple = num_choices
__lowerCamelCase : Optional[int] = scope
def _lowercase ( self : Optional[int] ) -> Dict:
__lowerCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__lowerCamelCase : Optional[int] = None
if self.use_input_mask:
__lowerCamelCase : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] )
__lowerCamelCase : Tuple = None
if self.use_token_type_ids:
__lowerCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
__lowerCamelCase : Optional[int] = None
__lowerCamelCase : Union[str, Any] = None
__lowerCamelCase : List[str] = None
if self.use_labels:
__lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__lowerCamelCase : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__lowerCamelCase : Any = ids_tensor([self.batch_size] , self.num_choices )
__lowerCamelCase : List[Any] = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def _lowercase ( self : List[str] ) -> int:
return NezhaConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , )
def _lowercase ( self : Tuple ) -> Optional[Any]:
(
(
__lowerCamelCase
) ,(
__lowerCamelCase
) ,(
__lowerCamelCase
) ,(
__lowerCamelCase
) ,(
__lowerCamelCase
) ,(
__lowerCamelCase
) ,(
__lowerCamelCase
) ,
) : List[Any] = self.prepare_config_and_inputs()
__lowerCamelCase : Optional[Any] = True
__lowerCamelCase : Optional[int] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] )
__lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 )
return (
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
)
def _lowercase ( self : Optional[int] , _a : List[Any] , _a : Dict , _a : Union[str, Any] , _a : Tuple , _a : Tuple , _a : Dict , _a : Any ) -> Tuple:
__lowerCamelCase : List[Any] = NezhaModel(config=_a )
model.to(_a )
model.eval()
__lowerCamelCase : Any = model(_a , attention_mask=_a , token_type_ids=_a )
__lowerCamelCase : int = model(_a , token_type_ids=_a )
__lowerCamelCase : Optional[Any] = 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 _lowercase ( self : Optional[Any] , _a : List[str] , _a : Dict , _a : Optional[Any] , _a : int , _a : List[str] , _a : Optional[int] , _a : List[str] , _a : Optional[int] , _a : Any , ) -> Dict:
__lowerCamelCase : Optional[Any] = True
__lowerCamelCase : Union[str, Any] = NezhaModel(_a )
model.to(_a )
model.eval()
__lowerCamelCase : Any = model(
_a , attention_mask=_a , token_type_ids=_a , encoder_hidden_states=_a , encoder_attention_mask=_a , )
__lowerCamelCase : Tuple = model(
_a , attention_mask=_a , token_type_ids=_a , encoder_hidden_states=_a , )
__lowerCamelCase : str = model(_a , attention_mask=_a , token_type_ids=_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 _lowercase ( self : Union[str, Any] , _a : Optional[int] , _a : int , _a : Optional[Any] , _a : Any , _a : Tuple , _a : Optional[int] , _a : int ) -> List[Any]:
__lowerCamelCase : int = NezhaForMaskedLM(config=_a )
model.to(_a )
model.eval()
__lowerCamelCase : Optional[Any] = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def _lowercase ( self : int , _a : Tuple , _a : List[Any] , _a : Any , _a : Optional[Any] , _a : Dict , _a : Dict , _a : List[Any] ) -> str:
__lowerCamelCase : str = NezhaForNextSentencePrediction(config=_a )
model.to(_a )
model.eval()
__lowerCamelCase : str = model(
_a , attention_mask=_a , token_type_ids=_a , labels=_a , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) )
def _lowercase ( self : Any , _a : List[str] , _a : str , _a : List[Any] , _a : str , _a : Union[str, Any] , _a : int , _a : Tuple ) -> Dict:
__lowerCamelCase : List[str] = NezhaForPreTraining(config=_a )
model.to(_a )
model.eval()
__lowerCamelCase : Optional[int] = model(
_a , attention_mask=_a , token_type_ids=_a , labels=_a , next_sentence_label=_a , )
self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) )
def _lowercase ( self : int , _a : Dict , _a : Any , _a : Any , _a : Tuple , _a : List[str] , _a : Any , _a : List[Any] ) -> List[Any]:
__lowerCamelCase : Any = NezhaForQuestionAnswering(config=_a )
model.to(_a )
model.eval()
__lowerCamelCase : List[Any] = model(
_a , attention_mask=_a , token_type_ids=_a , start_positions=_a , end_positions=_a , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def _lowercase ( self : Optional[int] , _a : str , _a : Tuple , _a : List[str] , _a : List[str] , _a : Any , _a : str , _a : Union[str, Any] ) -> int:
__lowerCamelCase : Optional[int] = self.num_labels
__lowerCamelCase : List[str] = NezhaForSequenceClassification(_a )
model.to(_a )
model.eval()
__lowerCamelCase : Any = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def _lowercase ( self : List[Any] , _a : List[Any] , _a : str , _a : Tuple , _a : Dict , _a : Dict , _a : Union[str, Any] , _a : List[Any] ) -> int:
__lowerCamelCase : int = self.num_labels
__lowerCamelCase : int = NezhaForTokenClassification(config=_a )
model.to(_a )
model.eval()
__lowerCamelCase : List[str] = model(_a , attention_mask=_a , token_type_ids=_a , labels=_a )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def _lowercase ( self : List[str] , _a : Any , _a : List[str] , _a : Tuple , _a : Optional[Any] , _a : Optional[Any] , _a : str , _a : Optional[Any] ) -> int:
__lowerCamelCase : List[Any] = self.num_choices
__lowerCamelCase : Optional[Any] = NezhaForMultipleChoice(config=_a )
model.to(_a )
model.eval()
__lowerCamelCase : Optional[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__lowerCamelCase : Any = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__lowerCamelCase : List[str] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__lowerCamelCase : str = model(
_a , attention_mask=_a , token_type_ids=_a , labels=_a , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def _lowercase ( self : List[str] ) -> Any:
__lowerCamelCase : Optional[Any] = self.prepare_config_and_inputs()
(
(
__lowerCamelCase
) ,(
__lowerCamelCase
) ,(
__lowerCamelCase
) ,(
__lowerCamelCase
) ,(
__lowerCamelCase
) ,(
__lowerCamelCase
) ,(
__lowerCamelCase
) ,
) : Optional[int] = config_and_inputs
__lowerCamelCase : List[Any] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
return config, inputs_dict
@require_torch
class lowerCamelCase_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ):
"""simple docstring"""
a_ =(
(
NezhaModel,
NezhaForMaskedLM,
NezhaForMultipleChoice,
NezhaForNextSentencePrediction,
NezhaForPreTraining,
NezhaForQuestionAnswering,
NezhaForSequenceClassification,
NezhaForTokenClassification,
)
if is_torch_available()
else ()
)
a_ =(
{
"""feature-extraction""": NezhaModel,
"""fill-mask""": NezhaForMaskedLM,
"""question-answering""": NezhaForQuestionAnswering,
"""text-classification""": NezhaForSequenceClassification,
"""token-classification""": NezhaForTokenClassification,
"""zero-shot""": NezhaForSequenceClassification,
}
if is_torch_available()
else {}
)
a_ =True
def _lowercase ( self : List[str] , _a : Union[str, Any] , _a : Any , _a : List[Any]=False ) -> Optional[Any]:
__lowerCamelCase : List[str] = super()._prepare_for_class(_a , _a , return_labels=_a )
if return_labels:
if model_class in get_values(_a ):
__lowerCamelCase : Tuple = torch.zeros(
(self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=_a )
__lowerCamelCase : List[Any] = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=_a )
return inputs_dict
def _lowercase ( self : Optional[int] ) -> Any:
__lowerCamelCase : Dict = NezhaModelTester(self )
__lowerCamelCase : int = ConfigTester(self , config_class=_a , hidden_size=37 )
def _lowercase ( self : Optional[Any] ) -> List[Any]:
self.config_tester.run_common_tests()
def _lowercase ( self : int ) -> List[str]:
__lowerCamelCase : str = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_a )
def _lowercase ( self : Optional[Any] ) -> Union[str, Any]:
__lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_model_as_decoder(*_a )
def _lowercase ( self : str ) -> Any:
# This regression test was failing with PyTorch < 1.3
(
(
__lowerCamelCase
) ,(
__lowerCamelCase
) ,(
__lowerCamelCase
) ,(
__lowerCamelCase
) ,(
__lowerCamelCase
) ,(
__lowerCamelCase
) ,(
__lowerCamelCase
) ,(
__lowerCamelCase
) ,(
__lowerCamelCase
) ,
) : str = self.model_tester.prepare_config_and_inputs_for_decoder()
__lowerCamelCase : Dict = None
self.model_tester.create_and_check_model_as_decoder(
_a , _a , _a , _a , _a , _a , _a , _a , _a , )
def _lowercase ( self : int ) -> Tuple:
__lowerCamelCase : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*_a )
def _lowercase ( self : str ) -> str:
__lowerCamelCase : str = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*_a )
def _lowercase ( self : List[str] ) -> int:
__lowerCamelCase : int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_next_sequence_prediction(*_a )
def _lowercase ( self : Any ) -> Any:
__lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_pretraining(*_a )
def _lowercase ( self : Union[str, Any] ) -> Optional[int]:
__lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*_a )
def _lowercase ( self : Optional[int] ) -> str:
__lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*_a )
def _lowercase ( self : Dict ) -> Any:
__lowerCamelCase : str = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*_a )
@slow
def _lowercase ( self : Optional[Any] ) -> Union[str, Any]:
for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__lowerCamelCase : List[str] = NezhaModel.from_pretrained(_a )
self.assertIsNotNone(_a )
@slow
@require_torch_gpu
def _lowercase ( self : List[Any] ) -> str:
__lowerCamelCase ,__lowerCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
# NezhaForMultipleChoice behaves incorrectly in JIT environments.
if model_class == NezhaForMultipleChoice:
return
__lowerCamelCase : List[str] = True
__lowerCamelCase : Dict = model_class(config=_a )
__lowerCamelCase : List[str] = self._prepare_for_class(_a , _a )
__lowerCamelCase : Dict = torch.jit.trace(
_a , (inputs_dict['input_ids'].to('cpu' ), inputs_dict['attention_mask'].to('cpu' )) )
with tempfile.TemporaryDirectory() as tmp:
torch.jit.save(_a , os.path.join(_a , 'bert.pt' ) )
__lowerCamelCase : int = torch.jit.load(os.path.join(_a , 'bert.pt' ) , map_location=_a )
loaded(inputs_dict['input_ids'].to(_a ) , inputs_dict['attention_mask'].to(_a ) )
@require_torch
class lowerCamelCase_ ( unittest.TestCase ):
"""simple docstring"""
@slow
def _lowercase ( self : Dict ) -> Optional[int]:
__lowerCamelCase : Dict = NezhaModel.from_pretrained('sijunhe/nezha-cn-base' )
__lowerCamelCase : int = torch.tensor([[0, 1, 2, 3, 4, 5]] )
__lowerCamelCase : Dict = torch.tensor([[0, 1, 1, 1, 1, 1]] )
with torch.no_grad():
__lowerCamelCase : Tuple = model(_a , attention_mask=_a )[0]
__lowerCamelCase : Optional[int] = torch.Size((1, 6, 768) )
self.assertEqual(output.shape , _a )
__lowerCamelCase : Union[str, Any] = torch.tensor([[[0.0685, 0.2441, 0.1102], [0.0600, 0.1906, 0.1349], [0.0221, 0.0819, 0.0586]]] )
self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _a , atol=1e-4 ) )
@slow
def _lowercase ( self : Dict ) -> Dict:
__lowerCamelCase : Dict = NezhaForMaskedLM.from_pretrained('sijunhe/nezha-cn-base' )
__lowerCamelCase : Optional[Any] = torch.tensor([[0, 1, 2, 3, 4, 5]] )
__lowerCamelCase : List[str] = torch.tensor([[1, 1, 1, 1, 1, 1]] )
with torch.no_grad():
__lowerCamelCase : Union[str, Any] = model(_a , attention_mask=_a )[0]
__lowerCamelCase : Optional[Any] = torch.Size((1, 6, 2_1128) )
self.assertEqual(output.shape , _a )
__lowerCamelCase : Optional[Any] = torch.tensor(
[[-2.7939, -1.7902, -2.2189], [-2.8585, -1.8908, -2.3723], [-2.6499, -1.7750, -2.2558]] )
self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _a , atol=1e-4 ) )
| 459 | 1 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_torch_available,
)
SCREAMING_SNAKE_CASE__:Optional[int] = {"""configuration_vit_mae""": ["""VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ViTMAEConfig"""]}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE__:Union[str, Any] = [
"""VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""ViTMAEForPreTraining""",
"""ViTMAELayer""",
"""ViTMAEModel""",
"""ViTMAEPreTrainedModel""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE__:str = [
"""TFViTMAEForPreTraining""",
"""TFViTMAEModel""",
"""TFViTMAEPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_vit_mae import (
VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST,
ViTMAEForPreTraining,
ViTMAELayer,
ViTMAEModel,
ViTMAEPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel
else:
import sys
SCREAMING_SNAKE_CASE__:int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 67 | """simple docstring"""
import argparse
import logging
import sys
from unittest.mock import patch
import run_glue_deebert
from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow
logging.basicConfig(level=logging.DEBUG)
SCREAMING_SNAKE_CASE__:Dict = logging.getLogger()
def _lowerCamelCase( ):
__a = argparse.ArgumentParser()
parser.add_argument("-f" )
__a = parser.parse_args()
return args.f
class snake_case__ ( snake_case_ ):
def a__ ( self ):
__a = logging.StreamHandler(sys.stdout )
logger.addHandler(lowerCamelCase )
def a__ ( self , lowerCamelCase ):
__a = get_gpu_count()
if n_gpu > 1:
pass
# XXX: doesn't quite work with n_gpu > 1 https://github.com/huggingface/transformers/issues/10560
# script = f"{self.examples_dir_str}/research_projects/deebert/run_glue_deebert.py"
# distributed_args = f"-m torch.distributed.launch --nproc_per_node={n_gpu} {script}".split()
# cmd = [sys.executable] + distributed_args + args
# execute_subprocess_async(cmd, env=self.get_env())
# XXX: test the results - need to save them first into .json file
else:
args.insert(0 , "run_glue_deebert.py" )
with patch.object(lowerCamelCase , "argv" , lowerCamelCase ):
__a = run_glue_deebert.main()
for value in result.values():
self.assertGreaterEqual(lowerCamelCase , 0.666 )
@slow
@require_torch_non_multi_gpu
def a__ ( self ):
__a = "\n --model_type roberta\n --model_name_or_path roberta-base\n --task_name MRPC\n --do_train\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --max_seq_length 128\n --per_gpu_eval_batch_size=1\n --per_gpu_train_batch_size=8\n --learning_rate 2e-4\n --num_train_epochs 3\n --overwrite_output_dir\n --seed 42\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --save_steps 0\n --overwrite_cache\n --eval_after_first_stage\n ".split()
self.run_and_check(lowerCamelCase )
__a = "\n --model_type roberta\n --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --task_name MRPC\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --max_seq_length 128\n --eval_each_highway\n --eval_highway\n --overwrite_cache\n --per_gpu_eval_batch_size=1\n ".split()
self.run_and_check(lowerCamelCase )
__a = "\n --model_type roberta\n --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --task_name MRPC\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --max_seq_length 128\n --early_exit_entropy 0.1\n --eval_highway\n --overwrite_cache\n --per_gpu_eval_batch_size=1\n ".split()
self.run_and_check(lowerCamelCase )
| 67 | 1 |
from typing import List, Optional
import numpy as np
from ...processing_utils import ProcessorMixin
from ...utils import to_numpy
class lowerCAmelCase__ ( __lowerCamelCase ):
"""simple docstring"""
__UpperCAmelCase : Dict = '''EncodecFeatureExtractor'''
__UpperCAmelCase : Optional[Any] = ('''T5Tokenizer''', '''T5TokenizerFast''')
def __init__( self , a_ , a_ ):
super().__init__(a_ , a_ )
lowerCamelCase_ : int = self.feature_extractor
lowerCamelCase_ : Tuple = False
def _UpperCamelCase ( self , a_=None , a_=None , a_=True ):
return self.tokenizer.get_decoder_prompt_ids(task=a_ , language=a_ , no_timestamps=a_ )
def __call__( self , *a_ , **a_ ):
# For backward compatibility
if self._in_target_context_manager:
return self.current_processor(*a_ , **a_ )
lowerCamelCase_ : Union[str, Any] = kwargs.pop("audio" , a_ )
lowerCamelCase_ : Dict = kwargs.pop("sampling_rate" , a_ )
lowerCamelCase_ : List[str] = kwargs.pop("text" , a_ )
if len(a_ ) > 0:
lowerCamelCase_ : Dict = args[0]
lowerCamelCase_ : Any = 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:
lowerCamelCase_ : List[Any] = self.tokenizer(a_ , **a_ )
if audio is not None:
lowerCamelCase_ : Dict = self.feature_extractor(a_ , *a_ , sampling_rate=a_ , **a_ )
if audio is None:
return inputs
elif text is None:
return audio_inputs
else:
lowerCamelCase_ : Any = audio_inputs["input_values"]
if "padding_mask" in audio_inputs:
lowerCamelCase_ : List[Any] = audio_inputs["padding_mask"]
return inputs
def _UpperCamelCase ( self , *a_ , **a_ ):
lowerCamelCase_ : str = kwargs.pop("audio" , a_ )
lowerCamelCase_ : Dict = kwargs.pop("padding_mask" , a_ )
if len(a_ ) > 0:
lowerCamelCase_ : Optional[int] = args[0]
lowerCamelCase_ : List[Any] = 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_ ):
return self.tokenizer.decode(*a_ , **a_ )
def _UpperCamelCase ( self , a_ , a_ = None ):
lowerCamelCase_ : Any = to_numpy(a_ )
lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ : Optional[int] = audio_values.shape
if padding_mask is None:
return list(a_ )
lowerCamelCase_ : int = 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)
lowerCamelCase_ : Optional[Any] = seq_len - padding_mask.shape[-1]
lowerCamelCase_ : int = 1 - self.feature_extractor.padding_value
lowerCamelCase_ : Optional[int] = np.pad(a_ , ((0, 0), (0, difference)) , "constant" , constant_values=a_ )
lowerCamelCase_ : Optional[int] = audio_values.tolist()
for i in range(a_ ):
lowerCamelCase_ : Union[str, Any] = np.asarray(audio_values[i] )[
padding_mask[i][None, :] != self.feature_extractor.padding_value
]
lowerCamelCase_ : Optional[Any] = sliced_audio.reshape(a_ , -1 )
return audio_values
| 250 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
__magic_name__ = {
'''configuration_conditional_detr''': [
'''CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''ConditionalDetrConfig''',
'''ConditionalDetrOnnxConfig''',
]
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ = ['''ConditionalDetrFeatureExtractor''']
__magic_name__ = ['''ConditionalDetrImageProcessor''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ = [
'''CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''ConditionalDetrForObjectDetection''',
'''ConditionalDetrForSegmentation''',
'''ConditionalDetrModel''',
'''ConditionalDetrPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_conditional_detr import (
CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP,
ConditionalDetrConfig,
ConditionalDetrOnnxConfig,
)
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor
from .image_processing_conditional_detr import ConditionalDetrImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_conditional_detr import (
CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST,
ConditionalDetrForObjectDetection,
ConditionalDetrForSegmentation,
ConditionalDetrModel,
ConditionalDetrPreTrainedModel,
)
else:
import sys
__magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 250 | 1 |
import math
def UpperCamelCase ( __lowercase : list ,__lowercase : int ):
'''simple docstring'''
A_ : Dict = len(__lowercase )
A_ : List[str] = int(math.floor(math.sqrt(__lowercase ) ) )
A_ : int = 0
while arr[min(__lowercase ,__lowercase ) - 1] < x:
A_ : Optional[int] = step
step += int(math.floor(math.sqrt(__lowercase ) ) )
if prev >= n:
return -1
while arr[prev] < x:
A_ : Tuple = prev + 1
if prev == min(__lowercase ,__lowercase ):
return -1
if arr[prev] == x:
return prev
return -1
if __name__ == "__main__":
_UpperCAmelCase = input("""Enter numbers separated by a comma:\n""").strip()
_UpperCAmelCase = [int(item) for item in user_input.split(""",""")]
_UpperCAmelCase = int(input("""Enter the number to be searched:\n"""))
_UpperCAmelCase = jump_search(arr, x)
if res == -1:
print("""Number not found!""")
else:
print(F"""Number {x} is at index {res}""")
| 70 | 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()
_UpperCAmelCase = logging.get_logger()
def UpperCamelCase ( __lowercase : int ,__lowercase : str ,__lowercase : LevitConfig ,__lowercase : Path ,__lowercase : bool = True ):
'''simple docstring'''
print(f'''Converting {name}...''' )
with torch.no_grad():
if hidden_sizes == 1_28:
if name[-1] == "S":
A_ : int = timm.create_model('levit_128s' ,pretrained=__lowercase )
else:
A_ : str = timm.create_model('levit_128' ,pretrained=__lowercase )
if hidden_sizes == 1_92:
A_ : List[str] = timm.create_model('levit_192' ,pretrained=__lowercase )
if hidden_sizes == 2_56:
A_ : Optional[Any] = timm.create_model('levit_256' ,pretrained=__lowercase )
if hidden_sizes == 3_84:
A_ : Tuple = timm.create_model('levit_384' ,pretrained=__lowercase )
from_model.eval()
A_ : Dict = LevitForImageClassificationWithTeacher(__lowercase ).eval()
A_ : Union[str, Any] = OrderedDict()
A_ : Dict = from_model.state_dict()
A_ : Tuple = list(from_model.state_dict().keys() )
A_ : str = list(our_model.state_dict().keys() )
print(len(__lowercase ) ,len(__lowercase ) )
for i in range(len(__lowercase ) ):
A_ : str = weights[og_keys[i]]
our_model.load_state_dict(__lowercase )
A_ : str = torch.randn((2, 3, 2_24, 2_24) )
A_ : str = from_model(__lowercase )
A_ : Optional[Any] = our_model(__lowercase ).logits
assert torch.allclose(__lowercase ,__lowercase ), "The model logits don't match the original one."
A_ : List[str] = name
print(__lowercase )
if push_to_hub:
our_model.save_pretrained(save_directory / checkpoint_name )
A_ : Union[str, Any] = LevitImageProcessor()
image_processor.save_pretrained(save_directory / checkpoint_name )
print(f'''Pushed {checkpoint_name}''' )
def UpperCamelCase ( __lowercase : Path ,__lowercase : str = None ,__lowercase : bool = True ):
'''simple docstring'''
A_ : Dict = 'imagenet-1k-id2label.json'
A_ : Optional[int] = 10_00
A_ : Optional[int] = (1, num_labels)
A_ : int = 'huggingface/label-files'
A_ : int = num_labels
A_ : Union[str, Any] = json.load(open(hf_hub_download(__lowercase ,__lowercase ,repo_type='dataset' ) ,'r' ) )
A_ : int = {int(__lowercase ): v for k, v in idalabel.items()}
A_ : List[str] = idalabel
A_ : str = {v: k for k, v in idalabel.items()}
A_ : int = partial(__lowercase ,num_labels=__lowercase ,idalabel=__lowercase ,labelaid=__lowercase )
A_ : Any = {
'levit-128S': 1_28,
'levit-128': 1_28,
'levit-192': 1_92,
'levit-256': 2_56,
'levit-384': 3_84,
}
A_ : Tuple = {
'levit-128S': ImageNetPreTrainedConfig(
hidden_sizes=[1_28, 2_56, 3_84] ,num_attention_heads=[4, 6, 8] ,depths=[2, 3, 4] ,key_dim=[16, 16, 16] ,drop_path_rate=0 ,),
'levit-128': ImageNetPreTrainedConfig(
hidden_sizes=[1_28, 2_56, 3_84] ,num_attention_heads=[4, 8, 12] ,depths=[4, 4, 4] ,key_dim=[16, 16, 16] ,drop_path_rate=0 ,),
'levit-192': ImageNetPreTrainedConfig(
hidden_sizes=[1_92, 2_88, 3_84] ,num_attention_heads=[3, 5, 6] ,depths=[4, 4, 4] ,key_dim=[32, 32, 32] ,drop_path_rate=0 ,),
'levit-256': ImageNetPreTrainedConfig(
hidden_sizes=[2_56, 3_84, 5_12] ,num_attention_heads=[4, 6, 8] ,depths=[4, 4, 4] ,key_dim=[32, 32, 32] ,drop_path_rate=0 ,),
'levit-384': ImageNetPreTrainedConfig(
hidden_sizes=[3_84, 5_12, 7_68] ,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] ,__lowercase ,names_to_config[model_name] ,__lowercase ,__lowercase )
else:
for model_name, config in names_to_config.items():
convert_weight_and_push(names_to_hidden_sizes[model_name] ,__lowercase ,__lowercase ,__lowercase ,__lowercase )
return config, expected_shape
if __name__ == "__main__":
_UpperCAmelCase = 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""",
)
_UpperCAmelCase = parser.parse_args()
_UpperCAmelCase = 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)
| 70 | 1 |
'''simple docstring'''
def lowerCamelCase__ ( a ):
if not isinstance(snake_case__ , snake_case__ ):
raise TypeError('Input value must be an \'int\' type' )
__snake_case = 0
while number:
position += 1
number >>= 1
return position
if __name__ == "__main__":
import doctest
doctest.testmod()
| 356 |
import os
import pytest
from attr import dataclass
__UpperCAmelCase = '''us-east-1''' # defaults region
@dataclass
class lowerCAmelCase_ :
UpperCAmelCase__ : str
UpperCAmelCase__ : Tuple = "arn:aws:iam::558105141721:role/sagemaker_execution_role"
UpperCAmelCase__ : Union[str, Any] = {
"task_name": "mnli",
"per_device_train_batch_size": 16,
"per_device_eval_batch_size": 16,
"do_train": True,
"do_eval": True,
"do_predict": True,
"output_dir": "/opt/ml/model",
"overwrite_output_dir": True,
"max_steps": 500,
"save_steps": 5500,
}
UpperCAmelCase__ : Dict = {**hyperparameters, "max_steps": 1000}
@property
def snake_case_ ( self ) -> str:
if self.framework == "pytorch":
return [
{"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"},
{"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"},
{"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"},
]
else:
return [
{"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"},
{"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"},
{"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"},
]
@property
def snake_case_ ( self ) -> str:
return F"""{self.framework}-transfromers-test"""
@property
def snake_case_ ( self ) -> str:
return F"""./tests/sagemaker/scripts/{self.framework}"""
@property
def snake_case_ ( self ) -> str:
if self.framework == "pytorch":
return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04"
else:
return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04"
@pytest.fixture(scope='class' )
def UpperCamelCase ( snake_case__ : Any ) -> Union[str, Any]:
UpperCamelCase : Optional[Any] = SageMakerTestEnvironment(framework=request.cls.framework )
| 40 | 0 |
"""simple docstring"""
import argparse
from copy import deepcopy
import numpy as np
from datasets import ClassLabel, DatasetDict, load_dataset
from evaluate import load
from transformers import (
AutoModelForSequenceClassification,
AutoTokenizer,
DataCollatorWithPadding,
Trainer,
TrainerCallback,
TrainingArguments,
set_seed,
)
def snake_case__ ( ) ->str:
UpperCAmelCase__ = argparse.ArgumentParser()
parser.add_argument("""--model_ckpt""" , type=_SCREAMING_SNAKE_CASE , default="""microsoft/unixcoder-base-nine""" )
parser.add_argument("""--num_epochs""" , type=_SCREAMING_SNAKE_CASE , default=5 )
parser.add_argument("""--batch_size""" , type=_SCREAMING_SNAKE_CASE , default=6 )
parser.add_argument("""--gradient_accumulation_steps""" , type=_SCREAMING_SNAKE_CASE , default=1 )
parser.add_argument("""--freeze""" , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE )
parser.add_argument("""--learning_rate""" , type=_SCREAMING_SNAKE_CASE , default=5E-4 )
parser.add_argument("""--seed""" , type=_SCREAMING_SNAKE_CASE , default=0 )
parser.add_argument("""--lr_scheduler_type""" , type=_SCREAMING_SNAKE_CASE , default="""cosine""" )
parser.add_argument("""--num_warmup_steps""" , type=_SCREAMING_SNAKE_CASE , default=1_0 )
parser.add_argument("""--weight_decay""" , type=_SCREAMING_SNAKE_CASE , default=0.01 )
parser.add_argument("""--output_dir""" , type=_SCREAMING_SNAKE_CASE , default="""./results""" )
return parser.parse_args()
a : Any = load('''accuracy''')
def snake_case__ ( _SCREAMING_SNAKE_CASE ) ->str:
UpperCAmelCase__ , UpperCAmelCase__ = eval_pred
UpperCAmelCase__ = np.argmax(_SCREAMING_SNAKE_CASE , axis=1 )
return metric.compute(predictions=_SCREAMING_SNAKE_CASE , references=_SCREAMING_SNAKE_CASE )
class _UpperCamelCase ( __UpperCamelCase ):
'''simple docstring'''
def __init__( self , __lowercase ):
super().__init__()
UpperCAmelCase__ = trainer
def A__ ( self , __lowercase , __lowercase , __lowercase , **__lowercase ):
if control.should_evaluate:
UpperCAmelCase__ = deepcopy(__lowercase )
self._trainer.evaluate(eval_dataset=self._trainer.train_dataset , metric_key_prefix="""train""" )
return control_copy
def snake_case__ ( ) ->List[str]:
UpperCAmelCase__ = get_args()
set_seed(args.seed )
UpperCAmelCase__ = load_dataset("""codeparrot/codecomplex""" , split="""train""" )
UpperCAmelCase__ = dataset.train_test_split(test_size=0.2 )
UpperCAmelCase__ = train_test["""test"""].train_test_split(test_size=0.5 )
UpperCAmelCase__ = DatasetDict(
{
"""train""": train_test["""train"""],
"""test""": test_validation["""train"""],
"""valid""": test_validation["""test"""],
} )
print("""Loading tokenizer and model""" )
UpperCAmelCase__ = AutoTokenizer.from_pretrained(args.model_ckpt )
UpperCAmelCase__ = tokenizer.eos_token
UpperCAmelCase__ = AutoModelForSequenceClassification.from_pretrained(args.model_ckpt , num_labels=7 )
UpperCAmelCase__ = model.config.eos_token_id
if args.freeze:
for param in model.roberta.parameters():
UpperCAmelCase__ = False
UpperCAmelCase__ = ClassLabel(num_classes=7 , names=list(set(train_test_validation["""train"""]["""complexity"""] ) ) )
def tokenize(_SCREAMING_SNAKE_CASE ):
UpperCAmelCase__ = tokenizer(example["""src"""] , truncation=_SCREAMING_SNAKE_CASE , max_length=1_0_2_4 )
UpperCAmelCase__ = labels.straint(example["""complexity"""] )
return {
"input_ids": inputs["input_ids"],
"attention_mask": inputs["attention_mask"],
"label": label,
}
UpperCAmelCase__ = train_test_validation.map(
_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE , remove_columns=train_test_validation["""train"""].column_names , )
UpperCAmelCase__ = DataCollatorWithPadding(tokenizer=_SCREAMING_SNAKE_CASE )
UpperCAmelCase__ = TrainingArguments(
output_dir=args.output_dir , learning_rate=args.learning_rate , lr_scheduler_type=args.lr_scheduler_type , evaluation_strategy="""epoch""" , save_strategy="""epoch""" , logging_strategy="""epoch""" , per_device_train_batch_size=args.batch_size , per_device_eval_batch_size=args.batch_size , num_train_epochs=args.num_epochs , gradient_accumulation_steps=args.gradient_accumulation_steps , weight_decay=0.01 , metric_for_best_model="""accuracy""" , run_name="""complexity-java""" , report_to="""wandb""" , )
UpperCAmelCase__ = Trainer(
model=_SCREAMING_SNAKE_CASE , args=_SCREAMING_SNAKE_CASE , train_dataset=tokenized_datasets["""train"""] , eval_dataset=tokenized_datasets["""valid"""] , tokenizer=_SCREAMING_SNAKE_CASE , data_collator=_SCREAMING_SNAKE_CASE , compute_metrics=_SCREAMING_SNAKE_CASE , )
print("""Training...""" )
trainer.add_callback(CustomCallback(_SCREAMING_SNAKE_CASE ) )
trainer.train()
if __name__ == "__main__":
main()
| 422 |
"""simple docstring"""
import json
import unittest
import numpy as np
from huggingface_hub import hf_hub_download
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from transformers import OneFormerImageProcessor
from transformers.models.oneformer.image_processing_oneformer import binary_mask_to_rle
from transformers.models.oneformer.modeling_oneformer import OneFormerForUniversalSegmentationOutput
if is_vision_available():
from PIL import Image
def snake_case__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="shi-labs/oneformer_demo" ) ->List[str]:
with open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) as f:
UpperCAmelCase__ = json.load(_SCREAMING_SNAKE_CASE )
UpperCAmelCase__ = {}
UpperCAmelCase__ = []
UpperCAmelCase__ = []
for key, info in class_info.items():
UpperCAmelCase__ = info["""name"""]
class_names.append(info["""name"""] )
if info["isthing"]:
thing_ids.append(int(_SCREAMING_SNAKE_CASE ) )
UpperCAmelCase__ = thing_ids
UpperCAmelCase__ = class_names
return metadata
class _UpperCamelCase ( unittest.TestCase ):
'''simple docstring'''
def __init__( self , __lowercase , __lowercase=7 , __lowercase=3 , __lowercase=30 , __lowercase=400 , __lowercase=None , __lowercase=True , __lowercase=True , __lowercase=[0.5, 0.5, 0.5] , __lowercase=[0.5, 0.5, 0.5] , __lowercase=10 , __lowercase=False , __lowercase=255 , __lowercase="shi-labs/oneformer_demo" , __lowercase="ade20k_panoptic.json" , __lowercase=10 , ):
UpperCAmelCase__ = parent
UpperCAmelCase__ = batch_size
UpperCAmelCase__ = num_channels
UpperCAmelCase__ = min_resolution
UpperCAmelCase__ = max_resolution
UpperCAmelCase__ = do_resize
UpperCAmelCase__ = {"""shortest_edge""": 32, """longest_edge""": 1333} if size is None else size
UpperCAmelCase__ = do_normalize
UpperCAmelCase__ = image_mean
UpperCAmelCase__ = image_std
UpperCAmelCase__ = class_info_file
UpperCAmelCase__ = prepare_metadata(__lowercase , __lowercase )
UpperCAmelCase__ = num_text
UpperCAmelCase__ = repo_path
# for the post_process_functions
UpperCAmelCase__ = 2
UpperCAmelCase__ = 10
UpperCAmelCase__ = 10
UpperCAmelCase__ = 3
UpperCAmelCase__ = 4
UpperCAmelCase__ = num_labels
UpperCAmelCase__ = do_reduce_labels
UpperCAmelCase__ = ignore_index
def A__ ( self ):
return {
"do_resize": self.do_resize,
"size": self.size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"num_labels": self.num_labels,
"do_reduce_labels": self.do_reduce_labels,
"ignore_index": self.ignore_index,
"class_info_file": self.class_info_file,
"metadata": self.metadata,
"num_text": self.num_text,
}
def A__ ( self , __lowercase , __lowercase=False ):
if not batched:
UpperCAmelCase__ = image_inputs[0]
if isinstance(__lowercase , Image.Image ):
UpperCAmelCase__ , UpperCAmelCase__ = image.size
else:
UpperCAmelCase__ , UpperCAmelCase__ = image.shape[1], image.shape[2]
if w < h:
UpperCAmelCase__ = int(self.size["""shortest_edge"""] * h / w )
UpperCAmelCase__ = self.size["""shortest_edge"""]
elif w > h:
UpperCAmelCase__ = self.size["""shortest_edge"""]
UpperCAmelCase__ = int(self.size["""shortest_edge"""] * w / h )
else:
UpperCAmelCase__ = self.size["""shortest_edge"""]
UpperCAmelCase__ = self.size["""shortest_edge"""]
else:
UpperCAmelCase__ = []
for image in image_inputs:
UpperCAmelCase__ , UpperCAmelCase__ = self.get_expected_values([image] )
expected_values.append((expected_height, expected_width) )
UpperCAmelCase__ = max(__lowercase , key=lambda __lowercase : item[0] )[0]
UpperCAmelCase__ = max(__lowercase , key=lambda __lowercase : item[1] )[1]
return expected_height, expected_width
def A__ ( self ):
return OneFormerForUniversalSegmentationOutput(
# +1 for null class
class_queries_logits=torch.randn((self.batch_size, self.num_queries, self.num_classes + 1) ) , masks_queries_logits=torch.randn((self.batch_size, self.num_queries, self.height, self.width) ) , )
@require_torch
@require_vision
class _UpperCamelCase ( __UpperCamelCase , unittest.TestCase ):
'''simple docstring'''
__lowercase : Tuple = OneFormerImageProcessor if (is_vision_available() and is_torch_available()) else None
# only for test_image_processing_common.test_image_proc_to_json_string
__lowercase : Tuple = image_processing_class
def A__ ( self ):
UpperCAmelCase__ = OneFormerImageProcessorTester(self )
@property
def A__ ( self ):
return self.image_processing_tester.prepare_image_processor_dict()
def A__ ( self ):
UpperCAmelCase__ = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(__lowercase , """image_mean""" ) )
self.assertTrue(hasattr(__lowercase , """image_std""" ) )
self.assertTrue(hasattr(__lowercase , """do_normalize""" ) )
self.assertTrue(hasattr(__lowercase , """do_resize""" ) )
self.assertTrue(hasattr(__lowercase , """size""" ) )
self.assertTrue(hasattr(__lowercase , """ignore_index""" ) )
self.assertTrue(hasattr(__lowercase , """class_info_file""" ) )
self.assertTrue(hasattr(__lowercase , """num_text""" ) )
self.assertTrue(hasattr(__lowercase , """repo_path""" ) )
self.assertTrue(hasattr(__lowercase , """metadata""" ) )
self.assertTrue(hasattr(__lowercase , """do_reduce_labels""" ) )
def A__ ( self ):
pass
def A__ ( self ):
# Initialize image_processor
UpperCAmelCase__ = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
UpperCAmelCase__ = prepare_image_inputs(self.image_processing_tester , equal_resolution=__lowercase )
for image in image_inputs:
self.assertIsInstance(__lowercase , Image.Image )
# Test not batched input
UpperCAmelCase__ = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values
UpperCAmelCase__ , UpperCAmelCase__ = self.image_processing_tester.get_expected_values(__lowercase )
self.assertEqual(
encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , )
# Test batched
UpperCAmelCase__ , UpperCAmelCase__ = self.image_processing_tester.get_expected_values(__lowercase , batched=__lowercase )
UpperCAmelCase__ = image_processor(
__lowercase , ["""semantic"""] * len(__lowercase ) , return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processing_tester.batch_size,
self.image_processing_tester.num_channels,
expected_height,
expected_width,
) , )
def A__ ( self ):
# Initialize image_processor
UpperCAmelCase__ = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
UpperCAmelCase__ = prepare_image_inputs(self.image_processing_tester , equal_resolution=__lowercase , numpify=__lowercase )
for image in image_inputs:
self.assertIsInstance(__lowercase , np.ndarray )
# Test not batched input
UpperCAmelCase__ = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values
UpperCAmelCase__ , UpperCAmelCase__ = self.image_processing_tester.get_expected_values(__lowercase )
self.assertEqual(
encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , )
# Test batched
UpperCAmelCase__ , UpperCAmelCase__ = self.image_processing_tester.get_expected_values(__lowercase , batched=__lowercase )
UpperCAmelCase__ = image_processor(
__lowercase , ["""semantic"""] * len(__lowercase ) , return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processing_tester.batch_size,
self.image_processing_tester.num_channels,
expected_height,
expected_width,
) , )
def A__ ( self ):
# Initialize image_processor
UpperCAmelCase__ = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
UpperCAmelCase__ = prepare_image_inputs(self.image_processing_tester , equal_resolution=__lowercase , torchify=__lowercase )
for image in image_inputs:
self.assertIsInstance(__lowercase , torch.Tensor )
# Test not batched input
UpperCAmelCase__ = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values
UpperCAmelCase__ , UpperCAmelCase__ = self.image_processing_tester.get_expected_values(__lowercase )
self.assertEqual(
encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , )
# Test batched
UpperCAmelCase__ , UpperCAmelCase__ = self.image_processing_tester.get_expected_values(__lowercase , batched=__lowercase )
UpperCAmelCase__ = image_processor(
__lowercase , ["""semantic"""] * len(__lowercase ) , return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processing_tester.batch_size,
self.image_processing_tester.num_channels,
expected_height,
expected_width,
) , )
def A__ ( self , __lowercase=False , __lowercase=False , __lowercase="np" ):
UpperCAmelCase__ = self.image_processing_class(**self.image_processor_dict )
# prepare image and target
UpperCAmelCase__ = self.image_processing_tester.num_labels
UpperCAmelCase__ = None
UpperCAmelCase__ = None
UpperCAmelCase__ = prepare_image_inputs(self.image_processing_tester , equal_resolution=__lowercase )
if with_segmentation_maps:
UpperCAmelCase__ = num_labels
if is_instance_map:
UpperCAmelCase__ = list(range(__lowercase ) ) * 2
UpperCAmelCase__ = dict(enumerate(__lowercase ) )
UpperCAmelCase__ = [
np.random.randint(0 , high * 2 , (img.size[1], img.size[0]) ).astype(np.uinta ) for img in image_inputs
]
if segmentation_type == "pil":
UpperCAmelCase__ = [Image.fromarray(__lowercase ) for annotation in annotations]
UpperCAmelCase__ = image_processor(
__lowercase , ["""semantic"""] * len(__lowercase ) , __lowercase , return_tensors="""pt""" , instance_id_to_semantic_id=__lowercase , pad_and_return_pixel_mask=__lowercase , )
return inputs
def A__ ( self ):
pass
def A__ ( self ):
def common(__lowercase=False , __lowercase=None ):
UpperCAmelCase__ = self.comm_get_image_processor_inputs(
with_segmentation_maps=__lowercase , is_instance_map=__lowercase , segmentation_type=__lowercase )
UpperCAmelCase__ = inputs["""mask_labels"""]
UpperCAmelCase__ = inputs["""class_labels"""]
UpperCAmelCase__ = inputs["""pixel_values"""]
UpperCAmelCase__ = inputs["""text_inputs"""]
# check the batch_size
for mask_label, class_label, text_input in zip(__lowercase , __lowercase , __lowercase ):
self.assertEqual(mask_label.shape[0] , class_label.shape[0] )
# this ensure padding has happened
self.assertEqual(mask_label.shape[1:] , pixel_values.shape[2:] )
self.assertEqual(len(__lowercase ) , self.image_processing_tester.num_text )
common()
common(is_instance_map=__lowercase )
common(is_instance_map=__lowercase , segmentation_type="""pil""" )
common(is_instance_map=__lowercase , segmentation_type="""pil""" )
def A__ ( self ):
UpperCAmelCase__ = np.zeros((20, 50) )
UpperCAmelCase__ = 1
UpperCAmelCase__ = 1
UpperCAmelCase__ = 1
UpperCAmelCase__ = binary_mask_to_rle(__lowercase )
self.assertEqual(len(__lowercase ) , 4 )
self.assertEqual(rle[0] , 21 )
self.assertEqual(rle[1] , 45 )
def A__ ( self ):
UpperCAmelCase__ = self.image_processing_class(
num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , )
UpperCAmelCase__ = self.image_processing_tester.get_fake_oneformer_outputs()
UpperCAmelCase__ = fature_extractor.post_process_semantic_segmentation(__lowercase )
self.assertEqual(len(__lowercase ) , self.image_processing_tester.batch_size )
self.assertEqual(
segmentation[0].shape , (
self.image_processing_tester.height,
self.image_processing_tester.width,
) , )
UpperCAmelCase__ = [(1, 4) for i in range(self.image_processing_tester.batch_size )]
UpperCAmelCase__ = fature_extractor.post_process_semantic_segmentation(__lowercase , target_sizes=__lowercase )
self.assertEqual(segmentation[0].shape , target_sizes[0] )
def A__ ( self ):
UpperCAmelCase__ = self.image_processing_class(
num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , )
UpperCAmelCase__ = self.image_processing_tester.get_fake_oneformer_outputs()
UpperCAmelCase__ = image_processor.post_process_instance_segmentation(__lowercase , threshold=0 )
self.assertTrue(len(__lowercase ) == self.image_processing_tester.batch_size )
for el in segmentation:
self.assertTrue("""segmentation""" in el )
self.assertTrue("""segments_info""" in el )
self.assertEqual(type(el["""segments_info"""] ) , __lowercase )
self.assertEqual(
el["""segmentation"""].shape , (self.image_processing_tester.height, self.image_processing_tester.width) )
def A__ ( self ):
UpperCAmelCase__ = self.image_processing_class(
num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , )
UpperCAmelCase__ = self.image_processing_tester.get_fake_oneformer_outputs()
UpperCAmelCase__ = image_processor.post_process_panoptic_segmentation(__lowercase , threshold=0 )
self.assertTrue(len(__lowercase ) == self.image_processing_tester.batch_size )
for el in segmentation:
self.assertTrue("""segmentation""" in el )
self.assertTrue("""segments_info""" in el )
self.assertEqual(type(el["""segments_info"""] ) , __lowercase )
self.assertEqual(
el["""segmentation"""].shape , (self.image_processing_tester.height, self.image_processing_tester.width) )
| 422 | 1 |
"""simple docstring"""
import inspect
from typing import List, Optional, Tuple, Union
import numpy as np
import PIL
import torch
import torch.utils.checkpoint
from ...models import UNetaDModel, VQModel
from ...schedulers import (
DDIMScheduler,
DPMSolverMultistepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
LMSDiscreteScheduler,
PNDMScheduler,
)
from ...utils import PIL_INTERPOLATION, randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
def _UpperCAmelCase ( __lowerCamelCase : Tuple ) -> str:
_snake_case = image.size
_snake_case = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32
_snake_case = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] )
_snake_case = np.array(lowerCamelCase_ ).astype(np.floataa ) / 255.0
_snake_case = image[None].transpose(0 , 3 , 1 , 2 )
_snake_case = torch.from_numpy(lowerCamelCase_ )
return 2.0 * image - 1.0
class lowerCAmelCase__ ( UpperCamelCase_ ):
def __init__( self : Optional[Any] , _lowerCamelCase : VQModel , _lowerCamelCase : UNetaDModel , _lowerCamelCase : Union[
DDIMScheduler,
PNDMScheduler,
LMSDiscreteScheduler,
EulerDiscreteScheduler,
EulerAncestralDiscreteScheduler,
DPMSolverMultistepScheduler,
] , ):
super().__init__()
self.register_modules(vqvae=a__ , unet=a__ , scheduler=a__ )
@torch.no_grad()
def __call__( self : int , _lowerCamelCase : Union[torch.Tensor, PIL.Image.Image] = None , _lowerCamelCase : Optional[int] = 1 , _lowerCamelCase : Optional[int] = 100 , _lowerCamelCase : Optional[float] = 0.0 , _lowerCamelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , _lowerCamelCase : Optional[str] = "pil" , _lowerCamelCase : bool = True , ):
if isinstance(a__ , PIL.Image.Image ):
_snake_case = 1
elif isinstance(a__ , torch.Tensor ):
_snake_case = image.shape[0]
else:
raise ValueError(f'''`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(a__ )}''' )
if isinstance(a__ , PIL.Image.Image ):
_snake_case = preprocess(a__ )
_snake_case = image.shape[-2:]
# in_channels should be 6: 3 for latents, 3 for low resolution image
_snake_case = (batch_size, self.unet.config.in_channels // 2, height, width)
_snake_case = next(self.unet.parameters() ).dtype
_snake_case = randn_tensor(a__ , generator=a__ , device=self.device , dtype=a__ )
_snake_case = image.to(device=self.device , dtype=a__ )
# set timesteps and move to the correct device
self.scheduler.set_timesteps(a__ , device=self.device )
_snake_case = self.scheduler.timesteps
# scale the initial noise by the standard deviation required by the scheduler
_snake_case = latents * self.scheduler.init_noise_sigma
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature.
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
# and should be between [0, 1]
_snake_case = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() )
_snake_case = {}
if accepts_eta:
_snake_case = eta
for t in self.progress_bar(a__ ):
# concat latents and low resolution image in the channel dimension.
_snake_case = torch.cat([latents, image] , dim=1 )
_snake_case = self.scheduler.scale_model_input(a__ , a__ )
# predict the noise residual
_snake_case = self.unet(a__ , a__ ).sample
# compute the previous noisy sample x_t -> x_t-1
_snake_case = self.scheduler.step(a__ , a__ , a__ , **a__ ).prev_sample
# decode the image latents with the VQVAE
_snake_case = self.vqvae.decode(a__ ).sample
_snake_case = torch.clamp(a__ , -1.0 , 1.0 )
_snake_case = image / 2 + 0.5
_snake_case = image.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
_snake_case = self.numpy_to_pil(a__ )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=a__ )
| 224 |
'''simple docstring'''
def UpperCAmelCase_ ( lowerCamelCase_ ):
"""simple docstring"""
lowerCAmelCase__ : str = len(lowerCamelCase_ )
lowerCAmelCase__ : Optional[Any] = len(matrix[0] )
lowerCAmelCase__ : Any = min(lowerCamelCase_ , lowerCamelCase_ )
for row in range(lowerCamelCase_ ):
# Check if diagonal element is not zero
if matrix[row][row] != 0:
# Eliminate all the elements below the diagonal
for col in range(row + 1 , lowerCamelCase_ ):
lowerCAmelCase__ : Tuple = matrix[col][row] / matrix[row][row]
for i in range(lowerCamelCase_ , lowerCamelCase_ ):
matrix[col][i] -= multiplier * matrix[row][i]
else:
# Find a non-zero diagonal element to swap rows
lowerCAmelCase__ : Dict = True
for i in range(row + 1 , lowerCamelCase_ ):
if matrix[i][row] != 0:
lowerCAmelCase__ , lowerCAmelCase__ : Optional[Any] = matrix[i], matrix[row]
lowerCAmelCase__ : Optional[Any] = False
break
if reduce:
rank -= 1
for i in range(lowerCamelCase_ ):
lowerCAmelCase__ : Union[str, Any] = matrix[i][rank]
# Reduce the row pointer by one to stay on the same row
row -= 1
return rank
if __name__ == "__main__":
import doctest
doctest.testmod()
| 378 | 0 |
from __future__ import annotations
import requests
def a__ ( lowercase__ ):
'''simple docstring'''
UpperCAmelCase_ =F'https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty'
return requests.get(__lowerCAmelCase ).json()
def a__ ( lowercase__ = 1_0 ):
'''simple docstring'''
UpperCAmelCase_ ="https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty"
UpperCAmelCase_ =requests.get(__lowerCAmelCase ).json()[:max_stories]
return [get_hackernews_story(__lowerCAmelCase ) for story_id in story_ids]
def a__ ( lowercase__ = 1_0 ):
'''simple docstring'''
UpperCAmelCase_ =hackernews_top_stories(__lowerCAmelCase )
return "\n".join("* [{title}]({url})".format(**__lowerCAmelCase ) for story in stories )
if __name__ == "__main__":
print(hackernews_top_stories_as_markdown())
| 712 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowercase : Union[str, Any] =logging.get_logger(__name__)
__lowercase : List[Any] ={
"""tanreinama/GPTSAN-2.8B-spout_is_uniform""": (
"""https://huggingface.co/tanreinama/GPTSAN-2.8B-spout_is_uniform/resolve/main/config.json"""
),
}
class A ( __lowercase ):
_snake_case ='''gptsan-japanese'''
_snake_case =[
'''past_key_values''',
]
_snake_case ={
'''hidden_size''': '''d_model''',
'''num_attention_heads''': '''num_heads''',
'''num_hidden_layers''': '''num_layers''',
}
def __init__( self: Optional[Any] , _lowerCAmelCase: List[Any]=3_6000 , _lowerCAmelCase: List[Any]=1280 , _lowerCAmelCase: str=1024 , _lowerCAmelCase: Any=8192 , _lowerCAmelCase: str=4096 , _lowerCAmelCase: int=128 , _lowerCAmelCase: int=10 , _lowerCAmelCase: Dict=0 , _lowerCAmelCase: Any=16 , _lowerCAmelCase: Optional[int]=16 , _lowerCAmelCase: List[Any]=128 , _lowerCAmelCase: Tuple=0.0 , _lowerCAmelCase: Optional[Any]=1e-5 , _lowerCAmelCase: int=False , _lowerCAmelCase: Optional[Any]=0.0 , _lowerCAmelCase: str="float32" , _lowerCAmelCase: Dict=False , _lowerCAmelCase: Any=False , _lowerCAmelCase: int=False , _lowerCAmelCase: Union[str, Any]=0.0_02 , _lowerCAmelCase: Optional[int]=False , _lowerCAmelCase: int=True , _lowerCAmelCase: List[str]=3_5998 , _lowerCAmelCase: Optional[int]=3_5995 , _lowerCAmelCase: Dict=3_5999 , **_lowerCAmelCase: Optional[Any] , ) -> List[Any]:
'''simple docstring'''
UpperCAmelCase_ =vocab_size
UpperCAmelCase_ =max_position_embeddings
UpperCAmelCase_ =d_model
UpperCAmelCase_ =d_ff
UpperCAmelCase_ =d_ext
UpperCAmelCase_ =d_spout
UpperCAmelCase_ =num_switch_layers
UpperCAmelCase_ =num_ext_layers
UpperCAmelCase_ =num_switch_layers + num_ext_layers
UpperCAmelCase_ =num_heads
UpperCAmelCase_ =num_experts
UpperCAmelCase_ =expert_capacity
UpperCAmelCase_ =dropout_rate
UpperCAmelCase_ =layer_norm_epsilon
UpperCAmelCase_ =router_bias
UpperCAmelCase_ =router_jitter_noise
UpperCAmelCase_ =router_dtype
UpperCAmelCase_ =router_ignore_padding_tokens
UpperCAmelCase_ =output_hidden_states
UpperCAmelCase_ =output_attentions
UpperCAmelCase_ =initializer_factor
UpperCAmelCase_ =output_router_logits
UpperCAmelCase_ =use_cache
super().__init__(
separator_token_id=_lowerCAmelCase , pad_token_id=_lowerCAmelCase , eos_token_id=_lowerCAmelCase , **_lowerCAmelCase , )
| 550 | 0 |
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 numpy as np
import tensorflow as tf
from transformers import TFCamembertModel
@require_tf
@require_sentencepiece
@require_tokenizers
class __lowerCamelCase (unittest.TestCase ):
@slow
def snake_case_ ( self: Any ):
'''simple docstring'''
__UpperCamelCase = TFCamembertModel.from_pretrained('jplu/tf-camembert-base' )
__UpperCamelCase = tf.convert_to_tensor(
[[5, 121, 11, 660, 16, 730, 2_5543, 110, 83, 6]],dtype=tf.intaa,) # J'aime le camembert !"
__UpperCamelCase = model(A_ )['last_hidden_state']
__UpperCamelCase = tf.TensorShape((1, 10, 768) )
self.assertEqual(output.shape,A_ )
# compare the actual values for a slice.
__UpperCamelCase = tf.convert_to_tensor(
[[[-0.0_2_5_4, 0.0_2_3_5, 0.1_0_2_7], [0.0_6_0_6, -0.1_8_1_1, -0.0_4_1_8], [-0.1_5_6_1, -0.1_1_2_7, 0.2_6_8_7]]],dtype=tf.floataa,)
# camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0')
# camembert.eval()
# expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach()
self.assertTrue(np.allclose(output[:, :3, :3].numpy(),expected_slice.numpy(),atol=1E-4 ) )
| 1 |
from collections.abc import Generator
from math import sin
def _A ( _lowercase ) -> bytes:
"""simple docstring"""
if len(_lowercase ) != 32:
raise ValueError('Input must be of length 32' )
__UpperCamelCase = B''
for i in [3, 2, 1, 0]:
little_endian += string_aa[8 * i : 8 * i + 8]
return little_endian
def _A ( _lowercase ) -> bytes:
"""simple docstring"""
if i < 0:
raise ValueError('Input must be non-negative' )
__UpperCamelCase = format(_lowercase , '08x' )[-8:]
__UpperCamelCase = B''
for i in [3, 2, 1, 0]:
little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode('utf-8' )
return little_endian_hex
def _A ( _lowercase ) -> bytes:
"""simple docstring"""
__UpperCamelCase = B''
for char in message:
bit_string += format(_lowercase , '08b' ).encode('utf-8' )
__UpperCamelCase = format(len(_lowercase ) , '064b' ).encode('utf-8' )
# Pad bit_string to a multiple of 512 chars
bit_string += b"1"
while len(_lowercase ) % 5_12 != 4_48:
bit_string += b"0"
bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] )
return bit_string
def _A ( _lowercase ) -> Generator[list[int], None, None]:
"""simple docstring"""
if len(_lowercase ) % 5_12 != 0:
raise ValueError('Input must have length that\'s a multiple of 512' )
for pos in range(0 , len(_lowercase ) , 5_12 ):
__UpperCamelCase = bit_string[pos : pos + 5_12]
__UpperCamelCase = []
for i in range(0 , 5_12 , 32 ):
block_words.append(int(to_little_endian(block[i : i + 32] ) , 2 ) )
yield block_words
def _A ( _lowercase ) -> int:
"""simple docstring"""
if i < 0:
raise ValueError('Input must be non-negative' )
__UpperCamelCase = format(_lowercase , '032b' )
__UpperCamelCase = ''
for c in i_str:
new_str += "1" if c == "0" else "0"
return int(_lowercase , 2 )
def _A ( _lowercase , _lowercase ) -> int:
"""simple docstring"""
return (a + b) % 2**32
def _A ( _lowercase , _lowercase ) -> int:
"""simple docstring"""
if i < 0:
raise ValueError('Input must be non-negative' )
if shift < 0:
raise ValueError('Shift must be non-negative' )
return ((i << shift) ^ (i >> (32 - shift))) % 2**32
def _A ( _lowercase ) -> bytes:
"""simple docstring"""
__UpperCamelCase = preprocess(_lowercase )
__UpperCamelCase = [int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )]
# Starting states
__UpperCamelCase = 0X67_45_23_01
__UpperCamelCase = 0Xef_cd_ab_89
__UpperCamelCase = 0X98_ba_dc_fe
__UpperCamelCase = 0X10_32_54_76
__UpperCamelCase = [
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
]
# Process bit string in chunks, each with 16 32-char words
for block_words in get_block_words(_lowercase ):
__UpperCamelCase = aa
__UpperCamelCase = ba
__UpperCamelCase = ca
__UpperCamelCase = da
# Hash current chunk
for i in range(64 ):
if i <= 15:
# f = (b & c) | (not_32(b) & d) # Alternate definition for f
__UpperCamelCase = d ^ (b & (c ^ d))
__UpperCamelCase = i
elif i <= 31:
# f = (d & b) | (not_32(d) & c) # Alternate definition for f
__UpperCamelCase = c ^ (d & (b ^ c))
__UpperCamelCase = (5 * i + 1) % 16
elif i <= 47:
__UpperCamelCase = b ^ c ^ d
__UpperCamelCase = (3 * i + 5) % 16
else:
__UpperCamelCase = c ^ (b | not_aa(_lowercase ))
__UpperCamelCase = (7 * i) % 16
__UpperCamelCase = (f + a + added_consts[i] + block_words[g]) % 2**32
__UpperCamelCase = d
__UpperCamelCase = c
__UpperCamelCase = b
__UpperCamelCase = sum_aa(_lowercase , left_rotate_aa(_lowercase , shift_amounts[i] ) )
# Add hashed chunk to running total
__UpperCamelCase = sum_aa(_lowercase , _lowercase )
__UpperCamelCase = sum_aa(_lowercase , _lowercase )
__UpperCamelCase = sum_aa(_lowercase , _lowercase )
__UpperCamelCase = sum_aa(_lowercase , _lowercase )
__UpperCamelCase = reformat_hex(_lowercase ) + reformat_hex(_lowercase ) + reformat_hex(_lowercase ) + reformat_hex(_lowercase )
return digest
if __name__ == "__main__":
import doctest
doctest.testmod()
| 1 | 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 _UpperCamelCase ( lowerCAmelCase__: int ) -> Tuple:
if is_torch_version('<' ,'2.0.0' ) or not hasattr(lowerCAmelCase__ ,'_dynamo' ):
return False
return isinstance(lowerCAmelCase__ ,torch._dynamo.eval_frame.OptimizedModule )
def _UpperCamelCase ( lowerCAmelCase__: str ,lowerCAmelCase__: bool = True ) -> Optional[Any]:
SCREAMING_SNAKE_CASE_ = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)
SCREAMING_SNAKE_CASE_ = is_compiled_module(lowerCAmelCase__ )
if is_compiled:
SCREAMING_SNAKE_CASE_ = model
SCREAMING_SNAKE_CASE_ = model._orig_mod
if is_deepspeed_available():
options += (DeepSpeedEngine,)
while isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ):
SCREAMING_SNAKE_CASE_ = model.module
if not keep_fpaa_wrapper:
SCREAMING_SNAKE_CASE_ = getattr(lowerCAmelCase__ ,'forward' )
SCREAMING_SNAKE_CASE_ = model.__dict__.pop('_original_forward' ,lowerCAmelCase__ )
if original_forward is not None:
while hasattr(lowerCAmelCase__ ,'__wrapped__' ):
SCREAMING_SNAKE_CASE_ = forward.__wrapped__
if forward == original_forward:
break
SCREAMING_SNAKE_CASE_ = forward
if getattr(lowerCAmelCase__ ,'_converted_to_transformer_engine' ,lowerCAmelCase__ ):
convert_model(lowerCAmelCase__ ,to_transformer_engine=lowerCAmelCase__ )
if is_compiled:
SCREAMING_SNAKE_CASE_ = model
SCREAMING_SNAKE_CASE_ = compiled_model
return model
def _UpperCamelCase ( ) -> Tuple:
PartialState().wait_for_everyone()
def _UpperCamelCase ( lowerCAmelCase__: int ,lowerCAmelCase__: Optional[int] ) -> Union[str, Any]:
if PartialState().distributed_type == DistributedType.TPU:
xm.save(lowerCAmelCase__ ,lowerCAmelCase__ )
elif PartialState().local_process_index == 0:
torch.save(lowerCAmelCase__ ,lowerCAmelCase__ )
@contextmanager
def _UpperCamelCase ( **lowerCAmelCase__: Optional[int] ) -> str:
for key, value in kwargs.items():
SCREAMING_SNAKE_CASE_ = str(lowerCAmelCase__ )
yield
for key in kwargs:
if key.upper() in os.environ:
del os.environ[key.upper()]
def _UpperCamelCase ( lowerCAmelCase__: Optional[int] ) -> List[Any]:
if not hasattr(lowerCAmelCase__ ,'__qualname__' ) and not hasattr(lowerCAmelCase__ ,'__name__' ):
SCREAMING_SNAKE_CASE_ = getattr(lowerCAmelCase__ ,'__class__' ,lowerCAmelCase__ )
if hasattr(lowerCAmelCase__ ,'__qualname__' ):
return obj.__qualname__
if hasattr(lowerCAmelCase__ ,'__name__' ):
return obj.__name__
return str(lowerCAmelCase__ )
def _UpperCamelCase ( lowerCAmelCase__: Optional[int] ,lowerCAmelCase__: Union[str, Any] ) -> Dict:
for key, value in source.items():
if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ):
SCREAMING_SNAKE_CASE_ = destination.setdefault(lowerCAmelCase__ ,{} )
merge_dicts(lowerCAmelCase__ ,lowerCAmelCase__ )
else:
SCREAMING_SNAKE_CASE_ = value
return destination
def _UpperCamelCase ( lowerCAmelCase__: int = None ) -> bool:
if port is None:
SCREAMING_SNAKE_CASE_ = 2_9500
with socket.socket(socket.AF_INET ,socket.SOCK_STREAM ) as s:
return s.connect_ex(('localhost', port) ) == 0
| 710 |
'''simple docstring'''
import importlib
import json
import os
from collections import OrderedDict
from typing import Dict, Optional, Union
# Build the list of all feature extractors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...feature_extraction_utils import FeatureExtractionMixin
from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging
from .auto_factory import _LazyAutoMapping
from .configuration_auto import (
CONFIG_MAPPING_NAMES,
AutoConfig,
model_type_to_module_name,
replace_list_option_in_docstrings,
)
SCREAMING_SNAKE_CASE : List[Any] = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE : int = OrderedDict(
[
("audio-spectrogram-transformer", "ASTFeatureExtractor"),
("beit", "BeitFeatureExtractor"),
("chinese_clip", "ChineseCLIPFeatureExtractor"),
("clap", "ClapFeatureExtractor"),
("clip", "CLIPFeatureExtractor"),
("clipseg", "ViTFeatureExtractor"),
("conditional_detr", "ConditionalDetrFeatureExtractor"),
("convnext", "ConvNextFeatureExtractor"),
("cvt", "ConvNextFeatureExtractor"),
("data2vec-audio", "Wav2Vec2FeatureExtractor"),
("data2vec-vision", "BeitFeatureExtractor"),
("deformable_detr", "DeformableDetrFeatureExtractor"),
("deit", "DeiTFeatureExtractor"),
("detr", "DetrFeatureExtractor"),
("dinat", "ViTFeatureExtractor"),
("donut-swin", "DonutFeatureExtractor"),
("dpt", "DPTFeatureExtractor"),
("encodec", "EncodecFeatureExtractor"),
("flava", "FlavaFeatureExtractor"),
("glpn", "GLPNFeatureExtractor"),
("groupvit", "CLIPFeatureExtractor"),
("hubert", "Wav2Vec2FeatureExtractor"),
("imagegpt", "ImageGPTFeatureExtractor"),
("layoutlmv2", "LayoutLMv2FeatureExtractor"),
("layoutlmv3", "LayoutLMv3FeatureExtractor"),
("levit", "LevitFeatureExtractor"),
("maskformer", "MaskFormerFeatureExtractor"),
("mctct", "MCTCTFeatureExtractor"),
("mobilenet_v1", "MobileNetV1FeatureExtractor"),
("mobilenet_v2", "MobileNetV2FeatureExtractor"),
("mobilevit", "MobileViTFeatureExtractor"),
("nat", "ViTFeatureExtractor"),
("owlvit", "OwlViTFeatureExtractor"),
("perceiver", "PerceiverFeatureExtractor"),
("poolformer", "PoolFormerFeatureExtractor"),
("regnet", "ConvNextFeatureExtractor"),
("resnet", "ConvNextFeatureExtractor"),
("segformer", "SegformerFeatureExtractor"),
("sew", "Wav2Vec2FeatureExtractor"),
("sew-d", "Wav2Vec2FeatureExtractor"),
("speech_to_text", "Speech2TextFeatureExtractor"),
("speecht5", "SpeechT5FeatureExtractor"),
("swiftformer", "ViTFeatureExtractor"),
("swin", "ViTFeatureExtractor"),
("swinv2", "ViTFeatureExtractor"),
("table-transformer", "DetrFeatureExtractor"),
("timesformer", "VideoMAEFeatureExtractor"),
("tvlt", "TvltFeatureExtractor"),
("unispeech", "Wav2Vec2FeatureExtractor"),
("unispeech-sat", "Wav2Vec2FeatureExtractor"),
("van", "ConvNextFeatureExtractor"),
("videomae", "VideoMAEFeatureExtractor"),
("vilt", "ViltFeatureExtractor"),
("vit", "ViTFeatureExtractor"),
("vit_mae", "ViTFeatureExtractor"),
("vit_msn", "ViTFeatureExtractor"),
("wav2vec2", "Wav2Vec2FeatureExtractor"),
("wav2vec2-conformer", "Wav2Vec2FeatureExtractor"),
("wavlm", "Wav2Vec2FeatureExtractor"),
("whisper", "WhisperFeatureExtractor"),
("xclip", "CLIPFeatureExtractor"),
("yolos", "YolosFeatureExtractor"),
]
)
SCREAMING_SNAKE_CASE : str = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES)
def _UpperCamelCase ( lowerCAmelCase__: str ) -> Tuple:
for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items():
if class_name in extractors:
SCREAMING_SNAKE_CASE_ = model_type_to_module_name(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ = importlib.import_module(F""".{module_name}""" ,'transformers.models' )
try:
return getattr(lowerCAmelCase__ ,lowerCAmelCase__ )
except AttributeError:
continue
for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items():
if getattr(lowerCAmelCase__ ,'__name__' ,lowerCAmelCase__ ) == class_name:
return extractor
# We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
# init and we return the proper dummy to get an appropriate error message.
SCREAMING_SNAKE_CASE_ = importlib.import_module('transformers' )
if hasattr(lowerCAmelCase__ ,lowerCAmelCase__ ):
return getattr(lowerCAmelCase__ ,lowerCAmelCase__ )
return None
def _UpperCamelCase ( lowerCAmelCase__: Union[str, os.PathLike] ,lowerCAmelCase__: Optional[Union[str, os.PathLike]] = None ,lowerCAmelCase__: bool = False ,lowerCAmelCase__: bool = False ,lowerCAmelCase__: Optional[Dict[str, str]] = None ,lowerCAmelCase__: Optional[Union[bool, str]] = None ,lowerCAmelCase__: Optional[str] = None ,lowerCAmelCase__: bool = False ,**lowerCAmelCase__: int ,) -> str:
SCREAMING_SNAKE_CASE_ = get_file_from_repo(
lowerCAmelCase__ ,lowerCAmelCase__ ,cache_dir=lowerCAmelCase__ ,force_download=lowerCAmelCase__ ,resume_download=lowerCAmelCase__ ,proxies=lowerCAmelCase__ ,use_auth_token=lowerCAmelCase__ ,revision=lowerCAmelCase__ ,local_files_only=lowerCAmelCase__ ,)
if resolved_config_file is None:
logger.info(
'Could not locate the feature extractor configuration file, will try to use the model config instead.' )
return {}
with open(lowerCAmelCase__ ,encoding='utf-8' ) as reader:
return json.load(lowerCAmelCase__ )
class snake_case :
"""simple docstring"""
def __init__( self ) -> str:
raise EnvironmentError(
'AutoFeatureExtractor is designed to be instantiated '
'using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.' )
@classmethod
@replace_list_option_in_docstrings(_lowercase )
def a__ ( cls, _lowercase, **_lowercase ) -> List[str]:
SCREAMING_SNAKE_CASE_ = kwargs.pop('config', _lowercase )
SCREAMING_SNAKE_CASE_ = kwargs.pop('trust_remote_code', _lowercase )
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = FeatureExtractionMixin.get_feature_extractor_dict(_lowercase, **_lowercase )
SCREAMING_SNAKE_CASE_ = config_dict.get('feature_extractor_type', _lowercase )
SCREAMING_SNAKE_CASE_ = None
if "AutoFeatureExtractor" in config_dict.get('auto_map', {} ):
SCREAMING_SNAKE_CASE_ = config_dict['auto_map']['AutoFeatureExtractor']
# If we don't find the feature extractor class in the feature extractor config, let's try the model config.
if feature_extractor_class is None and feature_extractor_auto_map is None:
if not isinstance(_lowercase, _lowercase ):
SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained(_lowercase, **_lowercase )
# It could be in `config.feature_extractor_type``
SCREAMING_SNAKE_CASE_ = getattr(_lowercase, 'feature_extractor_type', _lowercase )
if hasattr(_lowercase, 'auto_map' ) and "AutoFeatureExtractor" in config.auto_map:
SCREAMING_SNAKE_CASE_ = config.auto_map['AutoFeatureExtractor']
if feature_extractor_class is not None:
SCREAMING_SNAKE_CASE_ = feature_extractor_class_from_name(_lowercase )
SCREAMING_SNAKE_CASE_ = feature_extractor_auto_map is not None
SCREAMING_SNAKE_CASE_ = feature_extractor_class is not None or type(_lowercase ) in FEATURE_EXTRACTOR_MAPPING
SCREAMING_SNAKE_CASE_ = resolve_trust_remote_code(
_lowercase, _lowercase, _lowercase, _lowercase )
if has_remote_code and trust_remote_code:
SCREAMING_SNAKE_CASE_ = get_class_from_dynamic_module(
_lowercase, _lowercase, **_lowercase )
SCREAMING_SNAKE_CASE_ = kwargs.pop('code_revision', _lowercase )
if os.path.isdir(_lowercase ):
feature_extractor_class.register_for_auto_class()
return feature_extractor_class.from_dict(_lowercase, **_lowercase )
elif feature_extractor_class is not None:
return feature_extractor_class.from_dict(_lowercase, **_lowercase )
# Last try: we use the FEATURE_EXTRACTOR_MAPPING.
elif type(_lowercase ) in FEATURE_EXTRACTOR_MAPPING:
SCREAMING_SNAKE_CASE_ = FEATURE_EXTRACTOR_MAPPING[type(_lowercase )]
return feature_extractor_class.from_dict(_lowercase, **_lowercase )
raise ValueError(
f"""Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a """
f"""`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following """
f"""`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys() )}""" )
@staticmethod
def a__ ( _lowercase, _lowercase ) -> Tuple:
FEATURE_EXTRACTOR_MAPPING.register(_lowercase, _lowercase )
| 238 | 0 |
"""simple docstring"""
import math
from typing import Any, Callable, List, Optional, Tuple, Union
import numpy as np
import torch
from ...models import TaFilmDecoder
from ...schedulers import DDPMScheduler
from ...utils import is_onnx_available, logging, randn_tensor
if is_onnx_available():
from ..onnx_utils import OnnxRuntimeModel
from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline
from .continous_encoder import SpectrogramContEncoder
from .notes_encoder import SpectrogramNotesEncoder
__A : str = logging.get_logger(__name__) # pylint: disable=invalid-name
__A : int = 256
class lowerCamelCase ( __SCREAMING_SNAKE_CASE ):
lowercase : Any = ['melgan']
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ):
super().__init__()
# From MELGAN
UpperCamelCase : List[Any] = math.log(1e-5 ) # Matches MelGAN training.
UpperCamelCase : str = 4.0 # Largest value for most examples
UpperCamelCase : Dict = 128
self.register_modules(
notes_encoder=UpperCAmelCase_ , continuous_encoder=UpperCAmelCase_ , decoder=UpperCAmelCase_ , scheduler=UpperCAmelCase_ , melgan=UpperCAmelCase_ , )
def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=(-1.0, 1.0) , SCREAMING_SNAKE_CASE_=False ):
UpperCamelCase : str = output_range
if clip:
UpperCamelCase : Any = torch.clip(UpperCAmelCase_ , self.min_value , self.max_value )
# Scale to [0, 1].
UpperCamelCase : Tuple = (features - self.min_value) / (self.max_value - self.min_value)
# Scale to [min_out, max_out].
return zero_one * (max_out - min_out) + min_out
def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=(-1.0, 1.0) , SCREAMING_SNAKE_CASE_=False ):
UpperCamelCase : List[Any] = input_range
UpperCamelCase : List[str] = torch.clip(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) if clip else outputs
# Scale to [0, 1].
UpperCamelCase : List[str] = (outputs - min_out) / (max_out - min_out)
# Scale to [self.min_value, self.max_value].
return zero_one * (self.max_value - self.min_value) + self.min_value
def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase : Dict = input_tokens > 0
UpperCamelCase : int = self.notes_encoder(
encoder_input_tokens=UpperCAmelCase_ , encoder_inputs_mask=UpperCAmelCase_ )
UpperCamelCase : Dict = self.continuous_encoder(
encoder_inputs=UpperCAmelCase_ , encoder_inputs_mask=UpperCAmelCase_ )
return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)]
def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase : Tuple = noise_time
if not torch.is_tensor(UpperCAmelCase_ ):
UpperCamelCase : Tuple = torch.tensor([timesteps] , dtype=torch.long , device=input_tokens.device )
elif torch.is_tensor(UpperCAmelCase_ ) and len(timesteps.shape ) == 0:
UpperCamelCase : Union[str, Any] = timesteps[None].to(input_tokens.device )
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
UpperCamelCase : List[Any] = timesteps * torch.ones(input_tokens.shape[0] , dtype=timesteps.dtype , device=timesteps.device )
UpperCamelCase : Tuple = self.decoder(
encodings_and_masks=UpperCAmelCase_ , decoder_input_tokens=UpperCAmelCase_ , decoder_noise_time=UpperCAmelCase_ )
return logits
@torch.no_grad()
def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 100 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = "numpy" , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , ):
if (callback_steps is None) or (
callback_steps is not None and (not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) or callback_steps <= 0)
):
raise ValueError(
f'`callback_steps` has to be a positive integer but is {callback_steps} of type'
f' {type(UpperCAmelCase_ )}.' )
UpperCamelCase : List[str] = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] , dtype=np.floataa )
UpperCamelCase : Union[str, Any] = np.zeros([1, 0, self.n_dims] , np.floataa )
UpperCamelCase : Optional[int] = torch.ones((1, TARGET_FEATURE_LENGTH) , dtype=UpperCAmelCase_ , device=self.device )
for i, encoder_input_tokens in enumerate(UpperCAmelCase_ ):
if i == 0:
UpperCamelCase : Optional[Any] = torch.from_numpy(pred_mel[:1].copy() ).to(
device=self.device , dtype=self.decoder.dtype )
# The first chunk has no previous context.
UpperCamelCase : int = torch.zeros((1, TARGET_FEATURE_LENGTH) , dtype=UpperCAmelCase_ , device=self.device )
else:
# The full song pipeline does not feed in a context feature, so the mask
# will be all 0s after the feature converter. Because we know we're
# feeding in a full context chunk from the previous prediction, set it
# to all 1s.
UpperCamelCase : Tuple = ones
UpperCamelCase : Optional[Any] = self.scale_features(
UpperCAmelCase_ , output_range=[-1.0, 1.0] , clip=UpperCAmelCase_ )
UpperCamelCase : Tuple = self.encode(
input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device ) , continuous_inputs=UpperCAmelCase_ , continuous_mask=UpperCAmelCase_ , )
# Sample encoder_continuous_inputs shaped gaussian noise to begin loop
UpperCamelCase : List[Any] = randn_tensor(
shape=encoder_continuous_inputs.shape , generator=UpperCAmelCase_ , device=self.device , dtype=self.decoder.dtype , )
# set step values
self.scheduler.set_timesteps(UpperCAmelCase_ )
# Denoising diffusion loop
for j, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ):
UpperCamelCase : Optional[int] = self.decode(
encodings_and_masks=UpperCAmelCase_ , input_tokens=UpperCAmelCase_ , noise_time=t / self.scheduler.config.num_train_timesteps , )
# Compute previous output: x_t -> x_t-1
UpperCamelCase : str = self.scheduler.step(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , generator=UpperCAmelCase_ ).prev_sample
UpperCamelCase : Optional[Any] = self.scale_to_features(UpperCAmelCase_ , input_range=[-1.0, 1.0] )
UpperCamelCase : List[Any] = mel[:1]
UpperCamelCase : Optional[int] = mel.cpu().float().numpy()
UpperCamelCase : int = np.concatenate([full_pred_mel, pred_mel[:1]] , axis=1 )
# call the callback, if provided
if callback is not None and i % callback_steps == 0:
callback(UpperCAmelCase_ , UpperCAmelCase_ )
logger.info("""Generated segment""" , UpperCAmelCase_ )
if output_type == "numpy" and not is_onnx_available():
raise ValueError(
"""Cannot return output in 'np' format if ONNX is not available. Make sure to have ONNX installed or set 'output_type' to 'mel'.""" )
elif output_type == "numpy" and self.melgan is None:
raise ValueError(
"""Cannot return output in 'np' format if melgan component is not defined. Make sure to define `self.melgan` or set 'output_type' to 'mel'.""" )
if output_type == "numpy":
UpperCamelCase : Any = self.melgan(input_features=full_pred_mel.astype(np.floataa ) )
else:
UpperCamelCase : Union[str, Any] = full_pred_mel
if not return_dict:
return (output,)
return AudioPipelineOutput(audios=UpperCAmelCase_ )
| 499 |
from transformers import BertTokenizerFast
from .custom_tokenization import CustomTokenizer
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = CustomTokenizer
pass
| 59 | 0 |
"""simple docstring"""
def A_ ( __UpperCamelCase : str , __UpperCamelCase : str ):
def get_matched_characters(__UpperCamelCase : str , __UpperCamelCase : str ) -> str:
lowercase = []
lowercase = min(len(_stra ) , len(_stra ) ) // 2
for i, l in enumerate(_stra ):
lowercase = int(max(0 , i - limit ) )
lowercase = int(min(i + limit + 1 , len(_stra ) ) )
if l in _stra[left:right]:
matched.append(__UpperCamelCase )
lowercase = f"""{_stra[0:_stra.index(__UpperCamelCase )]} {_stra[_stra.index(__UpperCamelCase ) + 1:]}"""
return "".join(__UpperCamelCase )
# matching characters
lowercase = get_matched_characters(__UpperCamelCase , __UpperCamelCase )
lowercase = get_matched_characters(__UpperCamelCase , __UpperCamelCase )
lowercase = len(__UpperCamelCase )
# transposition
lowercase = (
len([(ca, ca) for ca, ca in zip(__UpperCamelCase , __UpperCamelCase ) if ca != ca] ) // 2
)
if not match_count:
lowercase = 0.0
else:
lowercase = (
1
/ 3
* (
match_count / len(__UpperCamelCase )
+ match_count / len(__UpperCamelCase )
+ (match_count - transpositions) / match_count
)
)
# common prefix up to 4 characters
lowercase = 0
for ca, ca in zip(stra[:4] , stra[:4] ):
if ca == ca:
prefix_len += 1
else:
break
return jaro + 0.1 * prefix_len * (1 - jaro)
if __name__ == "__main__":
import doctest
doctest.testmod()
print(jaro_winkler('''hello''', '''world''')) | 396 |
"""simple docstring"""
def A_ ( __UpperCamelCase : list ):
for i in range(len(__UpperCamelCase ) - 1 , 0 , -1 ):
lowercase = False
for j in range(__UpperCamelCase , 0 , -1 ):
if unsorted[j] < unsorted[j - 1]:
lowercase , lowercase = unsorted[j - 1], unsorted[j]
lowercase = True
for j in range(__UpperCamelCase ):
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()
__lowerCAmelCase = input('''Enter numbers separated by a comma:\n''').strip()
__lowerCAmelCase = [int(item) for item in user_input.split(''',''')]
print(f'''{cocktail_shaker_sort(unsorted) = }''') | 396 | 1 |
import argparse
import torch
# Step 1. clone https://github.com/microsoft/unilm
# Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd
# Step 3. cd unilm
# Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink
# import classes
from unilm.wavlm.WavLM import WavLM as WavLMOrig
from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig
from transformers import WavLMConfig, WavLMModel, logging
logging.set_verbosity_info()
lowerCAmelCase__ :List[str] = logging.get_logger(__name__)
lowerCAmelCase__ :int = {
'''post_extract_proj''': '''feature_projection.projection''',
'''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''',
'''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''',
'''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''',
'''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''',
'''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''',
'''self_attn.grep_linear''': '''encoder.layers.*.attention.gru_rel_pos_linear''',
'''self_attn.relative_attention_bias''': '''encoder.layers.*.attention.rel_attn_embed''',
'''self_attn.grep_a''': '''encoder.layers.*.attention.gru_rel_pos_const''',
'''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''',
'''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''',
'''fc2''': '''encoder.layers.*.feed_forward.output_dense''',
'''final_layer_norm''': '''encoder.layers.*.final_layer_norm''',
'''encoder.layer_norm''': '''encoder.layer_norm''',
'''w2v_model.layer_norm''': '''feature_projection.layer_norm''',
'''quantizer.weight_proj''': '''quantizer.weight_proj''',
'''quantizer.vars''': '''quantizer.codevectors''',
'''project_q''': '''project_q''',
'''final_proj''': '''project_hid''',
'''w2v_encoder.proj''': '''ctc_proj''',
'''mask_emb''': '''masked_spec_embed''',
}
lowerCAmelCase__ :Union[str, Any] = [
'''ctc_proj''',
'''quantizer.weight_proj''',
'''quantizer.codevectors''',
'''project_q''',
'''project_hid''',
]
def lowerCAmelCase__ ( a__: Tuple , a__: Any , a__: Any , a__: Optional[Any] , a__: str ) -> Dict:
'''simple docstring'''
for attribute in key.split('.' ):
_UpperCAmelCase = getattr(a__ , a__ )
if weight_type is not None:
_UpperCAmelCase = getattr(a__ , a__ ).shape
else:
_UpperCAmelCase = hf_pointer.shape
assert hf_shape == value.shape, (
F'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be'''
F''' {value.shape} for {full_name}'''
)
if weight_type == "weight":
_UpperCAmelCase = value
elif weight_type == "weight_g":
_UpperCAmelCase = value
elif weight_type == "weight_v":
_UpperCAmelCase = value
elif weight_type == "bias":
_UpperCAmelCase = value
else:
_UpperCAmelCase = value
logger.info(F'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' )
def lowerCAmelCase__ ( a__: Optional[Any] , a__: Optional[Any] ) -> Optional[Any]:
'''simple docstring'''
_UpperCAmelCase = []
_UpperCAmelCase = fairseq_model.state_dict()
_UpperCAmelCase = hf_model.feature_extractor
for name, value in fairseq_dict.items():
_UpperCAmelCase = False
if "conv_layers" in name:
load_conv_layer(
a__ , a__ , a__ , a__ , hf_model.config.feat_extract_norm == 'group' , )
_UpperCAmelCase = True
else:
for key, mapped_key in MAPPING.items():
if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]:
_UpperCAmelCase = True
if "*" in mapped_key:
_UpperCAmelCase = name.split(a__ )[0].split('.' )[-2]
_UpperCAmelCase = mapped_key.replace('*' , a__ )
if "weight_g" in name:
_UpperCAmelCase = 'weight_g'
elif "weight_v" in name:
_UpperCAmelCase = 'weight_v'
elif "bias" in name and "relative_attention_bias" not in name:
_UpperCAmelCase = 'bias'
elif "weight" in name:
# TODO: don't match quantizer.weight_proj
_UpperCAmelCase = 'weight'
else:
_UpperCAmelCase = None
set_recursively(a__ , a__ , a__ , a__ , a__ )
continue
if not is_used:
unused_weights.append(a__ )
logger.warning(F'''Unused weights: {unused_weights}''' )
def lowerCAmelCase__ ( a__: Tuple , a__: Optional[Any] , a__: int , a__: Optional[int] , a__: Tuple ) -> Union[str, Any]:
'''simple docstring'''
_UpperCAmelCase = full_name.split('conv_layers.' )[-1]
_UpperCAmelCase = name.split('.' )
_UpperCAmelCase = int(items[0] )
_UpperCAmelCase = int(items[1] )
if type_id == 0:
if "bias" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.'''
)
_UpperCAmelCase = value
logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' )
elif "weight" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.'''
)
_UpperCAmelCase = value
logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' )
elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
if "bias" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
F'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was'''
" found."
)
_UpperCAmelCase = value
logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
elif "weight" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.'''
)
_UpperCAmelCase = value
logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
else:
unused_weights.append(a__ )
@torch.no_grad()
def lowerCAmelCase__ ( a__: List[str] , a__: Optional[int] , a__: Tuple=None ) -> Optional[Any]:
'''simple docstring'''
_UpperCAmelCase = torch.load(a__ )
_UpperCAmelCase = WavLMConfigOrig(checkpoint['cfg'] )
_UpperCAmelCase = WavLMOrig(a__ )
model.load_state_dict(checkpoint['model'] )
model.eval()
if config_path is not None:
_UpperCAmelCase = WavLMConfig.from_pretrained(a__ )
else:
_UpperCAmelCase = WavLMConfig()
_UpperCAmelCase = WavLMModel(a__ )
recursively_load_weights(a__ , a__ )
hf_wavlm.save_pretrained(a__ )
if __name__ == "__main__":
lowerCAmelCase__ :List[str] = argparse.ArgumentParser()
parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''')
parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''')
lowerCAmelCase__ :str = parser.parse_args()
convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
| 618 |
import re
import jax.numpy as jnp
from flax.traverse_util import flatten_dict, unflatten_dict
from jax.random import PRNGKey
from ..utils import logging
lowerCAmelCase__ :int = logging.get_logger(__name__)
def lowerCAmelCase__ ( a__: Dict ) -> List[str]:
'''simple docstring'''
_UpperCAmelCase = R'\w+[.]\d+'
_UpperCAmelCase = re.findall(a__ , a__ )
for pat in pats:
_UpperCAmelCase = key.replace(a__ , '_'.join(pat.split('.' ) ) )
return key
def lowerCAmelCase__ ( a__: Optional[int] , a__: Dict , a__: List[Any] ) -> str:
'''simple docstring'''
_UpperCAmelCase = pt_tuple_key[:-1] + ('scale',)
if (
any('norm' in str_ for str_ in pt_tuple_key )
and (pt_tuple_key[-1] == "bias")
and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict)
and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict)
):
_UpperCAmelCase = pt_tuple_key[:-1] + ('scale',)
return renamed_pt_tuple_key, pt_tensor
elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict:
_UpperCAmelCase = pt_tuple_key[:-1] + ('scale',)
return renamed_pt_tuple_key, pt_tensor
# embedding
if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict:
_UpperCAmelCase = pt_tuple_key[:-1] + ('embedding',)
return renamed_pt_tuple_key, pt_tensor
# conv layer
_UpperCAmelCase = pt_tuple_key[:-1] + ('kernel',)
if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4:
_UpperCAmelCase = pt_tensor.transpose(2 , 3 , 1 , 0 )
return renamed_pt_tuple_key, pt_tensor
# linear layer
_UpperCAmelCase = pt_tuple_key[:-1] + ('kernel',)
if pt_tuple_key[-1] == "weight":
_UpperCAmelCase = pt_tensor.T
return renamed_pt_tuple_key, pt_tensor
# old PyTorch layer norm weight
_UpperCAmelCase = pt_tuple_key[:-1] + ('weight',)
if pt_tuple_key[-1] == "gamma":
return renamed_pt_tuple_key, pt_tensor
# old PyTorch layer norm bias
_UpperCAmelCase = pt_tuple_key[:-1] + ('bias',)
if pt_tuple_key[-1] == "beta":
return renamed_pt_tuple_key, pt_tensor
return pt_tuple_key, pt_tensor
def lowerCAmelCase__ ( a__: Any , a__: Optional[Any] , a__: int=4_2 ) -> List[str]:
'''simple docstring'''
_UpperCAmelCase = {k: v.numpy() for k, v in pt_state_dict.items()}
# Step 2: Since the model is stateless, get random Flax params
_UpperCAmelCase = flax_model.init_weights(PRNGKey(a__ ) )
_UpperCAmelCase = flatten_dict(a__ )
_UpperCAmelCase = {}
# Need to change some parameters name to match Flax names
for pt_key, pt_tensor in pt_state_dict.items():
_UpperCAmelCase = rename_key(a__ )
_UpperCAmelCase = tuple(renamed_pt_key.split('.' ) )
# Correctly rename weight parameters
_UpperCAmelCase , _UpperCAmelCase = rename_key_and_reshape_tensor(a__ , a__ , a__ )
if flax_key in random_flax_state_dict:
if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
raise ValueError(
F'''PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape '''
F'''{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.''' )
# also add unexpected weight so that warning is thrown
_UpperCAmelCase = jnp.asarray(a__ )
return unflatten_dict(a__ )
| 618 | 1 |
'''simple docstring'''
import re
import tempfile
from pathlib import Path
import pytest
import yaml
from datasets.utils.readme import ReadMe
# @pytest.fixture
# def example_yaml_structure():
snake_case_ = yaml.safe_load(
"""\
name: \"\"
allow_empty: false
allow_empty_text: true
subsections:
- name: \"Dataset Card for X\" # First-level markdown heading
allow_empty: false
allow_empty_text: true
subsections:
- name: \"Table of Contents\"
allow_empty: false
allow_empty_text: false
subsections: null
- name: \"Dataset Description\"
allow_empty: false
allow_empty_text: false
subsections:
- name: \"Dataset Summary\"
allow_empty: false
allow_empty_text: false
subsections: null
- name: \"Supported Tasks and Leaderboards\"
allow_empty: true
allow_empty_text: true
subsections: null
- name: Languages
allow_empty: false
allow_empty_text: true
subsections: null
"""
)
snake_case_ = {
"""name""": """root""",
"""text""": """""",
"""is_empty_text""": True,
"""subsections""": [
{
"""name""": """Dataset Card for My Dataset""",
"""text""": """""",
"""is_empty_text""": True,
"""subsections""": [
{"""name""": """Table of Contents""", """text""": """Some text here.""", """is_empty_text""": False, """subsections""": []},
{
"""name""": """Dataset Description""",
"""text""": """Some text here.""",
"""is_empty_text""": False,
"""subsections""": [
{
"""name""": """Dataset Summary""",
"""text""": """Some text here.""",
"""is_empty_text""": False,
"""subsections""": [],
},
{
"""name""": """Supported Tasks and Leaderboards""",
"""text""": """""",
"""is_empty_text""": True,
"""subsections""": [],
},
{"""name""": """Languages""", """text""": """Language Text""", """is_empty_text""": False, """subsections""": []},
],
},
],
}
],
}
snake_case_ = """\
---
language:
- zh
- en
---
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""
snake_case_ = """\
---
language:
- zh
- en
---
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
#### Extra Ignored Subsection
### Supported Tasks and Leaderboards
### Languages
Language Text
"""
snake_case_ = {
"""name""": """root""",
"""text""": """""",
"""is_empty_text""": True,
"""subsections""": [
{
"""name""": """Dataset Card for My Dataset""",
"""text""": """""",
"""is_empty_text""": True,
"""subsections""": [
{"""name""": """Table of Contents""", """text""": """Some text here.""", """is_empty_text""": False, """subsections""": []},
{
"""name""": """Dataset Description""",
"""text""": """Some text here.""",
"""is_empty_text""": False,
"""subsections""": [
{
"""name""": """Dataset Summary""",
"""text""": """Some text here.""",
"""is_empty_text""": False,
"""subsections""": [
{
"""name""": """Extra Ignored Subsection""",
"""text""": """""",
"""is_empty_text""": True,
"""subsections""": [],
}
],
},
{
"""name""": """Supported Tasks and Leaderboards""",
"""text""": """""",
"""is_empty_text""": True,
"""subsections""": [],
},
{"""name""": """Languages""", """text""": """Language Text""", """is_empty_text""": False, """subsections""": []},
],
},
],
}
],
}
snake_case_ = """\
---
---
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""
snake_case_ = (
"""The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README."""
)
snake_case_ = """\
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""
snake_case_ = (
"""The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README."""
)
snake_case_ = """\
---
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""
snake_case_ = """The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README."""
snake_case_ = """\
---
language:
- zh
- en
---
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
### Supported Tasks and Leaderboards
### Languages
Language Text
"""
snake_case_ = """The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored)."""
snake_case_ = """\
---
language:
- zh
- en
---
# Dataset Card for My Dataset
"""
snake_case_ = """The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found 'None'."""
snake_case_ = """\
---
language:
- zh
- en
---
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Languages
Language Text
"""
snake_case_ = """The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`."""
snake_case_ = """\
---
language:
- zh
- en
---
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
"""
snake_case_ = """The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty."""
snake_case_ = """\
---
language:
- zh
- en
---
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""
snake_case_ = """The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README."""
snake_case_ = """\
---
language:
- zh
- en
---
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
# Dataset Card My Dataset
"""
snake_case_ = """The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README."""
snake_case_ = """\
---
language:
- zh
- en
---
# Dataset Card My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""
snake_case_ = """The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README."""
snake_case_ = """"""
snake_case_ = """The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README."""
snake_case_ = """\
---
language:
- zh
- en
---
# Dataset Card for My Dataset
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""
snake_case_ = """The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections."""
@pytest.mark.parametrize(
'''readme_md, expected_dict''' , [
(README_CORRECT, CORRECT_DICT),
(README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL),
] , )
def __lowercase (_SCREAMING_SNAKE_CASE :int , _SCREAMING_SNAKE_CASE :str ):
assert ReadMe.from_string(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to_dict() == expected_dict
@pytest.mark.parametrize(
'''readme_md, expected_error''' , [
(README_NO_YAML, EXPECTED_ERROR_README_NO_YAML),
(README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML),
(README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML),
(README_EMPTY, EXPECTED_ERROR_README_EMPTY),
(README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION),
(README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL),
(README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION),
(README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT),
(README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL),
(README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL),
(README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT),
] , )
def __lowercase (_SCREAMING_SNAKE_CASE :Optional[int] , _SCREAMING_SNAKE_CASE :Any ):
with pytest.raises(_SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path='''root''' ) ) ):
SCREAMING_SNAKE_CASE : str = ReadMe.from_string(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
readme.validate()
@pytest.mark.parametrize(
'''readme_md, expected_error''' , [
(README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1),
] , )
def __lowercase (_SCREAMING_SNAKE_CASE :int , _SCREAMING_SNAKE_CASE :int ):
with pytest.raises(_SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path='''root''' ) ) ):
ReadMe.from_string(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
@pytest.mark.parametrize(
'''readme_md,''' , [
(README_MULTIPLE_SAME_HEADING_1),
] , )
def __lowercase (_SCREAMING_SNAKE_CASE :Optional[Any] ):
ReadMe.from_string(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , suppress_parsing_errors=_SCREAMING_SNAKE_CASE )
@pytest.mark.parametrize(
'''readme_md, expected_dict''' , [
(README_CORRECT, CORRECT_DICT),
(README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL),
] , )
def __lowercase (_SCREAMING_SNAKE_CASE :int , _SCREAMING_SNAKE_CASE :Optional[Any] ):
with tempfile.TemporaryDirectory() as tmp_dir:
SCREAMING_SNAKE_CASE : int = Path(_SCREAMING_SNAKE_CASE ) / '''README.md'''
with open(_SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file:
readme_file.write(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE : Union[str, Any] = ReadMe.from_readme(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to_dict()
assert out["name"] == path
assert out["text"] == ""
assert out["is_empty_text"]
assert out["subsections"] == expected_dict["subsections"]
@pytest.mark.parametrize(
'''readme_md, expected_error''' , [
(README_NO_YAML, EXPECTED_ERROR_README_NO_YAML),
(README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML),
(README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML),
(README_EMPTY, EXPECTED_ERROR_README_EMPTY),
(README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION),
(README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL),
(README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION),
(README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT),
(README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL),
(README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL),
(README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT),
] , )
def __lowercase (_SCREAMING_SNAKE_CASE :Any , _SCREAMING_SNAKE_CASE :List[str] ):
with tempfile.TemporaryDirectory() as tmp_dir:
SCREAMING_SNAKE_CASE : Optional[int] = Path(_SCREAMING_SNAKE_CASE ) / '''README.md'''
with open(_SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file:
readme_file.write(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE : Optional[int] = expected_error.format(path=_SCREAMING_SNAKE_CASE )
with pytest.raises(_SCREAMING_SNAKE_CASE , match=re.escape(_SCREAMING_SNAKE_CASE ) ):
SCREAMING_SNAKE_CASE : Any = ReadMe.from_readme(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
readme.validate()
@pytest.mark.parametrize(
'''readme_md, expected_error''' , [
(README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1),
] , )
def __lowercase (_SCREAMING_SNAKE_CASE :List[str] , _SCREAMING_SNAKE_CASE :Optional[int] ):
with tempfile.TemporaryDirectory() as tmp_dir:
SCREAMING_SNAKE_CASE : Tuple = Path(_SCREAMING_SNAKE_CASE ) / '''README.md'''
with open(_SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file:
readme_file.write(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE : str = expected_error.format(path=_SCREAMING_SNAKE_CASE )
with pytest.raises(_SCREAMING_SNAKE_CASE , match=re.escape(_SCREAMING_SNAKE_CASE ) ):
ReadMe.from_readme(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
@pytest.mark.parametrize(
'''readme_md,''' , [
(README_MULTIPLE_SAME_HEADING_1),
] , )
def __lowercase (_SCREAMING_SNAKE_CASE :Optional[int] ):
with tempfile.TemporaryDirectory() as tmp_dir:
SCREAMING_SNAKE_CASE : Optional[int] = Path(_SCREAMING_SNAKE_CASE ) / '''README.md'''
with open(_SCREAMING_SNAKE_CASE , '''w+''' ) as readme_file:
readme_file.write(_SCREAMING_SNAKE_CASE )
ReadMe.from_readme(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , suppress_parsing_errors=_SCREAMING_SNAKE_CASE )
| 706 |
'''simple docstring'''
from __future__ import annotations
def __lowercase (_SCREAMING_SNAKE_CASE :int | str ):
SCREAMING_SNAKE_CASE : int = str(_SCREAMING_SNAKE_CASE )
return n == n[::-1]
def __lowercase (_SCREAMING_SNAKE_CASE :int = 1_00_00_00 ):
SCREAMING_SNAKE_CASE : int = 0
for i in range(1 , _SCREAMING_SNAKE_CASE ):
if is_palindrome(_SCREAMING_SNAKE_CASE ) and is_palindrome(bin(_SCREAMING_SNAKE_CASE ).split('''b''' )[1] ):
total += i
return total
if __name__ == "__main__":
print(solution(int(str(input().strip()))))
| 355 | 0 |
'''simple docstring'''
def lowerCAmelCase (__A):
"""simple docstring"""
if isinstance(__A , __A):
raise TypeError('''\'float\' object cannot be interpreted as an integer''')
if isinstance(__A , __A):
raise TypeError('''\'str\' object cannot be interpreted as an integer''')
if num == 0:
return "0b0"
_a = False
if num < 0:
_a = True
_a = -num
_a = []
while num > 0:
binary.insert(0 , num % 2)
num >>= 1
if negative:
return "-0b" + "".join(str(__A) for e in binary)
return "0b" + "".join(str(__A) for e in binary)
if __name__ == "__main__":
import doctest
doctest.testmod()
| 11 |
'''simple docstring'''
class __A :
'''simple docstring'''
def __init__(self , A ) -> None:
"""simple docstring"""
_a = len(A )
_a = [0] * len_array
if len_array > 0:
_a = array[0]
for i in range(1 , A ):
_a = self.prefix_sum[i - 1] + array[i]
def a__ (self , A , A ) -> int:
"""simple docstring"""
if start == 0:
return self.prefix_sum[end]
return self.prefix_sum[end] - self.prefix_sum[start - 1]
def a__ (self , A ) -> bool:
"""simple docstring"""
_a = {0}
for sum_item in self.prefix_sum:
if sum_item - target_sum in sums:
return True
sums.add(A )
return False
if __name__ == "__main__":
import doctest
doctest.testmod()
| 11 | 1 |
"""simple docstring"""
from typing import Callable, Dict, Optional, Tuple
import torch
from torch import nn
from torch.distributions import (
AffineTransform,
Distribution,
Independent,
NegativeBinomial,
Normal,
StudentT,
TransformedDistribution,
)
class A__ ( __lowercase):
"""simple docstring"""
def __init__( self: List[Any] , __a: Distribution , __a: List[Any]=None , __a: Optional[int]=None , __a: Union[str, Any]=0 )-> Any:
lowerCamelCase : Any = 1.0 if scale is None else scale
lowerCamelCase : int = 0.0 if loc is None else loc
super().__init__(__a , [AffineTransform(loc=self.loc , scale=self.scale , event_dim=__a )] )
@property
def a__ ( self: Tuple )-> Union[str, Any]:
return self.base_dist.mean * self.scale + self.loc
@property
def a__ ( self: Dict )-> List[str]:
return self.base_dist.variance * self.scale**2
@property
def a__ ( self: List[str] )-> int:
return self.variance.sqrt()
class A__ ( nn.Module):
"""simple docstring"""
def __init__( self: Optional[int] , __a: int , __a: Dict[str, int] , __a: Callable[..., Tuple[torch.Tensor]] , **__a: Optional[Any] )-> None:
super().__init__(**__a )
lowerCamelCase : Optional[int] = args_dim
lowerCamelCase : List[str] = nn.ModuleList([nn.Linear(__a , __a ) for dim in args_dim.values()] )
lowerCamelCase : str = domain_map
def a__ ( self: List[str] , __a: torch.Tensor )-> Tuple[torch.Tensor]:
lowerCamelCase : List[Any] = [proj(__a ) for proj in self.proj]
return self.domain_map(*__a )
class A__ ( nn.Module):
"""simple docstring"""
def __init__( self: Union[str, Any] , __a: str )-> Tuple:
super().__init__()
lowerCamelCase : Any = function
def a__ ( self: str , __a: Union[str, Any] , *__a: Optional[Any] )-> Any:
return self.function(__a , *__a )
class A__ :
"""simple docstring"""
snake_case__ : type
snake_case__ : int
snake_case__ : Dict[str, int]
def __init__( self: Dict , __a: int = 1 )-> None:
lowerCamelCase : List[Any] = dim
lowerCamelCase : List[Any] = {k: dim * self.args_dim[k] for k in self.args_dim}
def a__ ( self: List[str] , __a: Dict )-> List[Any]:
if self.dim == 1:
return self.distribution_class(*__a )
else:
return Independent(self.distribution_class(*__a ) , 1 )
def a__ ( self: Any , __a: str , __a: Optional[torch.Tensor] = None , __a: Optional[torch.Tensor] = None , )-> Distribution:
lowerCamelCase : Union[str, Any] = self._base_distribution(__a )
if loc is None and scale is None:
return distr
else:
return AffineTransformed(__a , loc=__a , scale=__a , event_dim=self.event_dim )
@property
def a__ ( self: str )-> Tuple:
return () if self.dim == 1 else (self.dim,)
@property
def a__ ( self: Union[str, Any] )-> int:
return len(self.event_shape )
@property
def a__ ( self: Dict )-> float:
return 0.0
def a__ ( self: Union[str, Any] , __a: int )-> nn.Module:
return ParameterProjection(
in_features=__a , args_dim=self.args_dim , domain_map=LambdaLayer(self.domain_map ) , )
def a__ ( self: Any , *__a: torch.Tensor )-> str:
raise NotImplementedError()
@staticmethod
def a__ ( __a: torch.Tensor )-> torch.Tensor:
return (x + torch.sqrt(torch.square(__a ) + 4.0 )) / 2.0
class A__ ( __lowercase):
"""simple docstring"""
snake_case__ : Dict[str, int] ={"df": 1, "loc": 1, "scale": 1}
snake_case__ : type =StudentT
@classmethod
def a__ ( cls: Optional[Any] , __a: torch.Tensor , __a: torch.Tensor , __a: torch.Tensor )-> Tuple:
lowerCamelCase : Optional[Any] = cls.squareplus(__a ).clamp_min(torch.finfo(scale.dtype ).eps )
lowerCamelCase : Optional[int] = 2.0 + cls.squareplus(__a )
return df.squeeze(-1 ), loc.squeeze(-1 ), scale.squeeze(-1 )
class A__ ( __lowercase):
"""simple docstring"""
snake_case__ : Dict[str, int] ={"loc": 1, "scale": 1}
snake_case__ : type =Normal
@classmethod
def a__ ( cls: Optional[int] , __a: torch.Tensor , __a: torch.Tensor )-> str:
lowerCamelCase : int = cls.squareplus(__a ).clamp_min(torch.finfo(scale.dtype ).eps )
return loc.squeeze(-1 ), scale.squeeze(-1 )
class A__ ( __lowercase):
"""simple docstring"""
snake_case__ : Dict[str, int] ={"total_count": 1, "logits": 1}
snake_case__ : type =NegativeBinomial
@classmethod
def a__ ( cls: Tuple , __a: torch.Tensor , __a: torch.Tensor )-> Union[str, Any]:
lowerCamelCase : int = cls.squareplus(__a )
return total_count.squeeze(-1 ), logits.squeeze(-1 )
def a__ ( self: List[Any] , __a: Union[str, Any] )-> Distribution:
lowerCamelCase : Optional[int] = distr_args
if self.dim == 1:
return self.distribution_class(total_count=__a , logits=__a )
else:
return Independent(self.distribution_class(total_count=__a , logits=__a ) , 1 )
def a__ ( self: str , __a: Any , __a: Optional[torch.Tensor] = None , __a: Optional[torch.Tensor] = None )-> Distribution:
lowerCamelCase : List[str] = distr_args
if scale is not None:
# See scaling property of Gamma.
logits += scale.log()
return self._base_distribution((total_count, logits) )
| 708 |
"""simple docstring"""
from typing import List, Optional, Union
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCamelCase :str = logging.get_logger(__name__)
__lowerCamelCase :Any = {
'huggingface/time-series-transformer-tourism-monthly': (
'https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json'
),
# See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer
}
class A__ ( __lowercase):
"""simple docstring"""
snake_case__ : List[Any] ='''time_series_transformer'''
snake_case__ : List[Any] ={
'''hidden_size''': '''d_model''',
'''num_attention_heads''': '''encoder_attention_heads''',
'''num_hidden_layers''': '''encoder_layers''',
}
def __init__( self: List[str] , __a: Optional[int] = None , __a: Optional[int] = None , __a: str = "student_t" , __a: str = "nll" , __a: int = 1 , __a: List[int] = [1, 2, 3, 4, 5, 6, 7] , __a: Optional[Union[str, bool]] = "mean" , __a: int = 0 , __a: int = 0 , __a: int = 0 , __a: int = 0 , __a: Optional[List[int]] = None , __a: Optional[List[int]] = None , __a: int = 32 , __a: int = 32 , __a: int = 2 , __a: int = 2 , __a: int = 2 , __a: int = 2 , __a: bool = True , __a: str = "gelu" , __a: int = 64 , __a: float = 0.1 , __a: float = 0.1 , __a: float = 0.1 , __a: float = 0.1 , __a: float = 0.1 , __a: int = 100 , __a: float = 0.02 , __a: Tuple=True , **__a: str , )-> Any:
# time series specific configuration
lowerCamelCase : str = prediction_length
lowerCamelCase : Optional[Any] = context_length or prediction_length
lowerCamelCase : Tuple = distribution_output
lowerCamelCase : Any = loss
lowerCamelCase : List[Any] = input_size
lowerCamelCase : int = num_time_features
lowerCamelCase : Dict = lags_sequence
lowerCamelCase : Optional[int] = scaling
lowerCamelCase : int = num_dynamic_real_features
lowerCamelCase : Tuple = num_static_real_features
lowerCamelCase : Any = num_static_categorical_features
if cardinality and num_static_categorical_features > 0:
if len(__a ) != num_static_categorical_features:
raise ValueError(
"""The cardinality should be a list of the same length as `num_static_categorical_features`""" )
lowerCamelCase : int = cardinality
else:
lowerCamelCase : Dict = [0]
if embedding_dimension and num_static_categorical_features > 0:
if len(__a ) != num_static_categorical_features:
raise ValueError(
"""The embedding dimension should be a list of the same length as `num_static_categorical_features`""" )
lowerCamelCase : str = embedding_dimension
else:
lowerCamelCase : str = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality]
lowerCamelCase : Any = num_parallel_samples
# Transformer architecture configuration
lowerCamelCase : Any = input_size * len(__a ) + self._number_of_features
lowerCamelCase : List[str] = d_model
lowerCamelCase : Tuple = encoder_attention_heads
lowerCamelCase : Optional[int] = decoder_attention_heads
lowerCamelCase : Union[str, Any] = encoder_ffn_dim
lowerCamelCase : str = decoder_ffn_dim
lowerCamelCase : str = encoder_layers
lowerCamelCase : Any = decoder_layers
lowerCamelCase : Optional[int] = dropout
lowerCamelCase : List[str] = attention_dropout
lowerCamelCase : Tuple = activation_dropout
lowerCamelCase : Optional[int] = encoder_layerdrop
lowerCamelCase : int = decoder_layerdrop
lowerCamelCase : Optional[int] = activation_function
lowerCamelCase : Optional[Any] = init_std
lowerCamelCase : Optional[Any] = use_cache
super().__init__(is_encoder_decoder=__a , **__a )
@property
def a__ ( self: int )-> int:
return (
sum(self.embedding_dimension )
+ self.num_dynamic_real_features
+ self.num_time_features
+ self.num_static_real_features
+ self.input_size * 2 # the log1p(abs(loc)) and log(scale) features
)
| 42 | 0 |
class __lowerCAmelCase :
"""simple docstring"""
def __init__( self : Tuple , _lowerCAmelCase : str , _lowerCAmelCase : int ) -> str:
"""simple docstring"""
snake_case_ = name
snake_case_ = val
def __str__( self : List[Any] ) -> List[str]:
"""simple docstring"""
return F'''{self.__class__.__name__}({self.name}, {self.val})'''
def __lt__( self : List[Any] , _lowerCAmelCase : Tuple ) -> List[Any]:
"""simple docstring"""
return self.val < other.val
class __lowerCAmelCase :
"""simple docstring"""
def __init__( self : Dict , _lowerCAmelCase : int ) -> Any:
"""simple docstring"""
snake_case_ = {}
snake_case_ = {}
snake_case_ = self.build_heap(__UpperCamelCase )
def __getitem__( self : Tuple , _lowerCAmelCase : Any ) -> Optional[int]:
"""simple docstring"""
return self.get_value(__UpperCamelCase )
def lowerCAmelCase__ ( self : Any , _lowerCAmelCase : Union[str, Any] ) -> Optional[int]:
"""simple docstring"""
return (idx - 1) // 2
def lowerCAmelCase__ ( self : List[str] , _lowerCAmelCase : List[Any] ) -> Optional[Any]:
"""simple docstring"""
return idx * 2 + 1
def lowerCAmelCase__ ( self : Optional[int] , _lowerCAmelCase : List[str] ) -> str:
"""simple docstring"""
return idx * 2 + 2
def lowerCAmelCase__ ( self : Any , _lowerCAmelCase : int ) -> List[str]:
"""simple docstring"""
return self.heap_dict[key]
def lowerCAmelCase__ ( self : List[Any] , _lowerCAmelCase : List[str] ) -> Optional[Any]:
"""simple docstring"""
snake_case_ = len(__UpperCamelCase ) - 1
snake_case_ = self.get_parent_idx(__UpperCamelCase )
for idx, i in enumerate(__UpperCamelCase ):
snake_case_ = idx
snake_case_ = i.val
for i in range(__UpperCamelCase , -1 , -1 ):
self.sift_down(__UpperCamelCase , __UpperCamelCase )
return array
def lowerCAmelCase__ ( self : Any , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : Dict ) -> int:
"""simple docstring"""
while True:
snake_case_ = self.get_left_child_idx(__UpperCamelCase ) # noqa: E741
snake_case_ = self.get_right_child_idx(__UpperCamelCase )
snake_case_ = idx
if l < len(__UpperCamelCase ) and array[l] < array[idx]:
snake_case_ = l
if r < len(__UpperCamelCase ) and array[r] < array[smallest]:
snake_case_ = r
if smallest != idx:
snake_case_ , snake_case_ = array[smallest], array[idx]
(
(
snake_case_
) , (
snake_case_
) ,
) = (
self.idx_of_element[array[smallest]],
self.idx_of_element[array[idx]],
)
snake_case_ = smallest
else:
break
def lowerCAmelCase__ ( self : List[str] , _lowerCAmelCase : Any ) -> int:
"""simple docstring"""
snake_case_ = self.get_parent_idx(__UpperCamelCase )
while p >= 0 and self.heap[p] > self.heap[idx]:
snake_case_ , snake_case_ = self.heap[idx], self.heap[p]
snake_case_ , snake_case_ = (
self.idx_of_element[self.heap[idx]],
self.idx_of_element[self.heap[p]],
)
snake_case_ = p
snake_case_ = self.get_parent_idx(__UpperCamelCase )
def lowerCAmelCase__ ( self : Optional[int] ) -> List[Any]:
"""simple docstring"""
return self.heap[0]
def lowerCAmelCase__ ( self : Tuple ) -> Any:
"""simple docstring"""
snake_case_ , snake_case_ = self.heap[-1], self.heap[0]
snake_case_ , snake_case_ = (
self.idx_of_element[self.heap[-1]],
self.idx_of_element[self.heap[0]],
)
snake_case_ = self.heap.pop()
del self.idx_of_element[x]
self.sift_down(0 , self.heap )
return x
def lowerCAmelCase__ ( self : List[str] , _lowerCAmelCase : Tuple ) -> Tuple:
"""simple docstring"""
self.heap.append(__UpperCamelCase )
snake_case_ = len(self.heap ) - 1
snake_case_ = node.val
self.sift_up(len(self.heap ) - 1 )
def lowerCAmelCase__ ( self : Dict ) -> Dict:
"""simple docstring"""
return len(self.heap ) == 0
def lowerCAmelCase__ ( self : Optional[int] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : str ) -> int:
"""simple docstring"""
assert (
self.heap[self.idx_of_element[node]].val > new_value
), "newValue must be less that current value"
snake_case_ = new_value
snake_case_ = new_value
self.sift_up(self.idx_of_element[node] )
SCREAMING_SNAKE_CASE :Dict = Node('''R''', -1)
SCREAMING_SNAKE_CASE :List[Any] = Node('''B''', 6)
SCREAMING_SNAKE_CASE :List[str] = Node('''A''', 3)
SCREAMING_SNAKE_CASE :Optional[Any] = Node('''X''', 1)
SCREAMING_SNAKE_CASE :List[Any] = Node('''E''', 4)
# Use one of these two ways to generate Min-Heap
# Generating Min-Heap from array
SCREAMING_SNAKE_CASE :Union[str, Any] = MinHeap([r, b, a, x, e])
# Generating Min-Heap by Insert method
# myMinHeap.insert(a)
# myMinHeap.insert(b)
# myMinHeap.insert(x)
# myMinHeap.insert(r)
# myMinHeap.insert(e)
# Before
print('''Min Heap - before decrease key''')
for i in my_min_heap.heap:
print(i)
print('''Min Heap - After decrease key of node [B -> -17]''')
my_min_heap.decrease_key(b, -17)
# After
for i in my_min_heap.heap:
print(i)
if __name__ == "__main__":
import doctest
doctest.testmod()
| 283 |
import unittest
from accelerate import debug_launcher
from accelerate.test_utils import require_cpu, test_ops, test_script
@require_cpu
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
def __lowerCAmelCase ( self ):
"""simple docstring"""
debug_launcher(test_script.main )
def __lowerCAmelCase ( self ):
"""simple docstring"""
debug_launcher(test_ops.main )
| 187 | 0 |
"""simple docstring"""
from operator import delitem, getitem, setitem
import pytest
from data_structures.hashing.hash_map import HashMap
def UpperCamelCase_ ( lowerCAmelCase__ : Optional[int] ) -> Any:
"""simple docstring"""
return getitem, k
def UpperCamelCase_ ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : int ) -> Any:
"""simple docstring"""
return setitem, k, v
def UpperCamelCase_ ( lowerCAmelCase__ : Tuple ) -> Optional[Any]:
"""simple docstring"""
return delitem, k
def UpperCamelCase_ ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Optional[int] , *lowerCAmelCase__ : List[str] ) -> Union[str, Any]:
"""simple docstring"""
try:
return fun(lowerCAmelCase__ , *lowerCAmelCase__ ), None
except Exception as e:
return None, e
lowercase__ : Optional[Any] = (
_set("""key_a""", """val_a"""),
_set("""key_b""", """val_b"""),
)
lowercase__ : Union[str, Any] = [
_set("""key_a""", """val_a"""),
_set("""key_a""", """val_b"""),
]
lowercase__ : Optional[int] = [
_set("""key_a""", """val_a"""),
_set("""key_b""", """val_b"""),
_del("""key_a"""),
_del("""key_b"""),
_set("""key_a""", """val_a"""),
_del("""key_a"""),
]
lowercase__ : Optional[int] = [
_get("""key_a"""),
_del("""key_a"""),
_set("""key_a""", """val_a"""),
_del("""key_a"""),
_del("""key_a"""),
_get("""key_a"""),
]
lowercase__ : str = [
*[_set(x, x) for x in range(5)], # guaranteed upsize
]
lowercase__ : Any = [
*[_set(x, x) for x in range(5)], # guaranteed upsize
*[_del(x) for x in range(5)],
_set("""key_a""", """val_b"""),
]
@pytest.mark.parametrize(
'operations' , (
pytest.param(_add_items , id='add items' ),
pytest.param(_overwrite_items , id='overwrite items' ),
pytest.param(_delete_items , id='delete items' ),
pytest.param(_access_absent_items , id='access absent items' ),
pytest.param(_add_with_resize_up , id='add with resize up' ),
pytest.param(_add_with_resize_down , id='add with resize down' ),
) , )
def UpperCamelCase_ ( lowerCAmelCase__ : str ) -> str:
"""simple docstring"""
lowerCAmelCase_ : List[Any] = HashMap(initial_block_size=4 )
lowerCAmelCase_ : List[Any] = {}
for _, (fun, *args) in enumerate(lowerCAmelCase__ ):
lowerCAmelCase_ ,lowerCAmelCase_ : Dict = _run_operation(lowerCAmelCase__ , lowerCAmelCase__ , *lowerCAmelCase__ )
lowerCAmelCase_ ,lowerCAmelCase_ : List[Any] = _run_operation(lowerCAmelCase__ , lowerCAmelCase__ , *lowerCAmelCase__ )
assert my_res == py_res
assert str(lowerCAmelCase__ ) == str(lowerCAmelCase__ )
assert set(lowerCAmelCase__ ) == set(lowerCAmelCase__ )
assert len(lowerCAmelCase__ ) == len(lowerCAmelCase__ )
assert set(my.items() ) == set(py.items() )
def UpperCamelCase_ ( ) -> Any:
"""simple docstring"""
def is_public(lowerCAmelCase__ : str ) -> bool:
return not name.startswith('_' )
lowerCAmelCase_ : List[str] = {name for name in dir({} ) if is_public(lowerCAmelCase__ )}
lowerCAmelCase_ : str = {name for name in dir(HashMap() ) if is_public(lowerCAmelCase__ )}
assert dict_public_names > hash_public_names
| 317 |
"""simple docstring"""
def UpperCamelCase_ ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Any ) -> int:
"""simple docstring"""
lowerCAmelCase_ : Tuple = 0
while b > 0:
if b & 1:
res += a
a += a
b >>= 1
return res
def UpperCamelCase_ ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Any , lowerCAmelCase__ : List[Any] ) -> Dict:
"""simple docstring"""
lowerCAmelCase_ : List[Any] = 0
while b > 0:
if b & 1:
lowerCAmelCase_ : int = ((res % c) + (a % c)) % c
a += a
b >>= 1
return res
| 317 | 1 |
'''simple docstring'''
from __future__ import annotations
import inspect
import unittest
from math import floor
import numpy as np
from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TFCvtForImageClassification, TFCvtModel
from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class SCREAMING_SNAKE_CASE ( lowercase_ ):
'''simple docstring'''
def __UpperCAmelCase ( self : Tuple ):
"""simple docstring"""
_snake_case : int = self.config_class(**self.inputs_dict )
self.parent.assertTrue(hasattr(a__ , 'embed_dim' ) )
self.parent.assertTrue(hasattr(a__ , 'num_heads' ) )
class SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__( self : Optional[Any] , snake_case : Optional[int] , snake_case : Union[str, Any]=13 , snake_case : List[str]=64 , snake_case : Optional[Any]=3 , snake_case : int=[16, 48, 96] , snake_case : Optional[Any]=[1, 3, 6] , snake_case : int=[1, 2, 10] , snake_case : str=[7, 3, 3] , snake_case : List[str]=[4, 2, 2] , snake_case : Optional[Any]=[2, 1, 1] , snake_case : Optional[Any]=[2, 2, 2] , snake_case : Optional[Any]=[False, False, True] , snake_case : int=[0.0, 0.0, 0.0] , snake_case : Optional[Any]=0.02 , snake_case : Optional[int]=1e-12 , snake_case : List[Any]=True , snake_case : List[str]=True , snake_case : Optional[Any]=2 , ):
"""simple docstring"""
_snake_case : Tuple = parent
_snake_case : Optional[Any] = batch_size
_snake_case : int = image_size
_snake_case : Optional[Any] = patch_sizes
_snake_case : List[str] = patch_stride
_snake_case : Tuple = patch_padding
_snake_case : int = is_training
_snake_case : str = use_labels
_snake_case : Tuple = num_labels
_snake_case : Dict = num_channels
_snake_case : List[Any] = embed_dim
_snake_case : List[str] = num_heads
_snake_case : Optional[int] = stride_kv
_snake_case : Dict = depth
_snake_case : str = cls_token
_snake_case : Tuple = attention_drop_rate
_snake_case : List[Any] = initializer_range
_snake_case : int = layer_norm_eps
def __UpperCAmelCase ( self : Optional[int] ):
"""simple docstring"""
_snake_case : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
_snake_case : int = None
if self.use_labels:
# create a random int32 tensor of given shape
_snake_case : Union[str, Any] = ids_tensor([self.batch_size] , self.num_labels )
_snake_case : Union[str, Any] = self.get_config()
return config, pixel_values, labels
def __UpperCAmelCase ( self : Optional[Any] ):
"""simple docstring"""
return CvtConfig(
image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , )
def __UpperCAmelCase ( self : List[str] , snake_case : int , snake_case : Union[str, Any] , snake_case : Optional[int] ):
"""simple docstring"""
_snake_case : Optional[int] = TFCvtModel(config=a__ )
_snake_case : Optional[int] = model(a__ , training=a__ )
_snake_case : List[Any] = (self.image_size, self.image_size)
_snake_case , _snake_case : str = image_size[0], image_size[1]
for i in range(len(self.depth ) ):
_snake_case : Optional[Any] = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 )
_snake_case : Tuple = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) )
def __UpperCAmelCase ( self : str , snake_case : Any , snake_case : Dict , snake_case : List[str] ):
"""simple docstring"""
_snake_case : Dict = self.num_labels
_snake_case : Optional[int] = TFCvtForImageClassification(a__ )
_snake_case : Union[str, Any] = model(a__ , labels=a__ , training=a__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def __UpperCAmelCase ( self : List[str] ):
"""simple docstring"""
_snake_case : int = self.prepare_config_and_inputs()
_snake_case , _snake_case , _snake_case : Any = config_and_inputs
_snake_case : int = {'pixel_values': pixel_values}
return config, inputs_dict
@require_tf
class SCREAMING_SNAKE_CASE ( lowercase_ ,lowercase_ ,unittest.TestCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : List[str] = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
SCREAMING_SNAKE_CASE__ : Tuple = (
{"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification}
if is_tf_available()
else {}
)
SCREAMING_SNAKE_CASE__ : Optional[Any] = False
SCREAMING_SNAKE_CASE__ : Optional[Any] = False
SCREAMING_SNAKE_CASE__ : Optional[int] = False
SCREAMING_SNAKE_CASE__ : Union[str, Any] = False
SCREAMING_SNAKE_CASE__ : Dict = False
def __UpperCAmelCase ( self : str ):
"""simple docstring"""
_snake_case : Any = TFCvtModelTester(self )
_snake_case : Union[str, Any] = TFCvtConfigTester(self , config_class=a__ , has_text_modality=a__ , hidden_size=37 )
def __UpperCAmelCase ( self : List[Any] ):
"""simple docstring"""
self.config_tester.create_and_test_config_common_properties()
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
@unittest.skip(reason='Cvt does not output attentions' )
def __UpperCAmelCase ( self : Any ):
"""simple docstring"""
pass
@unittest.skip(reason='Cvt does not use inputs_embeds' )
def __UpperCAmelCase ( self : Any ):
"""simple docstring"""
pass
@unittest.skip(reason='Cvt does not support input and output embeddings' )
def __UpperCAmelCase ( self : List[str] ):
"""simple docstring"""
pass
@unittest.skipIf(
not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , )
def __UpperCAmelCase ( self : Tuple ):
"""simple docstring"""
super().test_dataset_conversion()
@unittest.skipIf(
not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , )
@slow
def __UpperCAmelCase ( self : List[Any] ):
"""simple docstring"""
super().test_keras_fit()
@unittest.skip(reason='Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8' )
def __UpperCAmelCase ( self : Optional[Any] ):
"""simple docstring"""
_snake_case : Union[str, Any] = tf.keras.mixed_precision.Policy('mixed_float16' )
tf.keras.mixed_precision.set_global_policy(a__ )
super().test_keras_fit()
tf.keras.mixed_precision.set_global_policy('float32' )
def __UpperCAmelCase ( self : Dict ):
"""simple docstring"""
_snake_case , _snake_case : str = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_snake_case : Optional[int] = model_class(a__ )
_snake_case : int = inspect.signature(model.call )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_snake_case : List[Any] = [*signature.parameters.keys()]
_snake_case : Union[str, Any] = ['pixel_values']
self.assertListEqual(arg_names[:1] , a__ )
def __UpperCAmelCase ( self : Tuple ):
"""simple docstring"""
def check_hidden_states_output(snake_case : List[Any] , snake_case : Tuple , snake_case : Dict ):
_snake_case : Dict = model_class(a__ )
_snake_case : Tuple = model(**self._prepare_for_class(a__ , a__ ) )
_snake_case : int = outputs.hidden_states
_snake_case : Union[str, Any] = len(self.model_tester.depth )
self.assertEqual(len(a__ ) , a__ )
# verify the first hidden states (first block)
self.assertListEqual(
list(hidden_states[0].shape[-3:] ) , [
self.model_tester.embed_dim[0],
self.model_tester.image_size // 4,
self.model_tester.image_size // 4,
] , )
_snake_case , _snake_case : Any = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_snake_case : Tuple = True
check_hidden_states_output(a__ , a__ , a__ )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
_snake_case : Union[str, Any] = True
check_hidden_states_output(a__ , a__ , a__ )
def __UpperCAmelCase ( self : Dict ):
"""simple docstring"""
_snake_case : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*a__ )
def __UpperCAmelCase ( self : List[str] ):
"""simple docstring"""
_snake_case : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*a__ )
@slow
def __UpperCAmelCase ( self : Tuple ):
"""simple docstring"""
for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_snake_case : Union[str, Any] = TFCvtModel.from_pretrained(a__ )
self.assertIsNotNone(a__ )
def lowerCamelCase__ ( ) -> Tuple:
"""simple docstring"""
_snake_case : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
return image
@require_tf
@require_vision
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
@cached_property
def __UpperCAmelCase ( self : List[str] ):
"""simple docstring"""
return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
@slow
def __UpperCAmelCase ( self : Tuple ):
"""simple docstring"""
_snake_case : str = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
_snake_case : Union[str, Any] = self.default_image_processor
_snake_case : Union[str, Any] = prepare_img()
_snake_case : int = image_processor(images=a__ , return_tensors='tf' )
# forward pass
_snake_case : int = model(**a__ )
# verify the logits
_snake_case : int = tf.TensorShape((1, 1000) )
self.assertEqual(outputs.logits.shape , a__ )
_snake_case : Optional[Any] = tf.constant([0.9285, 0.9015, -0.3150] )
self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , a__ , atol=1e-4 ) )
| 517 |
'''simple docstring'''
from dataclasses import dataclass
from typing import Optional
import numpy as np
import torch
import torch.nn as nn
from ..utils import BaseOutput, is_torch_version, randn_tensor
from .attention_processor import SpatialNorm
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block
@dataclass
class _snake_case ( lowercase_ ):
lowerCAmelCase_ : torch.FloatTensor
class _snake_case ( nn.Module ):
def __init__( self , a__=3 , a__=3 , a__=("DownEncoderBlock2D",) , a__=(64,) , a__=2 , a__=32 , a__="silu" , a__=True , ) -> Union[str, Any]:
'''simple docstring'''
super().__init__()
snake_case_ = layers_per_block
snake_case_ = torch.nn.Convad(
a__ , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , )
snake_case_ = None
snake_case_ = nn.ModuleList([] )
# down
snake_case_ = block_out_channels[0]
for i, down_block_type in enumerate(a__ ):
snake_case_ = output_channel
snake_case_ = block_out_channels[i]
snake_case_ = i == len(a__ ) - 1
snake_case_ = get_down_block(
a__ , num_layers=self.layers_per_block , in_channels=a__ , out_channels=a__ , add_downsample=not is_final_block , resnet_eps=1e-6 , downsample_padding=0 , resnet_act_fn=a__ , resnet_groups=a__ , attention_head_dim=a__ , temb_channels=a__ , )
self.down_blocks.append(a__ )
# mid
snake_case_ = UNetMidBlockaD(
in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=a__ , output_scale_factor=1 , resnet_time_scale_shift="default" , attention_head_dim=block_out_channels[-1] , resnet_groups=a__ , temb_channels=a__ , )
# out
snake_case_ = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=a__ , eps=1e-6 )
snake_case_ = nn.SiLU()
snake_case_ = 2 * out_channels if double_z else out_channels
snake_case_ = nn.Convad(block_out_channels[-1] , a__ , 3 , padding=1 )
snake_case_ = False
def lowerCAmelCase__ ( self , a__ ) -> Tuple:
'''simple docstring'''
snake_case_ = x
snake_case_ = self.conv_in(a__ )
if self.training and self.gradient_checkpointing:
def create_custom_forward(a__ ):
def custom_forward(*a__ ):
return module(*a__ )
return custom_forward
# down
if is_torch_version(">=" , "1.11.0" ):
for down_block in self.down_blocks:
snake_case_ = torch.utils.checkpoint.checkpoint(
create_custom_forward(a__ ) , a__ , use_reentrant=a__ )
# middle
snake_case_ = torch.utils.checkpoint.checkpoint(
create_custom_forward(self.mid_block ) , a__ , use_reentrant=a__ )
else:
for down_block in self.down_blocks:
snake_case_ = torch.utils.checkpoint.checkpoint(create_custom_forward(a__ ) , a__ )
# middle
snake_case_ = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , a__ )
else:
# down
for down_block in self.down_blocks:
snake_case_ = down_block(a__ )
# middle
snake_case_ = self.mid_block(a__ )
# post-process
snake_case_ = self.conv_norm_out(a__ )
snake_case_ = self.conv_act(a__ )
snake_case_ = self.conv_out(a__ )
return sample
class _snake_case ( nn.Module ):
def __init__( self , a__=3 , a__=3 , a__=("UpDecoderBlock2D",) , a__=(64,) , a__=2 , a__=32 , a__="silu" , a__="group" , ) -> int:
'''simple docstring'''
super().__init__()
snake_case_ = layers_per_block
snake_case_ = nn.Convad(
a__ , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , )
snake_case_ = None
snake_case_ = nn.ModuleList([] )
snake_case_ = in_channels if norm_type == "spatial" else None
# mid
snake_case_ = UNetMidBlockaD(
in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=a__ , output_scale_factor=1 , resnet_time_scale_shift="default" if norm_type == "group" else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=a__ , temb_channels=a__ , )
# up
snake_case_ = list(reversed(a__ ) )
snake_case_ = reversed_block_out_channels[0]
for i, up_block_type in enumerate(a__ ):
snake_case_ = output_channel
snake_case_ = reversed_block_out_channels[i]
snake_case_ = i == len(a__ ) - 1
snake_case_ = get_up_block(
a__ , num_layers=self.layers_per_block + 1 , in_channels=a__ , out_channels=a__ , prev_output_channel=a__ , add_upsample=not is_final_block , resnet_eps=1e-6 , resnet_act_fn=a__ , resnet_groups=a__ , attention_head_dim=a__ , temb_channels=a__ , resnet_time_scale_shift=a__ , )
self.up_blocks.append(a__ )
snake_case_ = output_channel
# out
if norm_type == "spatial":
snake_case_ = SpatialNorm(block_out_channels[0] , a__ )
else:
snake_case_ = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=a__ , eps=1e-6 )
snake_case_ = nn.SiLU()
snake_case_ = nn.Convad(block_out_channels[0] , a__ , 3 , padding=1 )
snake_case_ = False
def lowerCAmelCase__ ( self , a__ , a__=None ) -> Union[str, Any]:
'''simple docstring'''
snake_case_ = z
snake_case_ = self.conv_in(a__ )
snake_case_ = next(iter(self.up_blocks.parameters() ) ).dtype
if self.training and self.gradient_checkpointing:
def create_custom_forward(a__ ):
def custom_forward(*a__ ):
return module(*a__ )
return custom_forward
if is_torch_version(">=" , "1.11.0" ):
# middle
snake_case_ = torch.utils.checkpoint.checkpoint(
create_custom_forward(self.mid_block ) , a__ , a__ , use_reentrant=a__ )
snake_case_ = sample.to(a__ )
# up
for up_block in self.up_blocks:
snake_case_ = torch.utils.checkpoint.checkpoint(
create_custom_forward(a__ ) , a__ , a__ , use_reentrant=a__ )
else:
# middle
snake_case_ = torch.utils.checkpoint.checkpoint(
create_custom_forward(self.mid_block ) , a__ , a__ )
snake_case_ = sample.to(a__ )
# up
for up_block in self.up_blocks:
snake_case_ = torch.utils.checkpoint.checkpoint(create_custom_forward(a__ ) , a__ , a__ )
else:
# middle
snake_case_ = self.mid_block(a__ , a__ )
snake_case_ = sample.to(a__ )
# up
for up_block in self.up_blocks:
snake_case_ = up_block(a__ , a__ )
# post-process
if latent_embeds is None:
snake_case_ = self.conv_norm_out(a__ )
else:
snake_case_ = self.conv_norm_out(a__ , a__ )
snake_case_ = self.conv_act(a__ )
snake_case_ = self.conv_out(a__ )
return sample
class _snake_case ( nn.Module ):
def __init__( self , a__ , a__ , a__ , a__=None , a__="random" , a__=False , a__=True ) -> Optional[Any]:
'''simple docstring'''
super().__init__()
snake_case_ = n_e
snake_case_ = vq_embed_dim
snake_case_ = beta
snake_case_ = legacy
snake_case_ = nn.Embedding(self.n_e , self.vq_embed_dim )
self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e )
snake_case_ = remap
if self.remap is not None:
self.register_buffer("used" , torch.tensor(np.load(self.remap ) ) )
snake_case_ = self.used.shape[0]
snake_case_ = unknown_index # "random" or "extra" or integer
if self.unknown_index == "extra":
snake_case_ = self.re_embed
snake_case_ = self.re_embed + 1
print(
F'Remapping {self.n_e} indices to {self.re_embed} indices. '
F'Using {self.unknown_index} for unknown indices.' )
else:
snake_case_ = n_e
snake_case_ = sane_index_shape
def lowerCAmelCase__ ( self , a__ ) -> Optional[int]:
'''simple docstring'''
snake_case_ = inds.shape
assert len(a__ ) > 1
snake_case_ = inds.reshape(ishape[0] , -1 )
snake_case_ = self.used.to(a__ )
snake_case_ = (inds[:, :, None] == used[None, None, ...]).long()
snake_case_ = match.argmax(-1 )
snake_case_ = match.sum(2 ) < 1
if self.unknown_index == "random":
snake_case_ = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device )
else:
snake_case_ = self.unknown_index
return new.reshape(a__ )
def lowerCAmelCase__ ( self , a__ ) -> str:
'''simple docstring'''
snake_case_ = inds.shape
assert len(a__ ) > 1
snake_case_ = inds.reshape(ishape[0] , -1 )
snake_case_ = self.used.to(a__ )
if self.re_embed > self.used.shape[0]: # extra token
snake_case_ = 0 # simply set to zero
snake_case_ = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , a__ )
return back.reshape(a__ )
def lowerCAmelCase__ ( self , a__ ) -> str:
'''simple docstring'''
snake_case_ = z.permute(0 , 2 , 3 , 1 ).contiguous()
snake_case_ = z.view(-1 , self.vq_embed_dim )
# distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
snake_case_ = torch.argmin(torch.cdist(a__ , self.embedding.weight ) , dim=1 )
snake_case_ = self.embedding(a__ ).view(z.shape )
snake_case_ = None
snake_case_ = None
# compute loss for embedding
if not self.legacy:
snake_case_ = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 )
else:
snake_case_ = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 )
# preserve gradients
snake_case_ = z + (z_q - z).detach()
# reshape back to match original input shape
snake_case_ = z_q.permute(0 , 3 , 1 , 2 ).contiguous()
if self.remap is not None:
snake_case_ = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis
snake_case_ = self.remap_to_used(a__ )
snake_case_ = min_encoding_indices.reshape(-1 , 1 ) # flatten
if self.sane_index_shape:
snake_case_ = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] )
return z_q, loss, (perplexity, min_encodings, min_encoding_indices)
def lowerCAmelCase__ ( self , a__ , a__ ) -> List[str]:
'''simple docstring'''
if self.remap is not None:
snake_case_ = indices.reshape(shape[0] , -1 ) # add batch axis
snake_case_ = self.unmap_to_all(a__ )
snake_case_ = indices.reshape(-1 ) # flatten again
# get quantized latent vectors
snake_case_ = self.embedding(a__ )
if shape is not None:
snake_case_ = z_q.view(a__ )
# reshape back to match original input shape
snake_case_ = z_q.permute(0 , 3 , 1 , 2 ).contiguous()
return z_q
class _snake_case ( lowercase_ ):
def __init__( self , a__ , a__=False ) -> Optional[int]:
'''simple docstring'''
snake_case_ = parameters
snake_case_ , snake_case_ = torch.chunk(a__ , 2 , dim=1 )
snake_case_ = torch.clamp(self.logvar , -3_0.0 , 2_0.0 )
snake_case_ = deterministic
snake_case_ = torch.exp(0.5 * self.logvar )
snake_case_ = torch.exp(self.logvar )
if self.deterministic:
snake_case_ = snake_case_ = torch.zeros_like(
self.mean , device=self.parameters.device , dtype=self.parameters.dtype )
def lowerCAmelCase__ ( self , a__ = None ) -> torch.FloatTensor:
'''simple docstring'''
snake_case_ = randn_tensor(
self.mean.shape , generator=a__ , device=self.parameters.device , dtype=self.parameters.dtype )
snake_case_ = self.mean + self.std * sample
return x
def lowerCAmelCase__ ( self , a__=None ) -> List[str]:
'''simple docstring'''
if self.deterministic:
return torch.Tensor([0.0] )
else:
if other is None:
return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] )
else:
return 0.5 * torch.sum(
torch.pow(self.mean - other.mean , 2 ) / other.var
+ self.var / other.var
- 1.0
- self.logvar
+ other.logvar , dim=[1, 2, 3] , )
def lowerCAmelCase__ ( self , a__ , a__=[1, 2, 3] ) -> Optional[int]:
'''simple docstring'''
if self.deterministic:
return torch.Tensor([0.0] )
snake_case_ = np.log(2.0 * np.pi )
return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=a__ )
def lowerCAmelCase__ ( self ) -> Any:
'''simple docstring'''
return self.mean
| 400 | 0 |
'''simple docstring'''
import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock
import torch
from ..state import AcceleratorState, PartialState
from ..utils import (
gather,
is_bnb_available,
is_comet_ml_available,
is_datasets_available,
is_deepspeed_available,
is_mps_available,
is_safetensors_available,
is_tensorboard_available,
is_torch_version,
is_tpu_available,
is_transformers_available,
is_wandb_available,
is_xpu_available,
)
def a ( lowerCamelCase__ , lowerCamelCase__=False ):
'''simple docstring'''
try:
A_ : Union[str, Any] = os.environ[key]
except KeyError:
# KEY isn't set, default to `default`.
A_ : Optional[int] = default
else:
# KEY is set, convert it to True or False.
try:
A_ : Any = strtobool(lowerCamelCase__ )
except ValueError:
# More values are supported, but let's keep the message simple.
raise ValueError(f'If set, {key} must be yes or no.' )
return _value
lowerCamelCase :str = parse_flag_from_env('''RUN_SLOW''', default=False)
def a ( lowerCamelCase__ ):
'''simple docstring'''
return unittest.skip("""Test was skipped""" )(lowerCamelCase__ )
def a ( lowerCamelCase__ ):
'''simple docstring'''
return unittest.skipUnless(_run_slow_tests , """test is slow""" )(lowerCamelCase__ )
def a ( lowerCamelCase__ ):
'''simple docstring'''
return unittest.skipUnless(not torch.cuda.is_available() , """test requires only a CPU""" )(lowerCamelCase__ )
def a ( lowerCamelCase__ ):
'''simple docstring'''
return unittest.skipUnless(torch.cuda.is_available() , """test requires a GPU""" )(lowerCamelCase__ )
def a ( lowerCamelCase__ ):
'''simple docstring'''
return unittest.skipUnless(is_xpu_available() , """test requires a XPU""" )(lowerCamelCase__ )
def a ( lowerCamelCase__ ):
'''simple docstring'''
return unittest.skipUnless(is_mps_available() , """test requires a `mps` backend support in `torch`""" )(lowerCamelCase__ )
def a ( lowerCamelCase__ ):
'''simple docstring'''
return unittest.skipUnless(
is_transformers_available() and is_datasets_available() , """test requires the Hugging Face suite""" )(lowerCamelCase__ )
def a ( lowerCamelCase__ ):
'''simple docstring'''
return unittest.skipUnless(is_bnb_available() , """test requires the bitsandbytes library""" )(lowerCamelCase__ )
def a ( lowerCamelCase__ ):
'''simple docstring'''
return unittest.skipUnless(is_tpu_available() , """test requires TPU""" )(lowerCamelCase__ )
def a ( lowerCamelCase__ ):
'''simple docstring'''
return unittest.skipUnless(torch.cuda.device_count() == 1 , """test requires a GPU""" )(lowerCamelCase__ )
def a ( lowerCamelCase__ ):
'''simple docstring'''
return unittest.skipUnless(torch.xpu.device_count() == 1 , """test requires a XPU""" )(lowerCamelCase__ )
def a ( lowerCamelCase__ ):
'''simple docstring'''
return unittest.skipUnless(torch.cuda.device_count() > 1 , """test requires multiple GPUs""" )(lowerCamelCase__ )
def a ( lowerCamelCase__ ):
'''simple docstring'''
return unittest.skipUnless(torch.xpu.device_count() > 1 , """test requires multiple XPUs""" )(lowerCamelCase__ )
def a ( lowerCamelCase__ ):
'''simple docstring'''
return unittest.skipUnless(is_safetensors_available() , """test requires safetensors""" )(lowerCamelCase__ )
def a ( lowerCamelCase__ ):
'''simple docstring'''
return unittest.skipUnless(is_deepspeed_available() , """test requires DeepSpeed""" )(lowerCamelCase__ )
def a ( lowerCamelCase__ ):
'''simple docstring'''
return unittest.skipUnless(is_torch_version(""">=""" , """1.12.0""" ) , """test requires torch version >= 1.12.0""" )(lowerCamelCase__ )
def a ( lowerCamelCase__=None , lowerCamelCase__=None ):
'''simple docstring'''
if test_case is None:
return partial(lowerCamelCase__ , version=lowerCamelCase__ )
return unittest.skipUnless(is_torch_version(""">=""" , lowerCamelCase__ ) , f'test requires torch version >= {version}' )(lowerCamelCase__ )
def a ( lowerCamelCase__ ):
'''simple docstring'''
return unittest.skipUnless(is_tensorboard_available() , """test requires Tensorboard""" )(lowerCamelCase__ )
def a ( lowerCamelCase__ ):
'''simple docstring'''
return unittest.skipUnless(is_wandb_available() , """test requires wandb""" )(lowerCamelCase__ )
def a ( lowerCamelCase__ ):
'''simple docstring'''
return unittest.skipUnless(is_comet_ml_available() , """test requires comet_ml""" )(lowerCamelCase__ )
lowerCamelCase :str = (
any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)
def a ( lowerCamelCase__ ):
'''simple docstring'''
return unittest.skipUnless(
_atleast_one_tracker_available , """test requires at least one tracker to be available and for `comet_ml` to not be installed""" , )(lowerCamelCase__ )
class _lowerCAmelCase ( unittest.TestCase ):
__SCREAMING_SNAKE_CASE : Any = True
@classmethod
def _a (cls ):
A_ : Tuple = tempfile.mkdtemp()
@classmethod
def _a (cls ):
if os.path.exists(cls.tmpdir ):
shutil.rmtree(cls.tmpdir )
def _a (self ):
if self.clear_on_setup:
for path in Path(self.tmpdir ).glob("""**/*""" ):
if path.is_file():
path.unlink()
elif path.is_dir():
shutil.rmtree(lowercase )
class _lowerCAmelCase ( unittest.TestCase ):
def _a (self ):
super().tearDown()
# Reset the state of the AcceleratorState singleton.
AcceleratorState._reset_state()
PartialState._reset_state()
class _lowerCAmelCase ( unittest.TestCase ):
def _a (self , lowercase ):
A_ : Optional[int] = mocks if isinstance(lowercase , (tuple, list) ) else [mocks]
for m in self.mocks:
m.start()
self.addCleanup(m.stop )
def a ( lowerCamelCase__ ):
'''simple docstring'''
A_ : Dict = AcceleratorState()
A_ : str = tensor[None].clone().to(state.device )
A_ : Optional[int] = gather(lowerCamelCase__ ).cpu()
A_ : List[Any] = tensor[0].cpu()
for i in range(tensors.shape[0] ):
if not torch.equal(tensors[i] , lowerCamelCase__ ):
return False
return True
class _lowerCAmelCase :
def __init__(self , lowercase , lowercase , lowercase ):
A_ : str = returncode
A_ : Union[str, Any] = stdout
A_ : Dict = stderr
async def a ( lowerCamelCase__ , lowerCamelCase__ ):
'''simple docstring'''
while True:
A_ : Optional[int] = await stream.readline()
if line:
callback(lowerCamelCase__ )
else:
break
async def a ( lowerCamelCase__ , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__=False , lowerCamelCase__=False ):
'''simple docstring'''
if echo:
print("""\nRunning: """ , """ """.join(lowerCamelCase__ ) )
A_ : List[Any] = await asyncio.create_subprocess_exec(
cmd[0] , *cmd[1:] , stdin=lowerCamelCase__ , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=lowerCamelCase__ , )
# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
#
# If it starts hanging, will need to switch to the following code. The problem is that no data
# will be seen until it's done and if it hangs for example there will be no debug info.
# out, err = await p.communicate()
# return _RunOutput(p.returncode, out, err)
A_ : Union[str, Any] = []
A_ : List[Any] = []
def tee(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__="" ):
A_ : List[Any] = line.decode("""utf-8""" ).rstrip()
sink.append(lowerCamelCase__ )
if not quiet:
print(lowerCamelCase__ , lowerCamelCase__ , file=lowerCamelCase__ )
# XXX: the timeout doesn't seem to make any difference here
await asyncio.wait(
[
asyncio.create_task(_read_stream(p.stdout , lambda lowerCamelCase__ : tee(lowerCamelCase__ , lowerCamelCase__ , sys.stdout , label="""stdout:""" ) ) ),
asyncio.create_task(_read_stream(p.stderr , lambda lowerCamelCase__ : tee(lowerCamelCase__ , lowerCamelCase__ , sys.stderr , label="""stderr:""" ) ) ),
] , timeout=lowerCamelCase__ , )
return _RunOutput(await p.wait() , lowerCamelCase__ , lowerCamelCase__ )
def a ( lowerCamelCase__ , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__=1_80 , lowerCamelCase__=False , lowerCamelCase__=True ):
'''simple docstring'''
A_ : Tuple = asyncio.get_event_loop()
A_ : Tuple = loop.run_until_complete(
_stream_subprocess(lowerCamelCase__ , env=lowerCamelCase__ , stdin=lowerCamelCase__ , timeout=lowerCamelCase__ , quiet=lowerCamelCase__ , echo=lowerCamelCase__ ) )
A_ : Optional[Any] = """ """.join(lowerCamelCase__ )
if result.returncode > 0:
A_ : int = """\n""".join(result.stderr )
raise RuntimeError(
f'\'{cmd_str}\' failed with returncode {result.returncode}\n\n'
f'The combined stderr from workers follows:\n{stderr}' )
return result
class _lowerCAmelCase ( __UpperCAmelCase ):
pass
def a ( lowerCamelCase__ , lowerCamelCase__=False ):
'''simple docstring'''
try:
A_ : Dict = subprocess.check_output(lowerCamelCase__ , stderr=subprocess.STDOUT )
if return_stdout:
if hasattr(lowerCamelCase__ , """decode""" ):
A_ : str = output.decode("""utf-8""" )
return output
except subprocess.CalledProcessError as e:
raise SubprocessCallException(
f'Command `{" ".join(lowerCamelCase__ )}` failed with the following error:\n\n{e.output.decode()}' ) from e | 686 |
'''simple docstring'''
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
lowerCamelCase :Optional[int] = {
'''gwf-440k''': {
'''url''': '''https://model-server.zqevans2.workers.dev/gwf-440k.ckpt''',
'''sample_rate''': 4_8_0_0_0,
'''sample_size''': 6_5_5_3_6,
},
'''jmann-small-190k''': {
'''url''': '''https://model-server.zqevans2.workers.dev/jmann-small-190k.ckpt''',
'''sample_rate''': 4_8_0_0_0,
'''sample_size''': 6_5_5_3_6,
},
'''jmann-large-580k''': {
'''url''': '''https://model-server.zqevans2.workers.dev/jmann-large-580k.ckpt''',
'''sample_rate''': 4_8_0_0_0,
'''sample_size''': 1_3_1_0_7_2,
},
'''maestro-uncond-150k''': {
'''url''': '''https://model-server.zqevans2.workers.dev/maestro-uncond-150k.ckpt''',
'''sample_rate''': 1_6_0_0_0,
'''sample_size''': 6_5_5_3_6,
},
'''unlocked-uncond-250k''': {
'''url''': '''https://model-server.zqevans2.workers.dev/unlocked-uncond-250k.ckpt''',
'''sample_rate''': 1_6_0_0_0,
'''sample_size''': 6_5_5_3_6,
},
'''honk-140k''': {
'''url''': '''https://model-server.zqevans2.workers.dev/honk-140k.ckpt''',
'''sample_rate''': 1_6_0_0_0,
'''sample_size''': 6_5_5_3_6,
},
}
def a ( lowerCamelCase__ , lowerCamelCase__ ):
'''simple docstring'''
return torch.atana(lowerCamelCase__ , lowerCamelCase__ ) / math.pi * 2
def a ( lowerCamelCase__ ):
'''simple docstring'''
A_ : Optional[Any] = torch.sin(t * math.pi / 2 ) ** 2
A_ : List[Any] = (1 - sigma**2) ** 0.5
return alpha_sigma_to_t(lowerCamelCase__ , lowerCamelCase__ )
class _lowerCAmelCase ( __UpperCAmelCase ):
pass
class _lowerCAmelCase ( nn.Module ):
def __init__(self , lowercase ):
super().__init__()
A_ : int = DiffusionAttnUnetaD(lowercase , n_attn_layers=4 )
A_ : str = deepcopy(self.diffusion )
A_ : Optional[int] = torch.quasirandom.SobolEngine(1 , scramble=lowercase )
def a ( lowerCamelCase__ ):
'''simple docstring'''
A_ : List[str] = MODELS_MAP[model_name]["""url"""]
os.system(f'wget {url} ./' )
return f'./{model_name}.ckpt'
lowerCamelCase :str = {
'''1''': '''resnets.0''',
'''2''': '''attentions.0''',
'''3''': '''resnets.1''',
'''4''': '''attentions.1''',
'''5''': '''resnets.2''',
'''6''': '''attentions.2''',
}
lowerCamelCase :str = {
'''8''': '''resnets.0''',
'''9''': '''attentions.0''',
'''10''': '''resnets.1''',
'''11''': '''attentions.1''',
'''12''': '''resnets.2''',
'''13''': '''attentions.2''',
}
lowerCamelCase :str = {
'''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''',
}
lowerCamelCase :int = {
'''0''': '''resnets.0''',
'''1''': '''resnets.1''',
'''2''': '''resnets.2''',
'''4''': '''resnets.0''',
'''5''': '''resnets.1''',
'''6''': '''resnets.2''',
}
lowerCamelCase :List[Any] = {
'''skip''': '''conv_skip''',
'''main.0''': '''conv_1''',
'''main.1''': '''group_norm_1''',
'''main.3''': '''conv_2''',
'''main.4''': '''group_norm_2''',
}
lowerCamelCase :Optional[Any] = {
'''norm''': '''group_norm''',
'''qkv_proj''': ['''query''', '''key''', '''value'''],
'''out_proj''': ['''proj_attn'''],
}
def a ( lowerCamelCase__ ):
'''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 ( lowerCamelCase__ ):
'''simple docstring'''
for key, value in ATTN_MAP.items():
if name.startswith(lowerCamelCase__ ) and not isinstance(lowerCamelCase__ , lowerCamelCase__ ):
return name.replace(lowerCamelCase__ , lowerCamelCase__ )
elif name.startswith(lowerCamelCase__ ):
return [name.replace(lowerCamelCase__ , lowerCamelCase__ ) for v in value]
raise ValueError(f'Attn error with {name}' )
def a ( lowerCamelCase__ , lowerCamelCase__=13 ):
'''simple docstring'''
A_ : Union[str, Any] = input_string
if string.split(""".""" )[0] == "timestep_embed":
return string.replace("""timestep_embed""" , """time_proj""" )
A_ : Dict = 0
if string.startswith("""net.3.""" ):
depth += 1
A_ : int = string[6:]
elif string.startswith("""net.""" ):
A_ : Tuple = string[4:]
while string.startswith("""main.7.""" ):
depth += 1
A_ : Dict = string[7:]
if string.startswith("""main.""" ):
A_ : Union[str, Any] = string[5:]
# mid block
if string[:2].isdigit():
A_ : Optional[Any] = string[:2]
A_ : Optional[Any] = string[2:]
else:
A_ : List[Any] = string[0]
A_ : Dict = string[1:]
if depth == max_depth:
A_ : Optional[int] = MID_NUM_TO_LAYER[layer_num]
A_ : Optional[Any] = """mid_block"""
elif depth > 0 and int(lowerCamelCase__ ) < 7:
A_ : Any = DOWN_NUM_TO_LAYER[layer_num]
A_ : Union[str, Any] = f'down_blocks.{depth}'
elif depth > 0 and int(lowerCamelCase__ ) > 7:
A_ : List[str] = UP_NUM_TO_LAYER[layer_num]
A_ : List[str] = f'up_blocks.{max_depth - depth - 1}'
elif depth == 0:
A_ : str = DEPTH_0_TO_LAYER[layer_num]
A_ : Dict = f'up_blocks.{max_depth - 1}' if int(lowerCamelCase__ ) > 3 else """down_blocks.0"""
if not string_left.startswith(""".""" ):
raise ValueError(f'Naming error with {input_string} and string_left: {string_left}.' )
A_ : Optional[int] = string_left[1:]
if "resnets" in new_layer:
A_ : Tuple = convert_resconv_naming(lowerCamelCase__ )
elif "attentions" in new_layer:
A_ : Optional[int] = convert_attn_naming(lowerCamelCase__ )
A_ : Dict = new_string_left
if not isinstance(lowerCamelCase__ , lowerCamelCase__ ):
A_ : Union[str, Any] = prefix + """.""" + new_layer + """.""" + string_left
else:
A_ : Optional[int] = [prefix + """.""" + new_layer + """.""" + s for s in string_left]
return new_string
def a ( lowerCamelCase__ ):
'''simple docstring'''
A_ : Union[str, Any] = {}
for k, v in state_dict.items():
if k.endswith("""kernel""" ):
# up- and downsample layers, don't have trainable weights
continue
A_ : List[Any] = rename(lowerCamelCase__ )
# check if we need to transform from Conv => Linear for attention
if isinstance(lowerCamelCase__ , lowerCamelCase__ ):
A_ : Tuple = transform_conv_attns(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ )
else:
A_ : int = v
return new_state_dict
def a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ):
'''simple docstring'''
if len(lowerCamelCase__ ) == 1:
if len(v.shape ) == 3:
# weight
A_ : Optional[Any] = v[:, :, 0]
else:
# bias
A_ : Union[str, Any] = v
else:
# qkv matrices
A_ : Optional[int] = v.shape[0]
A_ : str = trippled_shape // 3
for i in range(3 ):
if len(v.shape ) == 3:
A_ : int = v[i * single_shape : (i + 1) * single_shape, :, 0]
else:
A_ : str = v[i * single_shape : (i + 1) * single_shape]
return new_state_dict
def a ( lowerCamelCase__ ):
'''simple docstring'''
A_ : List[Any] = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" )
A_ : Dict = 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()}'
A_ : int = download(lowerCamelCase__ )
A_ : Any = MODELS_MAP[model_name]["""sample_rate"""]
A_ : List[Any] = MODELS_MAP[model_name]["""sample_size"""]
A_ : Tuple = Object()
A_ : Union[str, Any] = sample_size
A_ : Tuple = sample_rate
A_ : int = 0
A_ : List[Any] = UNetaDModel(sample_size=lowerCamelCase__ , sample_rate=lowerCamelCase__ )
A_ : Optional[Any] = diffusers_model.state_dict()
A_ : Dict = DiffusionUncond(lowerCamelCase__ )
orig_model.load_state_dict(torch.load(args.model_path , map_location=lowerCamelCase__ )["""state_dict"""] )
A_ : Any = orig_model.diffusion_ema.eval()
A_ : Any = orig_model.state_dict()
A_ : List[str] = rename_orig_weights(lowerCamelCase__ )
A_ : Any = set(renamed_state_dict.keys() ) - set(diffusers_state_dict.keys() )
A_ : Optional[int] = set(diffusers_state_dict.keys() ) - set(renamed_state_dict.keys() )
assert len(lowerCamelCase__ ) == 0, f'Problem with {renamed_minus_diffusers}'
assert all(k.endswith("""kernel""" ) for k in list(lowerCamelCase__ ) ), 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":
A_ : str = value.squeeze()
A_ : Union[str, Any] = value
diffusers_model.load_state_dict(lowerCamelCase__ )
A_ : Optional[Any] = 1_00
A_ : Union[str, Any] = 33
A_ : Any = IPNDMScheduler(num_train_timesteps=lowerCamelCase__ )
A_ : List[str] = torch.manual_seed(lowerCamelCase__ )
A_ : Any = torch.randn([1, 2, config.sample_size] , generator=lowerCamelCase__ ).to(lowerCamelCase__ )
A_ : str = torch.linspace(1 , 0 , steps + 1 , device=lowerCamelCase__ )[:-1]
A_ : List[Any] = get_crash_schedule(lowerCamelCase__ )
A_ : str = DanceDiffusionPipeline(unet=lowerCamelCase__ , scheduler=lowerCamelCase__ )
A_ : str = torch.manual_seed(33 )
A_ : int = pipe(num_inference_steps=lowerCamelCase__ , generator=lowerCamelCase__ ).audios
A_ : Optional[int] = sampling.iplms_sample(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , {} )
A_ : str = generated.clamp(-1 , 1 )
A_ : List[Any] = (generated - audio).abs().sum()
A_ : int = (generated - audio).abs().max()
if args.save:
pipe.save_pretrained(args.checkpoint_path )
print("""Diff sum""" , lowerCamelCase__ )
print("""Diff max""" , lowerCamelCase__ )
assert diff_max < 1E-3, f'Diff max: {diff_max} is too much :-/'
print(f'Conversion for {model_name} successful!' )
if __name__ == "__main__":
lowerCamelCase :int = 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.''')
lowerCamelCase :List[str] = parser.parse_args()
main(args) | 686 | 1 |
'''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_ ( __A ):
"""simple docstring"""
def __init__( self : List[str] , UpperCAmelCase : Any , UpperCAmelCase : Tuple=13 , UpperCAmelCase : Dict=7 , UpperCAmelCase : int=True , UpperCAmelCase : Union[str, Any]=True , UpperCAmelCase : Dict=False , UpperCAmelCase : List[Any]=True , UpperCAmelCase : Dict=99 , UpperCAmelCase : Union[str, Any]=32 , UpperCAmelCase : Dict=5 , UpperCAmelCase : Tuple=4 , UpperCAmelCase : List[str]=37 , UpperCAmelCase : Tuple="gelu" , UpperCAmelCase : List[str]=0.1 , UpperCAmelCase : Tuple=0.1 , UpperCAmelCase : int=512 , UpperCAmelCase : Optional[Any]=16 , UpperCAmelCase : Tuple=2 , UpperCAmelCase : Optional[int]=0.0_2 , UpperCAmelCase : Optional[int]=3 , UpperCAmelCase : Optional[int]=4 , UpperCAmelCase : List[Any]=None , ) -> List[Any]:
'''simple docstring'''
lowercase : Union[str, Any] =parent
lowercase : Tuple =batch_size
lowercase : Dict =seq_length
lowercase : List[Any] =is_training
lowercase : int =use_input_mask
lowercase : List[Any] =use_token_type_ids
lowercase : List[Any] =use_labels
lowercase : Any =vocab_size
lowercase : List[Any] =hidden_size
lowercase : str =num_hidden_layers
lowercase : Dict =num_attention_heads
lowercase : Union[str, Any] =intermediate_size
lowercase : Union[str, Any] =hidden_act
lowercase : List[Any] =hidden_dropout_prob
lowercase : str =attention_probs_dropout_prob
lowercase : Optional[Any] =max_position_embeddings
lowercase : Dict =type_vocab_size
lowercase : List[Any] =type_sequence_label_size
lowercase : List[str] =initializer_range
lowercase : Union[str, Any] =num_labels
lowercase : List[str] =num_choices
lowercase : Union[str, Any] =scope
def A__ ( self : Any ) -> Dict:
'''simple docstring'''
lowercase : Tuple =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
lowercase : Dict =None
if self.use_input_mask:
lowercase : Optional[Any] =random_attention_mask([self.batch_size, self.seq_length] )
lowercase : Union[str, Any] =None
lowercase : int =None
lowercase : int =None
if self.use_labels:
lowercase : Dict =ids_tensor([self.batch_size] , self.type_sequence_label_size )
lowercase : Any =ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
lowercase : Union[str, Any] =ids_tensor([self.batch_size] , self.num_choices )
lowercase : Tuple =self.get_config()
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
def A__ ( self : Any ) -> Tuple:
'''simple docstring'''
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 A__ ( self : List[Any] , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : Optional[Any] , UpperCAmelCase : List[str] , UpperCAmelCase : int , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : Dict ) -> List[Any]:
'''simple docstring'''
lowercase : int =DistilBertModel(config=UpperCAmelCase )
model.to(UpperCAmelCase )
model.eval()
lowercase : List[str] =model(UpperCAmelCase , UpperCAmelCase )
lowercase : Dict =model(UpperCAmelCase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def A__ ( self : Optional[int] , UpperCAmelCase : List[str] , UpperCAmelCase : List[Any] , UpperCAmelCase : Tuple , UpperCAmelCase : str , UpperCAmelCase : Optional[Any] , UpperCAmelCase : Optional[int] ) -> int:
'''simple docstring'''
lowercase : Union[str, Any] =DistilBertForMaskedLM(config=UpperCAmelCase )
model.to(UpperCAmelCase )
model.eval()
lowercase : Optional[Any] =model(UpperCAmelCase , attention_mask=UpperCAmelCase , labels=UpperCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def A__ ( self : Union[str, Any] , UpperCAmelCase : Tuple , UpperCAmelCase : Optional[int] , UpperCAmelCase : List[str] , UpperCAmelCase : Tuple , UpperCAmelCase : int , UpperCAmelCase : List[str] ) -> List[str]:
'''simple docstring'''
lowercase : List[Any] =DistilBertForQuestionAnswering(config=UpperCAmelCase )
model.to(UpperCAmelCase )
model.eval()
lowercase : Any =model(
UpperCAmelCase , attention_mask=UpperCAmelCase , start_positions=UpperCAmelCase , end_positions=UpperCAmelCase )
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 , UpperCAmelCase : Optional[int] , UpperCAmelCase : Tuple , UpperCAmelCase : Optional[Any] , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : Dict , UpperCAmelCase : Dict ) -> str:
'''simple docstring'''
lowercase : Tuple =self.num_labels
lowercase : int =DistilBertForSequenceClassification(UpperCAmelCase )
model.to(UpperCAmelCase )
model.eval()
lowercase : Any =model(UpperCAmelCase , attention_mask=UpperCAmelCase , labels=UpperCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def A__ ( self : Optional[int] , UpperCAmelCase : List[str] , UpperCAmelCase : Tuple , UpperCAmelCase : str , UpperCAmelCase : str , UpperCAmelCase : Dict , UpperCAmelCase : Union[str, Any] ) -> Optional[Any]:
'''simple docstring'''
lowercase : Tuple =self.num_labels
lowercase : List[str] =DistilBertForTokenClassification(config=UpperCAmelCase )
model.to(UpperCAmelCase )
model.eval()
lowercase : Optional[int] =model(UpperCAmelCase , attention_mask=UpperCAmelCase , labels=UpperCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def A__ ( self : str , UpperCAmelCase : List[str] , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : int , UpperCAmelCase : List[str] , UpperCAmelCase : Any , UpperCAmelCase : Optional[Any] ) -> List[Any]:
'''simple docstring'''
lowercase : Tuple =self.num_choices
lowercase : Any =DistilBertForMultipleChoice(config=UpperCAmelCase )
model.to(UpperCAmelCase )
model.eval()
lowercase : Union[str, Any] =input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
lowercase : str =input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
lowercase : str =model(
UpperCAmelCase , attention_mask=UpperCAmelCase , labels=UpperCAmelCase , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def A__ ( self : Optional[int] ) -> str:
'''simple docstring'''
lowercase : List[str] =self.prepare_config_and_inputs()
((lowercase) , (lowercase) , (lowercase) , (lowercase) , (lowercase) , (lowercase)) : List[str] =config_and_inputs
lowercase : Union[str, Any] ={'''input_ids''': input_ids, '''attention_mask''': input_mask}
return config, inputs_dict
@require_torch
class UpperCAmelCase_ ( __A , __A , unittest.TestCase ):
"""simple docstring"""
UpperCamelCase_ = (
(
DistilBertModel,
DistilBertForMaskedLM,
DistilBertForMultipleChoice,
DistilBertForQuestionAnswering,
DistilBertForSequenceClassification,
DistilBertForTokenClassification,
)
if is_torch_available()
else None
)
UpperCamelCase_ = (
{
'''feature-extraction''': DistilBertModel,
'''fill-mask''': DistilBertForMaskedLM,
'''question-answering''': DistilBertForQuestionAnswering,
'''text-classification''': DistilBertForSequenceClassification,
'''token-classification''': DistilBertForTokenClassification,
'''zero-shot''': DistilBertForSequenceClassification,
}
if is_torch_available()
else {}
)
UpperCamelCase_ = True
UpperCamelCase_ = True
UpperCamelCase_ = True
UpperCamelCase_ = True
def A__ ( self : Any ) -> int:
'''simple docstring'''
lowercase : List[Any] =DistilBertModelTester(self )
lowercase : Union[str, Any] =ConfigTester(self , config_class=UpperCAmelCase , dim=37 )
def A__ ( self : Tuple ) -> str:
'''simple docstring'''
self.config_tester.run_common_tests()
def A__ ( self : Optional[int] ) -> Optional[int]:
'''simple docstring'''
lowercase : Any =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_model(*UpperCAmelCase )
def A__ ( self : Tuple ) -> Optional[int]:
'''simple docstring'''
lowercase : Optional[int] =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_masked_lm(*UpperCAmelCase )
def A__ ( self : Tuple ) -> Optional[int]:
'''simple docstring'''
lowercase : Any =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_question_answering(*UpperCAmelCase )
def A__ ( self : int ) -> str:
'''simple docstring'''
lowercase : Union[str, Any] =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_sequence_classification(*UpperCAmelCase )
def A__ ( self : List[Any] ) -> str:
'''simple docstring'''
lowercase : Optional[int] =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_token_classification(*UpperCAmelCase )
def A__ ( self : Dict ) -> int:
'''simple docstring'''
lowercase : int =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_multiple_choice(*UpperCAmelCase )
@slow
def A__ ( self : List[str] ) -> str:
'''simple docstring'''
for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowercase : List[str] =DistilBertModel.from_pretrained(UpperCAmelCase )
self.assertIsNotNone(UpperCAmelCase )
@slow
@require_torch_gpu
def A__ ( self : List[Any] ) -> Optional[Any]:
'''simple docstring'''
lowercase , lowercase : Optional[int] =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
lowercase : Optional[Any] =True
lowercase : Tuple =model_class(config=UpperCAmelCase )
lowercase : Tuple =self._prepare_for_class(UpperCAmelCase , UpperCAmelCase )
lowercase : Tuple =torch.jit.trace(
UpperCAmelCase , (inputs_dict['''input_ids'''].to('''cpu''' ), inputs_dict['''attention_mask'''].to('''cpu''' )) )
with tempfile.TemporaryDirectory() as tmp:
torch.jit.save(UpperCAmelCase , os.path.join(UpperCAmelCase , '''traced_model.pt''' ) )
lowercase : Any =torch.jit.load(os.path.join(UpperCAmelCase , '''traced_model.pt''' ) , map_location=UpperCAmelCase )
loaded(inputs_dict['''input_ids'''].to(UpperCAmelCase ) , inputs_dict['''attention_mask'''].to(UpperCAmelCase ) )
@require_torch
class UpperCAmelCase_ ( unittest.TestCase ):
"""simple docstring"""
@slow
def A__ ( self : str ) -> Optional[int]:
'''simple docstring'''
lowercase : Dict =DistilBertModel.from_pretrained('''distilbert-base-uncased''' )
lowercase : List[str] =torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] )
lowercase : List[Any] =torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
with torch.no_grad():
lowercase : Any =model(UpperCAmelCase , attention_mask=UpperCAmelCase )[0]
lowercase : Union[str, Any] =torch.Size((1, 11, 768) )
self.assertEqual(output.shape , UpperCAmelCase )
lowercase : Union[str, Any] =torch.tensor(
[[[-0.1_6_3_9, 0.3_2_9_9, 0.1_6_4_8], [-0.1_7_4_6, 0.3_2_8_9, 0.1_7_1_0], [-0.1_8_8_4, 0.3_3_5_7, 0.1_8_1_0]]] )
self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase , atol=1e-4 ) )
| 94 |
'''simple docstring'''
import math
def _lowerCamelCase (__lowerCamelCase : int ) -> str:
a__ = 0
a__ = 0
while num > 0:
a__ = num % 8
a__ = octal + (remainder * math.floor(math.pow(10 , __lowerCamelCase ) ))
counter += 1
a__ = math.floor(num / 8 ) # basically /= 8 without remainder if any
# This formatting removes trailing '.0' from `octal`.
return f'''0o{int(__lowerCamelCase )}'''
def _lowerCamelCase () -> None:
print("\n2 in octal is:" )
print(decimal_to_octal(2 ) ) # = 2
print("\n8 in octal is:" )
print(decimal_to_octal(8 ) ) # = 10
print("\n65 in octal is:" )
print(decimal_to_octal(65 ) ) # = 101
print("\n216 in octal is:" )
print(decimal_to_octal(216 ) ) # = 330
print("\n512 in octal is:" )
print(decimal_to_octal(512 ) ) # = 1000
print("\n" )
if __name__ == "__main__":
main()
| 489 | 0 |
import argparse
import json
import os
import torch
from transformers import LukeConfig, LukeModel, LukeTokenizer, RobertaTokenizer
from transformers.tokenization_utils_base import AddedToken
@torch.no_grad()
def lowerCAmelCase__ ( UpperCamelCase_ : str , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : str , UpperCamelCase_ : Dict , UpperCamelCase_ : int )-> Dict:
# Load configuration defined in the metadata file
with open(UpperCamelCase_ ) as metadata_file:
A__ = json.load(UpperCamelCase_ )
A__ = LukeConfig(use_entity_aware_attention=UpperCamelCase_ , **metadata['''model_config'''] )
# Load in the weights from the checkpoint_path
A__ = torch.load(UpperCamelCase_ , map_location='''cpu''' )
# Load the entity vocab file
A__ = load_entity_vocab(UpperCamelCase_ )
A__ = RobertaTokenizer.from_pretrained(metadata['''model_config''']['''bert_model_name'''] )
# Add special tokens to the token vocabulary for downstream tasks
A__ = AddedToken('''<ent>''' , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ )
A__ = AddedToken('''<ent2>''' , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ )
tokenizer.add_special_tokens({'''additional_special_tokens''': [entity_token_a, entity_token_a]} )
config.vocab_size += 2
print(f"Saving tokenizer to {pytorch_dump_folder_path}" )
tokenizer.save_pretrained(UpperCamelCase_ )
with open(os.path.join(UpperCamelCase_ , LukeTokenizer.vocab_files_names['''entity_vocab_file'''] ) , '''w''' ) as f:
json.dump(UpperCamelCase_ , UpperCamelCase_ )
A__ = LukeTokenizer.from_pretrained(UpperCamelCase_ )
# Initialize the embeddings of the special tokens
A__ = state_dict['''embeddings.word_embeddings.weight''']
A__ = word_emb[tokenizer.convert_tokens_to_ids(['''@'''] )[0]].unsqueeze(0 )
A__ = word_emb[tokenizer.convert_tokens_to_ids(['''#'''] )[0]].unsqueeze(0 )
A__ = torch.cat([word_emb, ent_emb, enta_emb] )
# Initialize the query layers of the entity-aware self-attention mechanism
for layer_index in range(config.num_hidden_layers ):
for matrix_name in ["query.weight", "query.bias"]:
A__ = f"encoder.layer.{layer_index}.attention.self."
A__ = state_dict[prefix + matrix_name]
A__ = state_dict[prefix + matrix_name]
A__ = state_dict[prefix + matrix_name]
# Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks
A__ = state_dict['''entity_embeddings.entity_embeddings.weight''']
A__ = entity_emb[entity_vocab['''[MASK]''']]
A__ = LukeModel(config=UpperCamelCase_ ).eval()
A__ , A__ = model.load_state_dict(UpperCamelCase_ , strict=UpperCamelCase_ )
if not (len(UpperCamelCase_ ) == 1 and missing_keys[0] == "embeddings.position_ids"):
raise ValueError(f"Missing keys {', '.join(UpperCamelCase_ )}. Expected only missing embeddings.position_ids" )
if not (all(key.startswith('''entity_predictions''' ) or key.startswith('''lm_head''' ) for key in unexpected_keys )):
raise ValueError(
'''Unexpected keys'''
f" {', '.join([key for key in unexpected_keys if not (key.startswith('entity_predictions' ) or key.startswith('lm_head' ))] )}" )
# Check outputs
A__ = LukeTokenizer.from_pretrained(UpperCamelCase_ , task='''entity_classification''' )
A__ = (
'''Top seed Ana Ivanovic said on Thursday she could hardly believe her luck as a fortuitous netcord helped the'''
''' new world number one avoid a humiliating second- round exit at Wimbledon .'''
)
A__ = (3_9, 4_2)
A__ = tokenizer(UpperCamelCase_ , entity_spans=[span] , add_prefix_space=UpperCamelCase_ , return_tensors='''pt''' )
A__ = model(**UpperCamelCase_ )
# Verify word hidden states
if model_size == "large":
A__ = torch.Size((1, 4_2, 1_0_2_4) )
A__ = torch.tensor(
[[0.0133, 0.0865, 0.0095], [0.3093, -0.2576, -0.7418], [-0.1720, -0.2117, -0.2869]] )
else: # base
A__ = torch.Size((1, 4_2, 7_6_8) )
A__ = torch.tensor([[0.0037, 0.1368, -0.0091], [0.1099, 0.3329, -0.1095], [0.0765, 0.5335, 0.1179]] )
if not (outputs.last_hidden_state.shape == expected_shape):
raise ValueError(
f"Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}" )
if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , UpperCamelCase_ , atol=1E-4 ):
raise ValueError
# Verify entity hidden states
if model_size == "large":
A__ = torch.Size((1, 1, 1_0_2_4) )
A__ = torch.tensor([[0.0466, -0.0106, -0.0179]] )
else: # base
A__ = torch.Size((1, 1, 7_6_8) )
A__ = torch.tensor([[0.1457, 0.1044, 0.0174]] )
if not (outputs.entity_last_hidden_state.shape != expected_shape):
raise ValueError(
f"Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is"
f" {expected_shape}" )
if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , UpperCamelCase_ , atol=1E-4 ):
raise ValueError
# Finally, save our PyTorch model and tokenizer
print('''Saving PyTorch model to {}'''.format(UpperCamelCase_ ) )
model.save_pretrained(UpperCamelCase_ )
def lowerCAmelCase__ ( UpperCamelCase_ : str )-> Any:
A__ = {}
with open(UpperCamelCase_ , '''r''' , encoding='''utf-8''' ) as f:
for index, line in enumerate(UpperCamelCase_ ):
A__ , A__ = line.rstrip().split('''\t''' )
A__ = index
return entity_vocab
if __name__ == "__main__":
_lowercase = argparse.ArgumentParser()
# Required parameters
parser.add_argument("--checkpoint_path", type=str, help="Path to a pytorch_model.bin file.")
parser.add_argument(
"--metadata_path", default=None, type=str, help="Path to a metadata.json file, defining the configuration."
)
parser.add_argument(
"--entity_vocab_path",
default=None,
type=str,
help="Path to an entity_vocab.tsv file, containing the entity vocabulary.",
)
parser.add_argument(
"--pytorch_dump_folder_path", default=None, type=str, help="Path to where to dump the output PyTorch model."
)
parser.add_argument(
"--model_size", default="base", type=str, choices=["base", "large"], help="Size of the model to be converted."
)
_lowercase = parser.parse_args()
convert_luke_checkpoint(
args.checkpoint_path,
args.metadata_path,
args.entity_vocab_path,
args.pytorch_dump_folder_path,
args.model_size,
)
| 711 |
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING
from ..models.auto import AutoModelForVisionaSeq
from ..utils import requires_backends
from .base import PipelineTool
if TYPE_CHECKING:
from PIL import Image
class _UpperCAmelCase ( A__ ):
UpperCamelCase__ = '''Salesforce/blip-image-captioning-base'''
UpperCamelCase__ = (
'''This is a tool that generates a description of an image. It takes an input named `image` which should be the '''
'''image to caption, and returns a text that contains the description in English.'''
)
UpperCamelCase__ = '''image_captioner'''
UpperCamelCase__ = AutoModelForVisionaSeq
UpperCamelCase__ = ['''image''']
UpperCamelCase__ = ['''text''']
def __init__( self , *a__ , **a__):
requires_backends(self , ['''vision'''])
super().__init__(*a__ , **a__)
def snake_case_ ( self , a__):
return self.pre_processor(images=a__ , return_tensors='''pt''')
def snake_case_ ( self , a__):
return self.model.generate(**a__)
def snake_case_ ( self , a__):
return self.pre_processor.batch_decode(a__ , skip_special_tokens=a__)[0].strip()
| 526 | 0 |
def _lowercase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : int ):
"""simple docstring"""
UpperCamelCase = [[] for _ in range(SCREAMING_SNAKE_CASE_ )]
UpperCamelCase = key - 1
if key <= 0:
raise ValueError("""Height of grid can't be 0 or negative""" )
if key == 1 or len(SCREAMING_SNAKE_CASE_ ) <= key:
return input_string
for position, character in enumerate(SCREAMING_SNAKE_CASE_ ):
UpperCamelCase = position % (lowest * 2) # puts it in bounds
UpperCamelCase = min(SCREAMING_SNAKE_CASE_ , lowest * 2 - num ) # creates zigzag pattern
temp_grid[num].append(SCREAMING_SNAKE_CASE_ )
UpperCamelCase = ["""""".join(SCREAMING_SNAKE_CASE_ ) for row in temp_grid]
UpperCamelCase = """""".join(SCREAMING_SNAKE_CASE_ )
return output_string
def _lowercase ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : int ):
"""simple docstring"""
UpperCamelCase = []
UpperCamelCase = key - 1
if key <= 0:
raise ValueError("""Height of grid can't be 0 or negative""" )
if key == 1:
return input_string
UpperCamelCase = [[] for _ in range(SCREAMING_SNAKE_CASE_ )] # generates template
for position in range(len(SCREAMING_SNAKE_CASE_ ) ):
UpperCamelCase = position % (lowest * 2) # puts it in bounds
UpperCamelCase = min(SCREAMING_SNAKE_CASE_ , lowest * 2 - num ) # creates zigzag pattern
temp_grid[num].append("""*""" )
UpperCamelCase = 0
for row in temp_grid: # fills in the characters
UpperCamelCase = input_string[counter : counter + len(SCREAMING_SNAKE_CASE_ )]
grid.append(list(SCREAMING_SNAKE_CASE_ ) )
counter += len(SCREAMING_SNAKE_CASE_ )
UpperCamelCase = """""" # reads as zigzag
for position in range(len(SCREAMING_SNAKE_CASE_ ) ):
UpperCamelCase = position % (lowest * 2) # puts it in bounds
UpperCamelCase = min(SCREAMING_SNAKE_CASE_ , lowest * 2 - num ) # creates zigzag pattern
output_string += grid[num][0]
grid[num].pop(0 )
return output_string
def _lowercase ( SCREAMING_SNAKE_CASE_ : str ):
"""simple docstring"""
UpperCamelCase = {}
for key_guess in range(1 , len(SCREAMING_SNAKE_CASE_ ) ): # tries every key
UpperCamelCase = decrypt(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
return results
if __name__ == "__main__":
import doctest
doctest.testmod()
| 386 |
import logging
import os
from typing import Dict, List, Optional, Union
import torch
import torch.nn as nn
from accelerate.utils.imports import (
is_abit_bnb_available,
is_abit_bnb_available,
is_bnb_available,
)
from ..big_modeling import dispatch_model, init_empty_weights
from .dataclasses import BnbQuantizationConfig
from .modeling import (
find_tied_parameters,
get_balanced_memory,
infer_auto_device_map,
load_checkpoint_in_model,
offload_weight,
set_module_tensor_to_device,
)
if is_bnb_available():
import bitsandbytes as bnb
from copy import deepcopy
__snake_case = logging.getLogger(__name__)
def _lowercase ( SCREAMING_SNAKE_CASE_ : torch.nn.Module , SCREAMING_SNAKE_CASE_ : BnbQuantizationConfig , SCREAMING_SNAKE_CASE_ : Union[str, os.PathLike] = None , SCREAMING_SNAKE_CASE_ : Optional[Dict[str, Union[int, str, torch.device]]] = None , SCREAMING_SNAKE_CASE_ : Optional[List[str]] = None , SCREAMING_SNAKE_CASE_ : Optional[Dict[Union[int, str], Union[int, str]]] = None , SCREAMING_SNAKE_CASE_ : Optional[Union[str, os.PathLike]] = None , SCREAMING_SNAKE_CASE_ : bool = False , ):
"""simple docstring"""
UpperCamelCase = bnb_quantization_config.load_in_abit
UpperCamelCase = bnb_quantization_config.load_in_abit
if load_in_abit and not is_abit_bnb_available():
raise ImportError(
"""You have a version of `bitsandbytes` that is not compatible with 8bit quantization,"""
""" make sure you have the latest version of `bitsandbytes` installed.""" )
if load_in_abit and not is_abit_bnb_available():
raise ValueError(
"""You have a version of `bitsandbytes` that is not compatible with 4bit quantization,"""
"""make sure you have the latest version of `bitsandbytes` installed.""" )
UpperCamelCase = []
# custom device map
if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and len(device_map.keys() ) > 1:
UpperCamelCase = [key for key, value in device_map.items() if value in ["""disk""", """cpu"""]]
# We keep some modules such as the lm_head in their original dtype for numerical stability reasons
if bnb_quantization_config.skip_modules is None:
UpperCamelCase = get_keys_to_not_convert(SCREAMING_SNAKE_CASE_ )
# add cpu modules to skip modules only for 4-bit modules
if load_in_abit:
bnb_quantization_config.skip_modules.extend(SCREAMING_SNAKE_CASE_ )
UpperCamelCase = bnb_quantization_config.skip_modules
# We add the modules we want to keep in full precision
if bnb_quantization_config.keep_in_fpaa_modules is None:
UpperCamelCase = []
UpperCamelCase = bnb_quantization_config.keep_in_fpaa_modules
modules_to_not_convert.extend(SCREAMING_SNAKE_CASE_ )
# compatibility with peft
UpperCamelCase = load_in_abit
UpperCamelCase = load_in_abit
UpperCamelCase = get_parameter_device(SCREAMING_SNAKE_CASE_ )
if model_device.type != "meta":
# quantization of an already loaded model
logger.warning(
"""It is not recommended to quantize a loaded model. """
"""The model should be instantiated under the `init_empty_weights` context manager.""" )
UpperCamelCase = replace_with_bnb_layers(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , modules_to_not_convert=SCREAMING_SNAKE_CASE_ )
# convert param to the right dtype
UpperCamelCase = bnb_quantization_config.torch_dtype
for name, param in model.state_dict().items():
if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ):
param.to(torch.floataa )
if param.dtype != torch.floataa:
UpperCamelCase = name.replace(""".weight""" , """""" ).replace(""".bias""" , """""" )
UpperCamelCase = getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
if param is not None:
param.to(torch.floataa )
elif torch.is_floating_point(SCREAMING_SNAKE_CASE_ ):
param.to(SCREAMING_SNAKE_CASE_ )
if model_device.type == "cuda":
# move everything to cpu in the first place because we can't do quantization if the weights are already on cuda
model.cuda(torch.cuda.current_device() )
torch.cuda.empty_cache()
elif torch.cuda.is_available():
model.to(torch.cuda.current_device() )
else:
raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" )
logger.info(
f'The model device type is {model_device.type}. However, cuda is needed for quantization.'
"""We move the model to cuda.""" )
return model
elif weights_location is None:
raise RuntimeError(
f'`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} ' )
else:
with init_empty_weights():
UpperCamelCase = replace_with_bnb_layers(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , modules_to_not_convert=SCREAMING_SNAKE_CASE_ )
UpperCamelCase = get_quantized_model_device_map(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , max_memory=SCREAMING_SNAKE_CASE_ , no_split_module_classes=SCREAMING_SNAKE_CASE_ , )
if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
UpperCamelCase = True
UpperCamelCase = any(x in list(device_map.values() ) for x in ["""cpu""", """disk"""] )
load_checkpoint_in_model(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , dtype=bnb_quantization_config.torch_dtype , offload_folder=SCREAMING_SNAKE_CASE_ , offload_state_dict=SCREAMING_SNAKE_CASE_ , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , )
return dispatch_model(SCREAMING_SNAKE_CASE_ , device_map=SCREAMING_SNAKE_CASE_ , offload_dir=SCREAMING_SNAKE_CASE_ )
def _lowercase ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Union[str, Any]=None , SCREAMING_SNAKE_CASE_ : Any=None , SCREAMING_SNAKE_CASE_ : Union[str, Any]=None ):
"""simple docstring"""
if device_map is None:
if torch.cuda.is_available():
UpperCamelCase = {"""""": torch.cuda.current_device()}
else:
raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" )
logger.info("""The device_map was not initialized.""" """Setting device_map to `{'':torch.cuda.current_device()}`.""" )
if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
raise ValueError(
"""If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or """
"""'sequential'.""" )
UpperCamelCase = {}
special_dtypes.update(
{
name: bnb_quantization_config.torch_dtype
for name, _ in model.named_parameters()
if any(m in name for m in bnb_quantization_config.skip_modules )
} )
special_dtypes.update(
{
name: torch.floataa
for name, _ in model.named_parameters()
if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules )
} )
UpperCamelCase = {}
UpperCamelCase = special_dtypes
UpperCamelCase = no_split_module_classes
UpperCamelCase = bnb_quantization_config.target_dtype
# get max_memory for each device.
if device_map != "sequential":
UpperCamelCase = get_balanced_memory(
SCREAMING_SNAKE_CASE_ , low_zero=(device_map == """balanced_low_0""") , max_memory=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , )
UpperCamelCase = max_memory
UpperCamelCase = infer_auto_device_map(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
# check if don't have any quantized module on the cpu
UpperCamelCase = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules
UpperCamelCase = {
key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert
}
for device in ["cpu", "disk"]:
if device in device_map_without_some_modules.values():
if bnb_quantization_config.load_in_abit:
raise ValueError(
"""
Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit
the quantized model. If you want to dispatch the model on the CPU or the disk while keeping
these modules in `torch_dtype`, you need to pass a custom `device_map` to
`load_and_quantize_model`. Check
https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk
for more details.
""" )
else:
logger.info(
"""Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit""" )
del device_map_without_some_modules
return device_map
def _lowercase ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[Any]=None , SCREAMING_SNAKE_CASE_ : Union[str, Any]=None ):
"""simple docstring"""
if modules_to_not_convert is None:
UpperCamelCase = []
UpperCamelCase , UpperCamelCase = _replace_with_bnb_layers(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
if not has_been_replaced:
logger.warning(
"""You are loading your model in 8bit or 4bit but no linear modules were found in your model."""
""" this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers."""
""" Please double check your model architecture, or submit an issue on github if you think this is"""
""" a bug.""" )
return model
def _lowercase ( SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : List[str]=None , SCREAMING_SNAKE_CASE_ : Dict=None , ):
"""simple docstring"""
UpperCamelCase = False
for name, module in model.named_children():
if current_key_name is None:
UpperCamelCase = []
current_key_name.append(SCREAMING_SNAKE_CASE_ )
if isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) and name not in modules_to_not_convert:
# Check if the current key is not in the `modules_to_not_convert`
UpperCamelCase = """.""".join(SCREAMING_SNAKE_CASE_ )
UpperCamelCase = True
for key in modules_to_not_convert:
if (
(key in current_key_name_str) and (key + "." in current_key_name_str)
) or key == current_key_name_str:
UpperCamelCase = False
break
if proceed:
# Load bnb module with empty weight and replace ``nn.Linear` module
if bnb_quantization_config.load_in_abit:
UpperCamelCase = bnb.nn.LinearabitLt(
module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=SCREAMING_SNAKE_CASE_ , threshold=bnb_quantization_config.llm_inta_threshold , )
elif bnb_quantization_config.load_in_abit:
UpperCamelCase = bnb.nn.Linearabit(
module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , )
else:
raise ValueError("""load_in_8bit and load_in_4bit can't be both False""" )
UpperCamelCase = module.weight.data
if module.bias is not None:
UpperCamelCase = module.bias.data
bnb_module.requires_grad_(SCREAMING_SNAKE_CASE_ )
setattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase = True
if len(list(module.children() ) ) > 0:
UpperCamelCase , UpperCamelCase = _replace_with_bnb_layers(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase = has_been_replaced | _has_been_replaced
# Remove the last key for recursion
current_key_name.pop(-1 )
return model, has_been_replaced
def _lowercase ( SCREAMING_SNAKE_CASE_ : Optional[int] ):
"""simple docstring"""
with init_empty_weights():
UpperCamelCase = deepcopy(SCREAMING_SNAKE_CASE_ ) # this has 0 cost since it is done inside `init_empty_weights` context manager`
UpperCamelCase = find_tied_parameters(SCREAMING_SNAKE_CASE_ )
# For compatibility with Accelerate < 0.18
if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
UpperCamelCase = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() )
else:
UpperCamelCase = sum(SCREAMING_SNAKE_CASE_ , [] )
UpperCamelCase = len(SCREAMING_SNAKE_CASE_ ) > 0
# Check if it is a base model
UpperCamelCase = False
if hasattr(SCREAMING_SNAKE_CASE_ , """base_model_prefix""" ):
UpperCamelCase = not hasattr(SCREAMING_SNAKE_CASE_ , model.base_model_prefix )
# Ignore this for base models (BertModel, GPT2Model, etc.)
if (not has_tied_params) and is_base_model:
return []
# otherwise they have an attached head
UpperCamelCase = list(model.named_children() )
UpperCamelCase = [list_modules[-1][0]]
# add last module together with tied weights
UpperCamelCase = set(SCREAMING_SNAKE_CASE_ ) - set(SCREAMING_SNAKE_CASE_ )
UpperCamelCase = list(set(SCREAMING_SNAKE_CASE_ ) ) + list(SCREAMING_SNAKE_CASE_ )
# remove ".weight" from the keys
UpperCamelCase = [""".weight""", """.bias"""]
UpperCamelCase = []
for name in list_untouched:
for name_to_remove in names_to_remove:
if name_to_remove in name:
UpperCamelCase = name.replace(SCREAMING_SNAKE_CASE_ , """""" )
filtered_module_names.append(SCREAMING_SNAKE_CASE_ )
return filtered_module_names
def _lowercase ( SCREAMING_SNAKE_CASE_ : List[Any] ):
"""simple docstring"""
for m in model.modules():
if isinstance(SCREAMING_SNAKE_CASE_ , bnb.nn.Linearabit ):
return True
return False
def _lowercase ( SCREAMING_SNAKE_CASE_ : nn.Module ):
"""simple docstring"""
return next(parameter.parameters() ).device
def _lowercase ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Optional[int] ):
"""simple docstring"""
if fpaa_statistics is None:
set_module_tensor_to_device(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 0 , dtype=SCREAMING_SNAKE_CASE_ , value=SCREAMING_SNAKE_CASE_ )
UpperCamelCase = param_name
UpperCamelCase = model
if "." in tensor_name:
UpperCamelCase = tensor_name.split(""".""" )
for split in splits[:-1]:
UpperCamelCase = getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
if new_module is None:
raise ValueError(f'{module} has no attribute {split}.' )
UpperCamelCase = new_module
UpperCamelCase = splits[-1]
# offload weights
UpperCamelCase = False
offload_weight(module._parameters[tensor_name] , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , index=SCREAMING_SNAKE_CASE_ )
if hasattr(module._parameters[tensor_name] , """SCB""" ):
offload_weight(
module._parameters[tensor_name].SCB , param_name.replace("""weight""" , """SCB""" ) , SCREAMING_SNAKE_CASE_ , index=SCREAMING_SNAKE_CASE_ , )
else:
offload_weight(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , index=SCREAMING_SNAKE_CASE_ )
offload_weight(SCREAMING_SNAKE_CASE_ , param_name.replace("""weight""" , """SCB""" ) , SCREAMING_SNAKE_CASE_ , index=SCREAMING_SNAKE_CASE_ )
set_module_tensor_to_device(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , """meta""" , dtype=SCREAMING_SNAKE_CASE_ , value=torch.empty(*param.size() ) )
| 386 | 1 |
'''simple docstring'''
import argparse
import torch
from torch import nn
from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration
def _lowerCamelCase (__lowerCamelCase : Dict ) -> Dict:
a__ = [
"encoder.version",
"decoder.version",
"model.encoder.version",
"model.decoder.version",
"decoder.output_projection.weight",
"_float_tensor",
"encoder.embed_positions._float_tensor",
"decoder.embed_positions._float_tensor",
]
for k in ignore_keys:
state_dict.pop(__lowerCamelCase , __lowerCamelCase )
def _lowerCamelCase (__lowerCamelCase : Optional[Any] ) -> Optional[Any]:
a__ = list(s_dict.keys() )
for key in keys:
if "transformer_layers" in key:
a__ = s_dict.pop(__lowerCamelCase )
elif "subsample" in key:
a__ = s_dict.pop(__lowerCamelCase )
def _lowerCamelCase (__lowerCamelCase : List[str] ) -> Dict:
a__ , a__ = emb.weight.shape
a__ = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase )
a__ = emb.weight.data
return lin_layer
def _lowerCamelCase (__lowerCamelCase : Any , __lowerCamelCase : List[str] ) -> Any:
a__ = torch.load(__lowerCamelCase , map_location="cpu" )
a__ = mam_aaa["args"]
a__ = mam_aaa["model"]
a__ = state_dict["decoder.output_projection.weight"]
remove_ignore_keys_(__lowerCamelCase )
rename_keys(__lowerCamelCase )
a__ = state_dict["decoder.embed_tokens.weight"].shape[0]
a__ = args.share_decoder_input_output_embed
a__ = [int(__lowerCamelCase ) for i in args.conv_kernel_sizes.split("," )]
a__ = SpeechaTextConfig(
vocab_size=__lowerCamelCase , max_source_positions=args.max_source_positions , max_target_positions=args.max_target_positions , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="relu" , num_conv_layers=len(__lowerCamelCase ) , conv_channels=args.conv_channels , conv_kernel_sizes=__lowerCamelCase , input_feat_per_channel=args.input_feat_per_channel , input_channels=args.input_channels , tie_word_embeddings=__lowerCamelCase , num_beams=5 , max_length=200 , use_cache=__lowerCamelCase , decoder_start_token_id=2 , early_stopping=__lowerCamelCase , )
a__ = SpeechaTextForConditionalGeneration(__lowerCamelCase )
a__ , a__ = model.model.load_state_dict(__lowerCamelCase , strict=__lowerCamelCase )
if len(__lowerCamelCase ) > 0 and not set(__lowerCamelCase ) <= {
"encoder.embed_positions.weights",
"decoder.embed_positions.weights",
}:
raise ValueError(
"Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,"
f''' but all the following weights are missing {missing}''' )
if tie_embeds:
a__ = make_linear_from_emb(model.model.decoder.embed_tokens )
else:
a__ = lm_head_weights
model.save_pretrained(__lowerCamelCase )
if __name__ == "__main__":
lowerCAmelCase_ : Tuple = argparse.ArgumentParser()
# Required parameters
parser.add_argument("--fairseq_path", type=str, help="Path to the fairseq model (.pt) file.")
parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
lowerCAmelCase_ : Optional[Any] = parser.parse_args()
convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)
| 289 |
'''simple docstring'''
def _lowerCamelCase (__lowerCamelCase : list[list[float]] ) -> list[list[float]]:
a__ = []
for data in source_data:
for i, el in enumerate(__lowerCamelCase ):
if len(__lowerCamelCase ) < i + 1:
data_lists.append([] )
data_lists[i].append(float(__lowerCamelCase ) )
return data_lists
def _lowerCamelCase (__lowerCamelCase : list[list[float]] , __lowerCamelCase : list[int] ) -> list[list[float]]:
a__ = []
for dlist, weight in zip(__lowerCamelCase , __lowerCamelCase ):
a__ = min(__lowerCamelCase )
a__ = max(__lowerCamelCase )
a__ = []
# for weight 0 score is 1 - actual score
if weight == 0:
for item in dlist:
try:
score.append(1 - ((item - mind) / (maxd - mind)) )
except ZeroDivisionError:
score.append(1 )
elif weight == 1:
for item in dlist:
try:
score.append((item - mind) / (maxd - mind) )
except ZeroDivisionError:
score.append(0 )
# weight not 0 or 1
else:
a__ = f'''Invalid weight of {weight:f} provided'''
raise ValueError(__lowerCamelCase )
score_lists.append(__lowerCamelCase )
return score_lists
def _lowerCamelCase (__lowerCamelCase : list[list[float]] ) -> list[float]:
a__ = [0 for i in range(len(score_lists[0] ) )]
for slist in score_lists:
for j, ele in enumerate(__lowerCamelCase ):
a__ = final_scores[j] + ele
return final_scores
def _lowerCamelCase (__lowerCamelCase : list[list[float]] , __lowerCamelCase : list[int] ) -> list[list[float]]:
a__ = get_data(__lowerCamelCase )
a__ = calculate_each_score(__lowerCamelCase , __lowerCamelCase )
a__ = generate_final_scores(__lowerCamelCase )
# append scores to source data
for i, ele in enumerate(__lowerCamelCase ):
source_data[i].append(__lowerCamelCase )
return source_data
| 289 | 1 |
import tempfile
import unittest
from transformers import TaConfig, is_torch_available
from transformers.testing_utils import (
require_sentencepiece,
require_tokenizers,
require_torch,
slow,
torch_device,
)
from ...generation.test_utils import GenerationTesterMixin
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel
class __lowercase :
def __init__( self : Tuple , __lowerCamelCase : int , __lowerCamelCase : List[Any]=99 , __lowerCamelCase : Any=13 , __lowerCamelCase : str=7 , __lowerCamelCase : int=9 , __lowerCamelCase : List[str]=True , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Union[str, Any]=False , __lowerCamelCase : Any=32 , __lowerCamelCase : Any=5 , __lowerCamelCase : Tuple=4 , __lowerCamelCase : List[str]=37 , __lowerCamelCase : Any=8 , __lowerCamelCase : int=0.1 , __lowerCamelCase : str=0.002 , __lowerCamelCase : Optional[int]=1 , __lowerCamelCase : int=0 , __lowerCamelCase : Dict=0 , __lowerCamelCase : Tuple=None , __lowerCamelCase : Optional[int]=None , ) -> List[str]:
'''simple docstring'''
lowercase = parent
lowercase = batch_size
lowercase = encoder_seq_length
lowercase = decoder_seq_length
# For common tests
lowercase = self.decoder_seq_length
lowercase = is_training
lowercase = use_attention_mask
lowercase = use_labels
lowercase = vocab_size
lowercase = hidden_size
lowercase = num_hidden_layers
lowercase = num_attention_heads
lowercase = d_ff
lowercase = relative_attention_num_buckets
lowercase = dropout_rate
lowercase = initializer_factor
lowercase = eos_token_id
lowercase = pad_token_id
lowercase = decoder_start_token_id
lowercase = None
lowercase = decoder_layers
def __a ( self : Optional[int] ) -> int:
'''simple docstring'''
return TaConfig.from_pretrained('''google/umt5-base''' )
def __a ( self : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : Any , __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any]=None , __lowerCamelCase : List[Any]=None , __lowerCamelCase : Dict=None , __lowerCamelCase : str=None , __lowerCamelCase : Optional[int]=None , ) -> int:
'''simple docstring'''
if attention_mask is None:
lowercase = input_ids.ne(config.pad_token_id )
if decoder_attention_mask is None:
lowercase = decoder_input_ids.ne(config.pad_token_id )
if head_mask is None:
lowercase = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=a_ )
if decoder_head_mask is None:
lowercase = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=a_ )
if cross_attn_head_mask is None:
lowercase = torch.ones(
config.num_decoder_layers , config.num_attention_heads , device=a_ )
return {
"input_ids": input_ids,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"decoder_attention_mask": decoder_attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"cross_attn_head_mask": cross_attn_head_mask,
}
def __a ( self : Union[str, Any] ) -> Tuple:
'''simple docstring'''
lowercase = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size )
lowercase = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size )
# we need to clamp the input ids here to avoid having pad token in between
# this is because for NllbMoe the position_ids are prepared such that
# all pad tokens have pos id = 2 and rest are between 2..seq_length
# and the seq_length here is seq_length - num_pad_tokens
# but when using past, there is no way of knowing if the past input ids had
# pad tokens in them, which results in incorrect seq_lenth and which in turn results in
# position_ids being off by num_pad_tokens in past input
lowercase = input_ids.clamp(self.pad_token_id + 1 )
lowercase = decoder_input_ids.clamp(self.pad_token_id + 1 )
lowercase = self.get_config()
lowercase = config.num_attention_heads
lowercase = self.prepare_inputs_dict(a_ , a_ , a_ )
return config, input_dict
def __a ( self : List[Any] ) -> Optional[Any]:
'''simple docstring'''
lowercase = self.prepare_config_and_inputs()
return config, inputs_dict
def __a ( self : Tuple ) -> Dict:
'''simple docstring'''
return TaConfig(
vocab_size=1_66 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , )
def __a ( self : Union[str, Any] ) -> Any:
'''simple docstring'''
return TaConfig(
vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , )
def __a ( self : Optional[int] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : int , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : int , ) -> List[str]:
'''simple docstring'''
lowercase = UMTaModel(config=a_ )
model.to(a_ )
model.eval()
lowercase = model(
input_ids=a_ , decoder_input_ids=a_ , attention_mask=a_ , decoder_attention_mask=a_ , )
lowercase = model(input_ids=a_ , decoder_input_ids=a_ )
lowercase = result.last_hidden_state
lowercase = result.past_key_values
lowercase = result.encoder_last_hidden_state
self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) )
self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) )
# There should be `num_layers` key value embeddings stored in decoder_past
self.parent.assertEqual(len(a_ ) , config.num_layers )
# There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple
self.parent.assertEqual(len(decoder_past[0] ) , 4 )
def __a ( self : List[str] , __lowerCamelCase : Any , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Tuple , __lowerCamelCase : int , __lowerCamelCase : str , __lowerCamelCase : List[str] , ) -> Union[str, Any]:
'''simple docstring'''
lowercase = UMTaModel(config=a_ ).get_decoder().to(a_ ).eval()
# first forward pass
lowercase = model(a_ , use_cache=a_ )
lowercase = model(a_ )
lowercase = model(a_ , use_cache=a_ )
self.parent.assertTrue(len(a_ ) == len(a_ ) )
self.parent.assertTrue(len(a_ ) == len(a_ ) + 1 )
lowercase = outputs.to_tuple()
# create hypothetical next token and extent to next_input_ids
lowercase = ids_tensor((self.batch_size, 1) , config.vocab_size )
# append to next input_ids and
lowercase = torch.cat([input_ids, next_tokens] , dim=-1 )
lowercase = model(a_ )["last_hidden_state"]
lowercase = model(a_ , past_key_values=a_ )["last_hidden_state"]
# select random slice
lowercase = ids_tensor((1,) , output_from_past.shape[-1] ).item()
lowercase = output_from_no_past[:, -1, random_slice_idx].detach()
lowercase = output_from_past[:, 0, random_slice_idx].detach()
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1E-3 ) )
def __a ( self : List[Any] , __lowerCamelCase : List[Any] , __lowerCamelCase : List[str] , ) -> Any:
'''simple docstring'''
lowercase = UMTaModel(config=a_ ).to(a_ ).half().eval()
lowercase = model(**a_ )["last_hidden_state"]
self.parent.assertFalse(torch.isnan(a_ ).any().item() )
@require_torch
class __lowercase ( _A , _A , _A , unittest.TestCase ):
lowercase = (
(UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else ()
)
lowercase = (UMTaForConditionalGeneration,) if is_torch_available() else ()
lowercase = (
{
'conversational': UMTaForConditionalGeneration,
'feature-extraction': UMTaModel,
'summarization': UMTaForConditionalGeneration,
'text2text-generation': UMTaForConditionalGeneration,
'translation': UMTaForConditionalGeneration,
'question-answering': UMTaForQuestionAnswering,
}
if is_torch_available()
else {}
)
lowercase = True
lowercase = False
lowercase = False
lowercase = True
lowercase = True
# The small UMT5 model needs higher percentages for CPU/MP tests
lowercase = [0.8, 0.9]
def __a ( self : List[Any] ) -> Tuple:
'''simple docstring'''
lowercase = UMTaModelTester(self )
@unittest.skip('''Test has a segmentation fault on torch 1.8.0''' )
def __a ( self : str ) -> int:
'''simple docstring'''
lowercase = self.model_tester.prepare_config_and_inputs()
lowercase = UMTaModel(config_and_inputs[0] ).to(a_ )
with tempfile.TemporaryDirectory() as tmpdirname:
torch.onnx.export(
a_ , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , f'{tmpdirname}/t5_test.onnx' , export_params=a_ , opset_version=9 , input_names=['''input_ids''', '''decoder_input_ids'''] , )
@unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' )
def __a ( self : Optional[int] ) -> List[str]:
'''simple docstring'''
lowercase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model_fpaa_forward(*a_ )
def __a ( self : int ) -> List[str]:
'''simple docstring'''
lowercase = ["encoder_attentions", "decoder_attentions", "cross_attentions"]
lowercase = self.model_tester.prepare_config_and_inputs()
lowercase = config_and_inputs[0]
lowercase = UMTaForConditionalGeneration(a_ ).eval()
model.to(a_ )
lowercase = {
"head_mask": torch.zeros(config.num_layers , config.num_heads , device=a_ ),
"decoder_head_mask": torch.zeros(config.num_decoder_layers , config.num_heads , device=a_ ),
"cross_attn_head_mask": torch.zeros(config.num_decoder_layers , config.num_heads , device=a_ ),
}
for attn_name, (name, mask) in zip(a_ , head_masking.items() ):
lowercase = {name: mask}
# Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified
if name == "head_mask":
lowercase = torch.ones(
config.num_decoder_layers , config.num_heads , device=a_ )
lowercase = model.generate(
config_and_inputs[1]['''input_ids'''] , num_beams=1 , max_length=3 , output_attentions=a_ , return_dict_in_generate=a_ , **a_ , )
# We check the state of decoder_attentions and cross_attentions just from the last step
lowercase = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1]
self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 )
@unittest.skip('''Does not work on the tiny model as we keep hitting edge cases.''' )
def __a ( self : Optional[int] ) -> int:
'''simple docstring'''
pass
@require_torch
@require_sentencepiece
@require_tokenizers
class __lowercase ( unittest.TestCase ):
@slow
@unittest.skip(
'''Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged''' )
def __a ( self : Optional[int] ) -> Any:
'''simple docstring'''
lowercase = UMTaForConditionalGeneration.from_pretrained('''google/umt5-small''' , return_dict=a_ ).to(a_ )
lowercase = AutoTokenizer.from_pretrained('''google/umt5-small''' , use_fast=a_ , legacy=a_ )
lowercase = [
"Bonjour monsieur <extra_id_0> bien <extra_id_1>.",
"No se como puedo <extra_id_0>.",
"This is the reason why we <extra_id_0> them.",
"The <extra_id_0> walks in <extra_id_1>, seats",
"A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.",
]
lowercase = tokenizer(a_ , return_tensors='''pt''' , padding=a_ ).input_ids
# fmt: off
lowercase = torch.tensor(
[
[ 3_85_30, 21_07_03, 25_62_99, 14_10, 25_62_98, 2_74, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0],
[ 8_26, 3_21, 6_71, 2_59_22, 25_62_99, 2_74, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0],
[ 14_60, 3_39, 3_12, 1_90_14, 1_06_20, 7_58, 25_62_99, 23_55,2_74, 1, 0, 0, 0, 0, 0, 0,0, 0],
[ 5_17, 25_62_99, 1_48_69, 2_81, 3_01, 25_62_98, 2_75, 11_99_83,1, 0, 0, 0, 0, 0, 0, 0,0, 0],
[ 3_20, 25_62_99, 1_48_69, 2_81, 22_34, 2_89, 22_75, 3_33,6_13_91, 2_89, 25_62_98, 5_43, 25_62_97, 16_87_14, 3_29, 25_62_96,2_74, 1],
] )
# fmt: on
torch.testing.assert_allclose(a_ , a_ )
lowercase = model.generate(input_ids.to(a_ ) )
lowercase = [
"<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>",
"<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>",
"<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>",
"<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>",
"<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>",
]
lowercase = tokenizer.batch_decode(a_ )
self.assertEqual(a_ , a_ )
| 604 |
'''simple docstring'''
import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional
import datasets
import evaluate
import numpy as np
from datasets import load_dataset
import transformers
from transformers import (
AutoConfig,
AutoModelForSequenceClassification,
AutoTokenizer,
DataCollatorWithPadding,
EvalPrediction,
HfArgumentParser,
Trainer,
TrainingArguments,
default_data_collator,
set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("""4.31.0""")
require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/text-classification/requirements.txt""")
lowerCAmelCase = logging.getLogger(__name__)
@dataclass
class lowerCamelCase :
snake_case_ = field(
default=128 , metadata={
"help": (
"The maximum total input sequence length after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded."
)
} , )
snake_case_ = field(
default=_A , metadata={"help": "Overwrite the cached preprocessed datasets or not."} )
snake_case_ = field(
default=_A , 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."
)
} , )
snake_case_ = field(
default=_A , metadata={
"help": (
"For debugging purposes or quicker training, truncate the number of training examples to this "
"value if set."
)
} , )
snake_case_ = field(
default=_A , metadata={
"help": (
"For debugging purposes or quicker training, truncate the number of evaluation examples to this "
"value if set."
)
} , )
snake_case_ = field(
default=_A , metadata={
"help": (
"For debugging purposes or quicker training, truncate the number of prediction examples to this "
"value if set."
)
} , )
@dataclass
class lowerCamelCase :
snake_case_ = field(
default=_A , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} )
snake_case_ = field(
default=_A , metadata={"help": "Evaluation language. Also train language if `train_language` is set to None."} )
snake_case_ = field(
default=_A , metadata={"help": "Train language if it is different from the evaluation language."} )
snake_case_ = field(
default=_A , metadata={"help": "Pretrained config name or path if not the same as model_name"} )
snake_case_ = field(
default=_A , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} )
snake_case_ = field(
default=_A , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , )
snake_case_ = field(
default=_A , metadata={"help": "arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"} , )
snake_case_ = field(
default=_A , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , )
snake_case_ = field(
default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , )
snake_case_ = field(
default=_A , metadata={
"help": (
"Will use the token generated when running `huggingface-cli login` (necessary to use this script "
"with private models)."
)
} , )
snake_case_ = field(
default=_A , metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} , )
def __A ( ):
# 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 : List[str] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
lowerCAmelCase , lowerCAmelCase , lowerCAmelCase : Tuple = parser.parse_args_into_dataclasses()
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_xnli" ,a_ )
# 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 )] ,)
if training_args.should_log:
# The default of training_args.log_level is passive, so we set log level at info here to have that default.
transformers.utils.logging.set_verbosity_info()
lowerCAmelCase : str = training_args.get_process_log_level()
logger.setLevel(a_ )
datasets.utils.logging.set_verbosity(a_ )
transformers.utils.logging.set_verbosity(a_ )
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
# 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}''' )
logger.info(f'''Training/evaluation parameters {training_args}''' )
# Detecting last checkpoint.
lowerCAmelCase : Union[str, Any] = None
if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir:
lowerCAmelCase : Dict = 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." )
# Set seed before initializing model.
set_seed(training_args.seed )
# In distributed training, the load_dataset function guarantees that only one local process can concurrently
# download the dataset.
# Downloading and loading xnli dataset from the hub.
if training_args.do_train:
if model_args.train_language is None:
lowerCAmelCase : Any = load_dataset(
"xnli" ,model_args.language ,split="train" ,cache_dir=model_args.cache_dir ,use_auth_token=True if model_args.use_auth_token else None ,)
else:
lowerCAmelCase : Union[str, Any] = load_dataset(
"xnli" ,model_args.train_language ,split="train" ,cache_dir=model_args.cache_dir ,use_auth_token=True if model_args.use_auth_token else None ,)
lowerCAmelCase : int = train_dataset.features["label"].names
if training_args.do_eval:
lowerCAmelCase : Any = load_dataset(
"xnli" ,model_args.language ,split="validation" ,cache_dir=model_args.cache_dir ,use_auth_token=True if model_args.use_auth_token else None ,)
lowerCAmelCase : Dict = eval_dataset.features["label"].names
if training_args.do_predict:
lowerCAmelCase : Optional[Any] = load_dataset(
"xnli" ,model_args.language ,split="test" ,cache_dir=model_args.cache_dir ,use_auth_token=True if model_args.use_auth_token else None ,)
lowerCAmelCase : List[Any] = predict_dataset.features["label"].names
# Labels
lowerCAmelCase : Tuple = len(a_ )
# Load pretrained model and tokenizer
# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
lowerCAmelCase : List[str] = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path ,num_labels=a_ ,idalabel={str(a_ ): label for i, label in enumerate(a_ )} ,labelaid={label: i for i, label in enumerate(a_ )} ,finetuning_task="xnli" ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,)
lowerCAmelCase : Optional[Any] = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path ,do_lower_case=model_args.do_lower_case ,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 ,)
lowerCAmelCase : List[Any] = AutoModelForSequenceClassification.from_pretrained(
model_args.model_name_or_path ,from_tf=bool(".ckpt" in model_args.model_name_or_path ) ,config=a_ ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,ignore_mismatched_sizes=model_args.ignore_mismatched_sizes ,)
# Preprocessing the datasets
# Padding strategy
if data_args.pad_to_max_length:
lowerCAmelCase : int = "max_length"
else:
# We will pad later, dynamically at batch creation, to the max sequence length in each batch
lowerCAmelCase : Union[str, Any] = False
def preprocess_function(a_ : Dict ):
# Tokenize the texts
return tokenizer(
examples["premise"] ,examples["hypothesis"] ,padding=a_ ,max_length=data_args.max_seq_length ,truncation=a_ ,)
if training_args.do_train:
if data_args.max_train_samples is not None:
lowerCAmelCase : Tuple = min(len(a_ ) ,data_args.max_train_samples )
lowerCAmelCase : int = train_dataset.select(range(a_ ) )
with training_args.main_process_first(desc="train dataset map pre-processing" ):
lowerCAmelCase : Optional[int] = train_dataset.map(
a_ ,batched=a_ ,load_from_cache_file=not data_args.overwrite_cache ,desc="Running tokenizer on train dataset" ,)
# Log a few random samples from the training set:
for index in random.sample(range(len(a_ ) ) ,3 ):
logger.info(f'''Sample {index} of the training set: {train_dataset[index]}.''' )
if training_args.do_eval:
if data_args.max_eval_samples is not None:
lowerCAmelCase : int = min(len(a_ ) ,data_args.max_eval_samples )
lowerCAmelCase : Optional[Any] = eval_dataset.select(range(a_ ) )
with training_args.main_process_first(desc="validation dataset map pre-processing" ):
lowerCAmelCase : Optional[Any] = eval_dataset.map(
a_ ,batched=a_ ,load_from_cache_file=not data_args.overwrite_cache ,desc="Running tokenizer on validation dataset" ,)
if training_args.do_predict:
if data_args.max_predict_samples is not None:
lowerCAmelCase : Optional[Any] = min(len(a_ ) ,data_args.max_predict_samples )
lowerCAmelCase : Optional[Any] = predict_dataset.select(range(a_ ) )
with training_args.main_process_first(desc="prediction dataset map pre-processing" ):
lowerCAmelCase : Tuple = predict_dataset.map(
a_ ,batched=a_ ,load_from_cache_file=not data_args.overwrite_cache ,desc="Running tokenizer on prediction dataset" ,)
# Get the metric function
lowerCAmelCase : str = evaluate.load("xnli" )
# You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
# predictions and label_ids field) and has to return a dictionary string to float.
def compute_metrics(a_ : EvalPrediction ):
lowerCAmelCase : Union[str, Any] = p.predictions[0] if isinstance(p.predictions ,a_ ) else p.predictions
lowerCAmelCase : Any = np.argmax(a_ ,axis=1 )
return metric.compute(predictions=a_ ,references=p.label_ids )
# Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
if data_args.pad_to_max_length:
lowerCAmelCase : Optional[Any] = default_data_collator
elif training_args.fpaa:
lowerCAmelCase : Union[str, Any] = DataCollatorWithPadding(a_ ,pad_to_multiple_of=8 )
else:
lowerCAmelCase : str = None
# Initialize our Trainer
lowerCAmelCase : Tuple = Trainer(
model=a_ ,args=a_ ,train_dataset=train_dataset if training_args.do_train else None ,eval_dataset=eval_dataset if training_args.do_eval else None ,compute_metrics=a_ ,tokenizer=a_ ,data_collator=a_ ,)
# Training
if training_args.do_train:
lowerCAmelCase : str = None
if training_args.resume_from_checkpoint is not None:
lowerCAmelCase : Any = training_args.resume_from_checkpoint
elif last_checkpoint is not None:
lowerCAmelCase : List[str] = last_checkpoint
lowerCAmelCase : Optional[int] = trainer.train(resume_from_checkpoint=a_ )
lowerCAmelCase : List[Any] = train_result.metrics
lowerCAmelCase : Optional[Any] = (
data_args.max_train_samples if data_args.max_train_samples is not None else len(a_ )
)
lowerCAmelCase : Any = min(a_ ,len(a_ ) )
trainer.save_model() # Saves the tokenizer too for easy upload
trainer.log_metrics("train" ,a_ )
trainer.save_metrics("train" ,a_ )
trainer.save_state()
# Evaluation
if training_args.do_eval:
logger.info("*** Evaluate ***" )
lowerCAmelCase : Optional[int] = trainer.evaluate(eval_dataset=a_ )
lowerCAmelCase : Optional[int] = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(a_ )
lowerCAmelCase : Any = min(a_ ,len(a_ ) )
trainer.log_metrics("eval" ,a_ )
trainer.save_metrics("eval" ,a_ )
# Prediction
if training_args.do_predict:
logger.info("*** Predict ***" )
lowerCAmelCase , lowerCAmelCase , lowerCAmelCase : Optional[Any] = trainer.predict(a_ ,metric_key_prefix="predict" )
lowerCAmelCase : List[Any] = (
data_args.max_predict_samples if data_args.max_predict_samples is not None else len(a_ )
)
lowerCAmelCase : Any = min(a_ ,len(a_ ) )
trainer.log_metrics("predict" ,a_ )
trainer.save_metrics("predict" ,a_ )
lowerCAmelCase : Optional[int] = np.argmax(a_ ,axis=1 )
lowerCAmelCase : Any = os.path.join(training_args.output_dir ,"predictions.txt" )
if trainer.is_world_process_zero():
with open(a_ ,"w" ) as writer:
writer.write("index\tprediction\n" )
for index, item in enumerate(a_ ):
lowerCAmelCase : str = label_list[item]
writer.write(f'''{index}\t{item}\n''' )
if __name__ == "__main__":
main()
| 525 | 0 |
import argparse
import torch
from torch import nn
from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration
def UpperCAmelCase__ (lowerCAmelCase_ ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE = [
"encoder.version",
"decoder.version",
"model.encoder.version",
"model.decoder.version",
"decoder.output_projection.weight",
"_float_tensor",
"encoder.embed_positions._float_tensor",
"decoder.embed_positions._float_tensor",
]
for k in ignore_keys:
state_dict.pop(lowerCAmelCase_ , lowerCAmelCase_ )
def UpperCAmelCase__ (lowerCAmelCase_ ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE = list(s_dict.keys() )
for key in keys:
if "transformer_layers" in key:
__SCREAMING_SNAKE_CASE = s_dict.pop(lowerCAmelCase_ )
elif "subsample" in key:
__SCREAMING_SNAKE_CASE = s_dict.pop(lowerCAmelCase_ )
def UpperCAmelCase__ (lowerCAmelCase_ ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = emb.weight.shape
__SCREAMING_SNAKE_CASE = nn.Linear(lowerCAmelCase_ , lowerCAmelCase_ , bias=lowerCAmelCase_ )
__SCREAMING_SNAKE_CASE = emb.weight.data
return lin_layer
def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE = torch.load(lowerCAmelCase_ , map_location="cpu" )
__SCREAMING_SNAKE_CASE = mam_aaa["args"]
__SCREAMING_SNAKE_CASE = mam_aaa["model"]
__SCREAMING_SNAKE_CASE = state_dict["decoder.output_projection.weight"]
remove_ignore_keys_(lowerCAmelCase_ )
rename_keys(lowerCAmelCase_ )
__SCREAMING_SNAKE_CASE = state_dict["decoder.embed_tokens.weight"].shape[0]
__SCREAMING_SNAKE_CASE = args.share_decoder_input_output_embed
__SCREAMING_SNAKE_CASE = [int(lowerCAmelCase_ ) for i in args.conv_kernel_sizes.split("," )]
__SCREAMING_SNAKE_CASE = SpeechaTextConfig(
vocab_size=lowerCAmelCase_ , max_source_positions=args.max_source_positions , max_target_positions=args.max_target_positions , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="relu" , num_conv_layers=len(lowerCAmelCase_ ) , conv_channels=args.conv_channels , conv_kernel_sizes=lowerCAmelCase_ , input_feat_per_channel=args.input_feat_per_channel , input_channels=args.input_channels , tie_word_embeddings=lowerCAmelCase_ , num_beams=5 , max_length=200 , use_cache=lowerCAmelCase_ , decoder_start_token_id=2 , early_stopping=lowerCAmelCase_ , )
__SCREAMING_SNAKE_CASE = SpeechaTextForConditionalGeneration(lowerCAmelCase_ )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model.model.load_state_dict(lowerCAmelCase_ , strict=lowerCAmelCase_ )
if len(lowerCAmelCase_ ) > 0 and not set(lowerCAmelCase_ ) <= {
"encoder.embed_positions.weights",
"decoder.embed_positions.weights",
}:
raise ValueError(
"Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,"
f""" but all the following weights are missing {missing}""" )
if tie_embeds:
__SCREAMING_SNAKE_CASE = make_linear_from_emb(model.model.decoder.embed_tokens )
else:
__SCREAMING_SNAKE_CASE = lm_head_weights
model.save_pretrained(lowerCAmelCase_ )
if __name__ == "__main__":
a__ : Any = argparse.ArgumentParser()
# Required parameters
parser.add_argument('''--fairseq_path''', type=str, help='''Path to the fairseq model (.pt) file.''')
parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
a__ : Tuple = parser.parse_args()
convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)
| 701 |
"""simple docstring"""
import copy
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..bit import BitConfig
a__ : Dict = logging.get_logger(__name__)
a__ : str = {
'''Intel/dpt-large''': '''https://huggingface.co/Intel/dpt-large/resolve/main/config.json''',
# See all DPT models at https://huggingface.co/models?filter=dpt
}
class UpperCamelCase_ ( UpperCamelCase):
"""simple docstring"""
snake_case__ : Optional[Any] = "dpt"
def __init__( self : Tuple , UpperCAmelCase__ : int=7_6_8 , UpperCAmelCase__ : List[str]=1_2 , UpperCAmelCase__ : Any=1_2 , UpperCAmelCase__ : int=3_0_7_2 , UpperCAmelCase__ : List[str]="gelu" , UpperCAmelCase__ : Union[str, Any]=0.0 , UpperCAmelCase__ : Any=0.0 , UpperCAmelCase__ : List[Any]=0.02 , UpperCAmelCase__ : List[Any]=1E-12 , UpperCAmelCase__ : List[str]=3_8_4 , UpperCAmelCase__ : Tuple=1_6 , UpperCAmelCase__ : Optional[Any]=3 , UpperCAmelCase__ : str=False , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : Optional[Any]=[2, 5, 8, 1_1] , UpperCAmelCase__ : Union[str, Any]="project" , UpperCAmelCase__ : Dict=[4, 2, 1, 0.5] , UpperCAmelCase__ : Optional[Any]=[9_6, 1_9_2, 3_8_4, 7_6_8] , UpperCAmelCase__ : List[str]=2_5_6 , UpperCAmelCase__ : Optional[Any]=-1 , UpperCAmelCase__ : Union[str, Any]=False , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : Dict=0.4 , UpperCAmelCase__ : Union[str, Any]=2_5_5 , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Optional[int]=[1, 1_0_2_4, 2_4, 2_4] , UpperCAmelCase__ : List[Any]=[0, 1] , UpperCAmelCase__ : List[str]=None , **UpperCAmelCase__ : List[Any] , ) -> Dict:
super().__init__(**UpperCAmelCase__ )
__SCREAMING_SNAKE_CASE = hidden_size
__SCREAMING_SNAKE_CASE = is_hybrid
if self.is_hybrid:
if backbone_config is None:
logger.info("Initializing the config with a `BiT` backbone." )
__SCREAMING_SNAKE_CASE = {
"global_padding": "same",
"layer_type": "bottleneck",
"depths": [3, 4, 9],
"out_features": ["stage1", "stage2", "stage3"],
"embedding_dynamic_padding": True,
}
__SCREAMING_SNAKE_CASE = BitConfig(**UpperCAmelCase__ )
elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ):
logger.info("Initializing the config with a `BiT` backbone." )
__SCREAMING_SNAKE_CASE = BitConfig(**UpperCAmelCase__ )
elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ):
__SCREAMING_SNAKE_CASE = backbone_config
else:
raise ValueError(
F"""backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.""" )
__SCREAMING_SNAKE_CASE = backbone_featmap_shape
__SCREAMING_SNAKE_CASE = neck_ignore_stages
if readout_type != "project":
raise ValueError("Readout type must be 'project' when using `DPT-hybrid` mode." )
else:
__SCREAMING_SNAKE_CASE = None
__SCREAMING_SNAKE_CASE = None
__SCREAMING_SNAKE_CASE = []
__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 = initializer_range
__SCREAMING_SNAKE_CASE = layer_norm_eps
__SCREAMING_SNAKE_CASE = image_size
__SCREAMING_SNAKE_CASE = patch_size
__SCREAMING_SNAKE_CASE = num_channels
__SCREAMING_SNAKE_CASE = qkv_bias
__SCREAMING_SNAKE_CASE = backbone_out_indices
if readout_type not in ["ignore", "add", "project"]:
raise ValueError("Readout_type must be one of ['ignore', 'add', 'project']" )
__SCREAMING_SNAKE_CASE = readout_type
__SCREAMING_SNAKE_CASE = reassemble_factors
__SCREAMING_SNAKE_CASE = neck_hidden_sizes
__SCREAMING_SNAKE_CASE = fusion_hidden_size
__SCREAMING_SNAKE_CASE = head_in_index
__SCREAMING_SNAKE_CASE = use_batch_norm_in_fusion_residual
# auxiliary head attributes (semantic segmentation)
__SCREAMING_SNAKE_CASE = use_auxiliary_head
__SCREAMING_SNAKE_CASE = auxiliary_loss_weight
__SCREAMING_SNAKE_CASE = semantic_loss_ignore_index
__SCREAMING_SNAKE_CASE = semantic_classifier_dropout
def UpperCAmelCase_ ( self : Optional[int] ) -> str:
__SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__ )
if output["backbone_config"] is not None:
__SCREAMING_SNAKE_CASE = self.backbone_config.to_dict()
__SCREAMING_SNAKE_CASE = self.__class__.model_type
return output
| 553 | 0 |
'''simple docstring'''
from __future__ import annotations
from random import choice
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE__ ):
return choice(_SCREAMING_SNAKE_CASE )
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
__a : str = random_pivot(_SCREAMING_SNAKE_CASE )
# partition based on pivot
# linear time
__a : List[Any] = [e for e in lst if e < pivot]
__a : Dict = [e for e in lst if e > pivot]
# if we get lucky, pivot might be the element we want.
# we can easily see this:
# small (elements smaller than k)
# + pivot (kth element)
# + big (elements larger than k)
if len(_SCREAMING_SNAKE_CASE ) == k - 1:
return pivot
# pivot is in elements bigger than k
elif len(_SCREAMING_SNAKE_CASE ) < k - 1:
return kth_number(_SCREAMING_SNAKE_CASE , k - len(_SCREAMING_SNAKE_CASE ) - 1 )
# pivot is in elements smaller than k
else:
return kth_number(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 597 |
'''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
snake_case_ = logging.get_logger(__name__)
snake_case_ = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""}
snake_case_ = {
"""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"""
),
},
}
snake_case_ = {
"""roberta-base""": 512,
"""roberta-large""": 512,
"""roberta-large-mnli""": 512,
"""distilroberta-base""": 512,
"""roberta-base-openai-detector""": 512,
"""roberta-large-openai-detector""": 512,
}
class a__ ( _lowercase ):
__magic_name__ : Any = VOCAB_FILES_NAMES
__magic_name__ : Any = PRETRAINED_VOCAB_FILES_MAP
__magic_name__ : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__magic_name__ : Dict = ["input_ids", "attention_mask"]
__magic_name__ : Tuple = RobertaTokenizer
def __init__(self : Optional[Any], __UpperCAmelCase : Dict=None, __UpperCAmelCase : Tuple=None, __UpperCAmelCase : Tuple=None, __UpperCAmelCase : Any="replace", __UpperCAmelCase : Dict="<s>", __UpperCAmelCase : List[Any]="</s>", __UpperCAmelCase : Union[str, Any]="</s>", __UpperCAmelCase : int="<s>", __UpperCAmelCase : Optional[Any]="<unk>", __UpperCAmelCase : Tuple="<pad>", __UpperCAmelCase : Union[str, Any]="<mask>", __UpperCAmelCase : Any=False, __UpperCAmelCase : Optional[int]=True, **__UpperCAmelCase : Optional[Any], ) -> Tuple:
"""simple docstring"""
super().__init__(
__UpperCAmelCase, __UpperCAmelCase, tokenizer_file=__UpperCAmelCase, errors=__UpperCAmelCase, bos_token=__UpperCAmelCase, eos_token=__UpperCAmelCase, sep_token=__UpperCAmelCase, cls_token=__UpperCAmelCase, unk_token=__UpperCAmelCase, pad_token=__UpperCAmelCase, mask_token=__UpperCAmelCase, add_prefix_space=__UpperCAmelCase, trim_offsets=__UpperCAmelCase, **__UpperCAmelCase, )
SCREAMING_SNAKE_CASE : Optional[Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
if pre_tok_state.get('''add_prefix_space''', __UpperCAmelCase ) != add_prefix_space:
SCREAMING_SNAKE_CASE : str = getattr(__UpperCAmelCase, pre_tok_state.pop('''type''' ) )
SCREAMING_SNAKE_CASE : Dict = add_prefix_space
SCREAMING_SNAKE_CASE : Optional[int] = pre_tok_class(**__UpperCAmelCase )
SCREAMING_SNAKE_CASE : Any = add_prefix_space
SCREAMING_SNAKE_CASE : Optional[int] = '''post_processor'''
SCREAMING_SNAKE_CASE : Any = getattr(self.backend_tokenizer, __UpperCAmelCase, __UpperCAmelCase )
if tokenizer_component_instance:
SCREAMING_SNAKE_CASE : Union[str, Any] = 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:
SCREAMING_SNAKE_CASE : Optional[Any] = tuple(state['''sep'''] )
if "cls" in state:
SCREAMING_SNAKE_CASE : Tuple = tuple(state['''cls'''] )
SCREAMING_SNAKE_CASE : str = False
if state.get('''add_prefix_space''', __UpperCAmelCase ) != add_prefix_space:
SCREAMING_SNAKE_CASE : int = add_prefix_space
SCREAMING_SNAKE_CASE : List[str] = True
if state.get('''trim_offsets''', __UpperCAmelCase ) != trim_offsets:
SCREAMING_SNAKE_CASE : Any = trim_offsets
SCREAMING_SNAKE_CASE : Dict = True
if changes_to_apply:
SCREAMING_SNAKE_CASE : Tuple = getattr(__UpperCAmelCase, state.pop('''type''' ) )
SCREAMING_SNAKE_CASE : List[Any] = component_class(**__UpperCAmelCase )
setattr(self.backend_tokenizer, __UpperCAmelCase, __UpperCAmelCase )
@property
def lowercase__ (self : int ) -> 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 lowercase__ (self : int, __UpperCAmelCase : List[str] ) -> Tuple:
"""simple docstring"""
SCREAMING_SNAKE_CASE : str = AddedToken(__UpperCAmelCase, lstrip=__UpperCAmelCase, rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase, __UpperCAmelCase ) else value
SCREAMING_SNAKE_CASE : List[str] = value
def lowercase__ (self : Optional[int], *__UpperCAmelCase : List[Any], **__UpperCAmelCase : Optional[Any] ) -> BatchEncoding:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Any = kwargs.get('''is_split_into_words''', __UpperCAmelCase )
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(*__UpperCAmelCase, **__UpperCAmelCase )
def lowercase__ (self : int, *__UpperCAmelCase : List[str], **__UpperCAmelCase : Tuple ) -> BatchEncoding:
"""simple docstring"""
SCREAMING_SNAKE_CASE : str = kwargs.get('''is_split_into_words''', __UpperCAmelCase )
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(*__UpperCAmelCase, **__UpperCAmelCase )
def lowercase__ (self : Optional[Any], __UpperCAmelCase : str, __UpperCAmelCase : Optional[str] = None ) -> Tuple[str]:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Any = self._tokenizer.model.save(__UpperCAmelCase, name=__UpperCAmelCase )
return tuple(__UpperCAmelCase )
def lowercase__ (self : Optional[int], __UpperCAmelCase : Dict, __UpperCAmelCase : List[str]=None ) -> Optional[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE : List[Any] = [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 : Union[str, Any], __UpperCAmelCase : List[int], __UpperCAmelCase : Optional[List[int]] = None ) -> List[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Union[str, Any] = [self.sep_token_id]
SCREAMING_SNAKE_CASE : int = [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]
| 507 | 0 |
def a_ ( ):
__lowerCAmelCase = 0
for i in range(1, 1001 ):
total += i**i
return str(lowerCAmelCase_ )[-10:]
if __name__ == "__main__":
print(solution())
| 421 |
def a_ ( lowerCAmelCase_ : str, lowerCAmelCase_ : str ):
if not (isinstance(lowerCAmelCase_, lowerCAmelCase_ ) and isinstance(lowerCAmelCase_, lowerCAmelCase_ )):
raise ValueError('longest_common_substring() takes two strings for inputs' )
__lowerCAmelCase = len(lowerCAmelCase_ )
__lowerCAmelCase = len(lowerCAmelCase_ )
__lowerCAmelCase = [[0] * (texta_length + 1) for _ in range(texta_length + 1 )]
__lowerCAmelCase = 0
__lowerCAmelCase = 0
for i in range(1, texta_length + 1 ):
for j in range(1, texta_length + 1 ):
if texta[i - 1] == texta[j - 1]:
__lowerCAmelCase = 1 + dp[i - 1][j - 1]
if dp[i][j] > ans_length:
__lowerCAmelCase = i
__lowerCAmelCase = dp[i][j]
return texta[ans_index - ans_length : ans_index]
if __name__ == "__main__":
import doctest
doctest.testmod()
| 421 | 1 |
import copy
from typing import Any, Dict, List, Optional, Union
import numpy as np
from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging
a__ = logging.get_logger(__name__)
class snake_case ( SCREAMING_SNAKE_CASE_ ):
'''simple docstring'''
snake_case_ : str = ["""input_features"""]
def __init__( self : Optional[Any] , lowerCAmelCase : Union[str, Any]=80 , lowerCAmelCase : List[str]=1_6000 , lowerCAmelCase : str=160 , lowerCAmelCase : Optional[int]=30 , lowerCAmelCase : Optional[int]=400 , lowerCAmelCase : Optional[Any]=0.0 , lowerCAmelCase : List[str]=False , **lowerCAmelCase : int , ) -> Optional[int]:
"""simple docstring"""
super().__init__(
feature_size=lowerCAmelCase , sampling_rate=lowerCAmelCase , padding_value=lowerCAmelCase , return_attention_mask=lowerCAmelCase , **lowerCAmelCase , )
_snake_case : Any = n_fft
_snake_case : Any = hop_length
_snake_case : Any = chunk_length
_snake_case : int = chunk_length * sampling_rate
_snake_case : Dict = self.n_samples // hop_length
_snake_case : Any = sampling_rate
_snake_case : Optional[int] = mel_filter_bank(
num_frequency_bins=1 + n_fft // 2 , num_mel_filters=lowerCAmelCase , min_frequency=0.0 , max_frequency=8_000.0 , sampling_rate=lowerCAmelCase , norm="""slaney""" , mel_scale="""slaney""" , )
def UpperCamelCase_ ( self : List[str] , lowerCAmelCase : np.array) -> np.ndarray:
"""simple docstring"""
_snake_case : Optional[Any] = spectrogram(
lowerCAmelCase , window_function(self.n_fft , """hann""") , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters , log_mel="""log10""" , )
_snake_case : List[Any] = log_spec[:, :-1]
_snake_case : Dict = np.maximum(lowerCAmelCase , log_spec.max() - 8.0)
_snake_case : List[Any] = (log_spec + 4.0) / 4.0
return log_spec
@staticmethod
# Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
def UpperCamelCase_ ( lowerCAmelCase : List[np.ndarray] , lowerCAmelCase : List[np.ndarray] , lowerCAmelCase : float = 0.0) -> List[np.ndarray]:
"""simple docstring"""
if attention_mask is not None:
_snake_case : Any = np.array(lowerCAmelCase , np.intaa)
_snake_case : Optional[Any] = []
for vector, length in zip(lowerCAmelCase , attention_mask.sum(-1)):
_snake_case : Optional[int] = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7)
if length < normed_slice.shape[0]:
_snake_case : List[str] = padding_value
normed_input_values.append(lowerCAmelCase)
else:
_snake_case : int = [(x - x.mean()) / np.sqrt(x.var() + 1E-7) for x in input_values]
return normed_input_values
def __call__( self : Tuple , lowerCAmelCase : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , lowerCAmelCase : bool = True , lowerCAmelCase : Optional[int] = None , lowerCAmelCase : Optional[Union[str, TensorType]] = None , lowerCAmelCase : Optional[bool] = None , lowerCAmelCase : Optional[str] = "max_length" , lowerCAmelCase : Optional[int] = None , lowerCAmelCase : Optional[int] = None , lowerCAmelCase : Optional[bool] = None , **lowerCAmelCase : Dict , ) -> BatchFeature:
"""simple docstring"""
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
F'''The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a'''
F''' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input'''
F''' was sampled with {self.sampling_rate} and not {sampling_rate}.''')
else:
logger.warning(
"""It is strongly recommended to pass the `sampling_rate` argument to this function. """
"""Failing to do so can result in silent errors that might be hard to debug.""")
_snake_case : Any = isinstance(lowerCAmelCase , 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 : Tuple = is_batched_numpy or (
isinstance(lowerCAmelCase , (list, tuple)) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list)))
)
if is_batched:
_snake_case : List[str] = [np.asarray([speech] , dtype=np.floataa).T for speech in raw_speech]
elif not is_batched and not isinstance(lowerCAmelCase , np.ndarray):
_snake_case : Any = np.asarray(lowerCAmelCase , dtype=np.floataa)
elif isinstance(lowerCAmelCase , np.ndarray) and raw_speech.dtype is np.dtype(np.floataa):
_snake_case : str = raw_speech.astype(np.floataa)
# always return batch
if not is_batched:
_snake_case : Dict = [np.asarray([raw_speech]).T]
_snake_case : List[Any] = BatchFeature({"""input_features""": raw_speech})
# convert into correct format for padding
_snake_case : int = self.pad(
lowerCAmelCase , padding=lowerCAmelCase , max_length=max_length if max_length else self.n_samples , truncation=lowerCAmelCase , pad_to_multiple_of=lowerCAmelCase , return_attention_mask=return_attention_mask or do_normalize , )
# zero-mean and unit-variance normalization
if do_normalize:
_snake_case : Any = self.zero_mean_unit_var_norm(
padded_inputs["""input_features"""] , attention_mask=padded_inputs["""attention_mask"""] , padding_value=self.padding_value , )
_snake_case : List[Any] = np.stack(padded_inputs["""input_features"""] , axis=0)
# make sure list is in array format
_snake_case : List[Any] = padded_inputs.get("""input_features""").transpose(2 , 0 , 1)
_snake_case : List[str] = [self._np_extract_fbank_features(lowerCAmelCase) for waveform in input_features[0]]
if isinstance(input_features[0] , lowerCAmelCase):
_snake_case : Union[str, Any] = [np.asarray(lowerCAmelCase , dtype=np.floataa) for feature in input_features]
else:
_snake_case : Union[str, Any] = input_features
if return_attention_mask:
# rescale from sample (48000) to feature (3000)
_snake_case : List[Any] = padded_inputs["""attention_mask"""][:, :: self.hop_length]
if return_tensors is not None:
_snake_case : List[Any] = padded_inputs.convert_to_tensors(lowerCAmelCase)
return padded_inputs
def UpperCamelCase_ ( self : List[Any]) -> Dict[str, Any]:
"""simple docstring"""
_snake_case : List[str] = copy.deepcopy(self.__dict__)
_snake_case : int = self.__class__.__name__
if "mel_filters" in output:
del output["mel_filters"]
return output
| 477 |
from __future__ import annotations
import inspect
import unittest
from math import floor
import numpy as np
from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TFCvtForImageClassification, TFCvtModel
from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class snake_case ( SCREAMING_SNAKE_CASE_ ):
'''simple docstring'''
def UpperCamelCase_ ( self : List[str]) -> Dict:
"""simple docstring"""
_snake_case : List[Any] = self.config_class(**self.inputs_dict)
self.parent.assertTrue(hasattr(lowerCAmelCase , """embed_dim"""))
self.parent.assertTrue(hasattr(lowerCAmelCase , """num_heads"""))
class snake_case :
'''simple docstring'''
def __init__( self : int , lowerCAmelCase : Optional[int] , lowerCAmelCase : Tuple=13 , lowerCAmelCase : Union[str, Any]=64 , lowerCAmelCase : Optional[Any]=3 , lowerCAmelCase : int=[16, 48, 96] , lowerCAmelCase : List[Any]=[1, 3, 6] , lowerCAmelCase : str=[1, 2, 10] , lowerCAmelCase : int=[7, 3, 3] , lowerCAmelCase : Union[str, Any]=[4, 2, 2] , lowerCAmelCase : List[Any]=[2, 1, 1] , lowerCAmelCase : Optional[Any]=[2, 2, 2] , lowerCAmelCase : str=[False, False, True] , lowerCAmelCase : str=[0.0, 0.0, 0.0] , lowerCAmelCase : Dict=0.02 , lowerCAmelCase : int=1E-12 , lowerCAmelCase : Tuple=True , lowerCAmelCase : int=True , lowerCAmelCase : int=2 , ) -> Tuple:
"""simple docstring"""
_snake_case : Optional[int] = parent
_snake_case : List[str] = batch_size
_snake_case : int = image_size
_snake_case : Tuple = patch_sizes
_snake_case : Dict = patch_stride
_snake_case : Dict = patch_padding
_snake_case : Any = is_training
_snake_case : int = use_labels
_snake_case : List[str] = num_labels
_snake_case : Dict = num_channels
_snake_case : int = embed_dim
_snake_case : str = num_heads
_snake_case : Union[str, Any] = stride_kv
_snake_case : Optional[Any] = depth
_snake_case : List[str] = cls_token
_snake_case : Optional[Any] = attention_drop_rate
_snake_case : List[Any] = initializer_range
_snake_case : str = layer_norm_eps
def UpperCamelCase_ ( self : Any) -> Optional[int]:
"""simple docstring"""
_snake_case : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
_snake_case : Optional[int] = None
if self.use_labels:
# create a random int32 tensor of given shape
_snake_case : Any = ids_tensor([self.batch_size] , self.num_labels)
_snake_case : Union[str, Any] = self.get_config()
return config, pixel_values, labels
def UpperCamelCase_ ( self : Optional[Any]) -> Tuple:
"""simple docstring"""
return CvtConfig(
image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , )
def UpperCamelCase_ ( self : Tuple , lowerCAmelCase : List[str] , lowerCAmelCase : str , lowerCAmelCase : List[Any]) -> List[str]:
"""simple docstring"""
_snake_case : Any = TFCvtModel(config=lowerCAmelCase)
_snake_case : int = model(lowerCAmelCase , training=lowerCAmelCase)
_snake_case : int = (self.image_size, self.image_size)
_snake_case , _snake_case : Dict = image_size[0], image_size[1]
for i in range(len(self.depth)):
_snake_case : Dict = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1)
_snake_case : int = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width))
def UpperCamelCase_ ( self : Union[str, Any] , lowerCAmelCase : List[str] , lowerCAmelCase : List[Any] , lowerCAmelCase : Union[str, Any]) -> Optional[int]:
"""simple docstring"""
_snake_case : int = self.num_labels
_snake_case : List[str] = TFCvtForImageClassification(lowerCAmelCase)
_snake_case : Dict = model(lowerCAmelCase , labels=lowerCAmelCase , training=lowerCAmelCase)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels))
def UpperCamelCase_ ( self : str) -> List[Any]:
"""simple docstring"""
_snake_case : Optional[Any] = self.prepare_config_and_inputs()
_snake_case , _snake_case , _snake_case : Any = config_and_inputs
_snake_case : Optional[Any] = {"""pixel_values""": pixel_values}
return config, inputs_dict
@require_tf
class snake_case ( SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,unittest.TestCase ):
'''simple docstring'''
snake_case_ : Dict = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
snake_case_ : int = (
{"""feature-extraction""": TFCvtModel, """image-classification""": TFCvtForImageClassification}
if is_tf_available()
else {}
)
snake_case_ : Tuple = False
snake_case_ : Union[str, Any] = False
snake_case_ : Dict = False
snake_case_ : str = False
snake_case_ : Optional[Any] = False
def UpperCamelCase_ ( self : Any) -> List[str]:
"""simple docstring"""
_snake_case : int = TFCvtModelTester(self)
_snake_case : Dict = TFCvtConfigTester(self , config_class=lowerCAmelCase , has_text_modality=lowerCAmelCase , hidden_size=37)
def UpperCamelCase_ ( self : Dict) -> Tuple:
"""simple docstring"""
self.config_tester.create_and_test_config_common_properties()
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
@unittest.skip(reason="""Cvt does not output attentions""")
def UpperCamelCase_ ( self : Dict) -> Optional[Any]:
"""simple docstring"""
pass
@unittest.skip(reason="""Cvt does not use inputs_embeds""")
def UpperCamelCase_ ( self : List[str]) -> Optional[int]:
"""simple docstring"""
pass
@unittest.skip(reason="""Cvt does not support input and output embeddings""")
def UpperCamelCase_ ( self : Tuple) -> str:
"""simple docstring"""
pass
@unittest.skipIf(
not is_tf_available() or len(tf.config.list_physical_devices("""GPU""")) == 0 , reason="""TF does not support backprop for grouped convolutions on CPU.""" , )
def UpperCamelCase_ ( self : Optional[Any]) -> int:
"""simple docstring"""
super().test_dataset_conversion()
@unittest.skipIf(
not is_tf_available() or len(tf.config.list_physical_devices("""GPU""")) == 0 , reason="""TF does not support backprop for grouped convolutions on CPU.""" , )
@slow
def UpperCamelCase_ ( self : Tuple) -> List[str]:
"""simple docstring"""
super().test_keras_fit()
@unittest.skip(reason="""Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8""")
def UpperCamelCase_ ( self : int) -> Dict:
"""simple docstring"""
_snake_case : List[str] = tf.keras.mixed_precision.Policy("""mixed_float16""")
tf.keras.mixed_precision.set_global_policy(lowerCAmelCase)
super().test_keras_fit()
tf.keras.mixed_precision.set_global_policy("""float32""")
def UpperCamelCase_ ( self : Dict) -> List[str]:
"""simple docstring"""
_snake_case , _snake_case : List[str] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_snake_case : Optional[Any] = model_class(lowerCAmelCase)
_snake_case : Tuple = inspect.signature(model.call)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_snake_case : int = [*signature.parameters.keys()]
_snake_case : List[str] = ["""pixel_values"""]
self.assertListEqual(arg_names[:1] , lowerCAmelCase)
def UpperCamelCase_ ( self : Optional[Any]) -> Dict:
"""simple docstring"""
def check_hidden_states_output(lowerCAmelCase : Optional[int] , lowerCAmelCase : Any , lowerCAmelCase : Any):
_snake_case : int = model_class(lowerCAmelCase)
_snake_case : str = model(**self._prepare_for_class(lowerCAmelCase , lowerCAmelCase))
_snake_case : Dict = outputs.hidden_states
_snake_case : Any = len(self.model_tester.depth)
self.assertEqual(len(lowerCAmelCase) , lowerCAmelCase)
# verify the first hidden states (first block)
self.assertListEqual(
list(hidden_states[0].shape[-3:]) , [
self.model_tester.embed_dim[0],
self.model_tester.image_size // 4,
self.model_tester.image_size // 4,
] , )
_snake_case , _snake_case : List[str] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_snake_case : Tuple = True
check_hidden_states_output(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase)
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
_snake_case : Optional[int] = True
check_hidden_states_output(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase)
def UpperCamelCase_ ( self : Dict) -> Any:
"""simple docstring"""
_snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCAmelCase)
def UpperCamelCase_ ( self : Union[str, Any]) -> Union[str, Any]:
"""simple docstring"""
_snake_case : int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase)
@slow
def UpperCamelCase_ ( self : Union[str, Any]) -> Dict:
"""simple docstring"""
for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_snake_case : Dict = TFCvtModel.from_pretrained(lowerCAmelCase)
self.assertIsNotNone(lowerCAmelCase)
def lowercase ( ) -> Any:
_snake_case : Any = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
return image
@require_tf
@require_vision
class snake_case ( unittest.TestCase ):
'''simple docstring'''
@cached_property
def UpperCamelCase_ ( self : Union[str, Any]) -> Union[str, Any]:
"""simple docstring"""
return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0])
@slow
def UpperCamelCase_ ( self : List[str]) -> Tuple:
"""simple docstring"""
_snake_case : List[str] = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0])
_snake_case : Dict = self.default_image_processor
_snake_case : int = prepare_img()
_snake_case : Union[str, Any] = image_processor(images=lowerCAmelCase , return_tensors="""tf""")
# forward pass
_snake_case : int = model(**lowerCAmelCase)
# verify the logits
_snake_case : Optional[int] = tf.TensorShape((1, 1000))
self.assertEqual(outputs.logits.shape , lowerCAmelCase)
_snake_case : int = tf.constant([0.9_285, 0.9_015, -0.3_150])
self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , lowerCAmelCase , atol=1E-4))
| 477 | 1 |
"""simple docstring"""
def __lowerCAmelCase( ):
"""simple docstring"""
return 1
def __lowerCAmelCase( __UpperCAmelCase ):
"""simple docstring"""
return 0 if x < 0 else two_pence(x - 2 ) + one_pence()
def __lowerCAmelCase( __UpperCAmelCase ):
"""simple docstring"""
return 0 if x < 0 else five_pence(x - 5 ) + two_pence(__UpperCAmelCase )
def __lowerCAmelCase( __UpperCAmelCase ):
"""simple docstring"""
return 0 if x < 0 else ten_pence(x - 10 ) + five_pence(__UpperCAmelCase )
def __lowerCAmelCase( __UpperCAmelCase ):
"""simple docstring"""
return 0 if x < 0 else twenty_pence(x - 20 ) + ten_pence(__UpperCAmelCase )
def __lowerCAmelCase( __UpperCAmelCase ):
"""simple docstring"""
return 0 if x < 0 else fifty_pence(x - 50 ) + twenty_pence(__UpperCAmelCase )
def __lowerCAmelCase( __UpperCAmelCase ):
"""simple docstring"""
return 0 if x < 0 else one_pound(x - 100 ) + fifty_pence(__UpperCAmelCase )
def __lowerCAmelCase( __UpperCAmelCase ):
"""simple docstring"""
return 0 if x < 0 else two_pound(x - 200 ) + one_pound(__UpperCAmelCase )
def __lowerCAmelCase( __UpperCAmelCase = 200 ):
"""simple docstring"""
return two_pound(__UpperCAmelCase )
if __name__ == "__main__":
print(solution(int(input().strip())))
| 283 | """simple docstring"""
def __lowerCAmelCase( __UpperCAmelCase ):
"""simple docstring"""
_lowercase : str = [0 for i in range(len(__UpperCAmelCase ) )]
# initialize interval's left pointer and right pointer
_lowercase , _lowercase : str = 0, 0
for i in range(1 ,len(__UpperCAmelCase ) ):
# case when current index is inside the interval
if i <= right_pointer:
_lowercase : Union[str, Any] = min(right_pointer - i + 1 ,z_result[i - left_pointer] )
_lowercase : Any = min_edge
while go_next(__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ):
z_result[i] += 1
# if new index's result gives us more right interval,
# we've to update left_pointer and right_pointer
if i + z_result[i] - 1 > right_pointer:
_lowercase , _lowercase : Optional[int] = i, i + z_result[i] - 1
return z_result
def __lowerCAmelCase( __UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ):
"""simple docstring"""
return i + z_result[i] < len(__UpperCAmelCase ) and s[z_result[i]] == s[i + z_result[i]]
def __lowerCAmelCase( __UpperCAmelCase ,__UpperCAmelCase ):
"""simple docstring"""
_lowercase : Union[str, Any] = 0
# concatenate 'pattern' and 'input_str' and call z_function
# with concatenated string
_lowercase : List[str] = z_function(pattern + input_str )
for val in z_result:
# if value is greater then length of the pattern string
# that means this index is starting position of substring
# which is equal to pattern string
if val >= len(__UpperCAmelCase ):
answer += 1
return answer
if __name__ == "__main__":
import doctest
doctest.testmod()
| 283 | 1 |
import warnings
from ...utils import logging
from .image_processing_flava import FlavaImageProcessor
lowercase__ : Dict = logging.get_logger(__name__)
class UpperCAmelCase ( lowerCAmelCase_ ):
'''simple docstring'''
def __init__( self : Optional[int] , *__lowercase : List[Any] , **__lowercase : Optional[int] ):
"""simple docstring"""
warnings.warn(
"The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"
" use FlavaImageProcessor instead." , __lowerCAmelCase , )
super().__init__(*__lowerCAmelCase , **__lowerCAmelCase )
| 376 | """simple docstring"""
from __future__ import annotations
from numpy import array, cos, cross, floataa, radians, sin
from numpy.typing import NDArray
def __UpperCAmelCase ( lowercase ,lowercase ,lowercase = False ):
"""simple docstring"""
if radian_mode:
return [magnitude * cos(lowercase ), magnitude * sin(lowercase )]
return [magnitude * cos(radians(lowercase ) ), magnitude * sin(radians(lowercase ) )]
def __UpperCAmelCase ( lowercase ,lowercase ,lowercase = 10**-1 ):
"""simple docstring"""
_UpperCAmelCase = cross(lowercase ,lowercase )
_UpperCAmelCase = sum(lowercase )
return abs(lowercase ) < eps
if __name__ == "__main__":
# Test to check if it works
UpperCAmelCase__ = array(
[
polar_force(718.4, 1_8_0 - 3_0),
polar_force(879.54, 4_5),
polar_force(1_0_0, -9_0),
]
)
UpperCAmelCase__ = array([[0, 0], [0, 0], [0, 0]])
assert in_static_equilibrium(forces, location)
# Problem 1 in image_data/2D_problems.jpg
UpperCAmelCase__ = array(
[
polar_force(3_0 * 9.81, 1_5),
polar_force(2_1_5, 1_8_0 - 4_5),
polar_force(2_6_4, 9_0 - 3_0),
]
)
UpperCAmelCase__ = array([[0, 0], [0, 0], [0, 0]])
assert in_static_equilibrium(forces, location)
# Problem in image_data/2D_problems_1.jpg
UpperCAmelCase__ = array([[0, -2_0_0_0], [0, -1_2_0_0], [0, 1_5_6_0_0], [0, -1_2_4_0_0]])
UpperCAmelCase__ = array([[0, 0], [6, 0], [1_0, 0], [1_2, 0]])
assert in_static_equilibrium(forces, location)
import doctest
doctest.testmod()
| 277 | 0 |
'''simple docstring'''
import re
import time
from typing import Optional
import IPython.display as disp
from ..trainer_callback import TrainerCallback
from ..trainer_utils import IntervalStrategy, has_length
def _lowerCAmelCase (_lowercase ):
a__ = int(_lowercase )
a__ , a__ , a__ = t // 36_00, (t // 60) % 60, t % 60
return F'{h}:{m:02d}:{s:02d}' if h != 0 else F'{m:02d}:{s:02d}'
def _lowerCAmelCase (_lowercase , _lowercase , _lowercase , _lowercase , _lowercase=3_00 ):
return F'\n <div>\n {prefix}\n <progress value=\'{value}\' max=\'{total}\' style=\'width:{width}px; height:20px; vertical-align: middle;\'></progress>\n {label}\n </div>\n '
def _lowerCAmelCase (_lowercase ):
a__ = "<table border=\"1\" class=\"dataframe\">\n"
html_code += """ <thead>\n <tr style="text-align: left;">\n"""
for i in items[0]:
html_code += F' <th>{i}</th>\n'
html_code += " </tr>\n </thead>\n <tbody>\n"
for line in items[1:]:
html_code += " <tr>\n"
for elt in line:
a__ = F'{elt:.6f}' if isinstance(_lowercase , _lowercase ) else str(_lowercase )
html_code += F' <td>{elt}</td>\n'
html_code += " </tr>\n"
html_code += " </tbody>\n</table><p>"
return html_code
class lowerCamelCase__ :
"""simple docstring"""
UpperCamelCase__ = 5
UpperCamelCase__ = 0.2
def __init__( self : str ,a__ : int ,a__ : Optional[str] = None ,a__ : bool = True ,a__ : Optional["NotebookTrainingTracker"] = None ,a__ : int = 3_00 ,):
a__ = total
a__ = "" if prefix is None else prefix
a__ = leave
a__ = parent
a__ = width
a__ = None
a__ = None
a__ = None
def lowerCAmelCase_ ( self : int ,a__ : int ,a__ : bool = False ,a__ : str = None ):
a__ = value
if comment is not None:
a__ = comment
if self.last_value is None:
a__ = a__ = time.time()
a__ = a__ = value
a__ = a__ = None
a__ = self.warmup
a__ = 1
self.update_bar(a__ )
elif value <= self.last_value and not force_update:
return
elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for ,self.total ):
if self.first_calls > 0:
self.first_calls -= 1
a__ = time.time()
a__ = current_time - self.start_time
# We could have value = self.start_value if the update is called twixe with the same start value.
if value > self.start_value:
a__ = self.elapsed_time / (value - self.start_value)
else:
a__ = None
if value >= self.total:
a__ = self.total
a__ = None
if not self.leave:
self.close()
elif self.average_time_per_item is not None:
a__ = self.average_time_per_item * (self.total - value)
self.update_bar(a__ )
a__ = value
a__ = current_time
if self.average_time_per_item is None:
a__ = 1
else:
a__ = max(int(self.update_every / self.average_time_per_item ) ,1 )
def lowerCAmelCase_ ( self : str ,a__ : List[str] ,a__ : List[str]=None ):
a__ = " " * (len(str(self.total ) ) - len(str(a__ ) )) + str(a__ )
if self.elapsed_time is None:
a__ = f'[{spaced_value}/{self.total} : < :'
elif self.predicted_remaining is None:
a__ = f'[{spaced_value}/{self.total} {format_time(self.elapsed_time )}'
else:
a__ = (
f'[{spaced_value}/{self.total} {format_time(self.elapsed_time )} <'
f' {format_time(self.predicted_remaining )}'
)
self.label += f', {1/self.average_time_per_item:.2f} it/s'
self.label += "]" if self.comment is None or len(self.comment ) == 0 else f', {self.comment}]'
self.display()
def lowerCAmelCase_ ( self : int ):
a__ = html_progress_bar(self.value ,self.total ,self.prefix ,self.label ,self.width )
if self.parent is not None:
# If this is a child bar, the parent will take care of the display.
self.parent.display()
return
if self.output is None:
a__ = disp.display(disp.HTML(self.html_code ) ,display_id=a__ )
else:
self.output.update(disp.HTML(self.html_code ) )
def lowerCAmelCase_ ( self : Any ):
if self.parent is None and self.output is not None:
self.output.update(disp.HTML("" ) )
class lowerCamelCase__ ( __lowerCamelCase ):
"""simple docstring"""
def __init__( self : Any ,a__ : Optional[int] ,a__ : Dict=None ):
super().__init__(a__ )
a__ = None if column_names is None else [column_names]
a__ = None
def lowerCAmelCase_ ( self : List[str] ):
a__ = html_progress_bar(self.value ,self.total ,self.prefix ,self.label ,self.width )
if self.inner_table is not None:
self.html_code += text_to_html_table(self.inner_table )
if self.child_bar is not None:
self.html_code += self.child_bar.html_code
if self.output is None:
a__ = disp.display(disp.HTML(self.html_code ) ,display_id=a__ )
else:
self.output.update(disp.HTML(self.html_code ) )
def lowerCAmelCase_ ( self : str ,a__ : Any ):
if self.inner_table is None:
a__ = [list(values.keys() ), list(values.values() )]
else:
a__ = self.inner_table[0]
if len(self.inner_table ) == 1:
# We give a chance to update the column names at the first iteration
for key in values.keys():
if key not in columns:
columns.append(a__ )
a__ = columns
self.inner_table.append([values[c] for c in columns] )
def lowerCAmelCase_ ( self : Optional[Any] ,a__ : Optional[Any] ,a__ : Any=None ,a__ : int=3_00 ):
a__ = NotebookProgressBar(a__ ,prefix=a__ ,parent=self ,width=a__ )
return self.child_bar
def lowerCAmelCase_ ( self : Dict ):
a__ = None
self.display()
class lowerCamelCase__ ( __lowerCamelCase ):
"""simple docstring"""
def __init__( self : List[Any] ):
a__ = None
a__ = None
a__ = False
def lowerCAmelCase_ ( self : List[str] ,a__ : Union[str, Any] ,a__ : Dict ,a__ : Tuple ,**a__ : Union[str, Any] ):
a__ = "Epoch" if args.evaluation_strategy == IntervalStrategy.EPOCH else "Step"
a__ = 0
a__ = 0
a__ = [self.first_column] + ["Training Loss"]
if args.evaluation_strategy != IntervalStrategy.NO:
column_names.append("Validation Loss" )
a__ = NotebookTrainingTracker(state.max_steps ,a__ )
def lowerCAmelCase_ ( self : int ,a__ : List[str] ,a__ : Tuple ,a__ : str ,**a__ : Optional[Any] ):
a__ = int(state.epoch ) if int(state.epoch ) == state.epoch else f'{state.epoch:.2f}'
self.training_tracker.update(
state.global_step + 1 ,comment=f'Epoch {epoch}/{state.num_train_epochs}' ,force_update=self._force_next_update ,)
a__ = False
def lowerCAmelCase_ ( self : Optional[Any] ,a__ : Dict ,a__ : Union[str, Any] ,a__ : Any ,a__ : Union[str, Any]=None ,**a__ : List[Any] ):
if not has_length(a__ ):
return
if self.prediction_bar is None:
if self.training_tracker is not None:
a__ = self.training_tracker.add_child(len(a__ ) )
else:
a__ = NotebookProgressBar(len(a__ ) )
self.prediction_bar.update(1 )
else:
self.prediction_bar.update(self.prediction_bar.value + 1 )
def lowerCAmelCase_ ( self : Union[str, Any] ,a__ : Any ,a__ : str ,a__ : Tuple ,**a__ : Any ):
if self.prediction_bar is not None:
self.prediction_bar.close()
a__ = None
def lowerCAmelCase_ ( self : Dict ,a__ : Tuple ,a__ : Dict ,a__ : str ,a__ : str=None ,**a__ : Tuple ):
# Only for when there is no evaluation
if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs:
a__ = {"Training Loss": logs["loss"]}
# First column is necessarily Step sine we're not in epoch eval strategy
a__ = state.global_step
self.training_tracker.write_line(a__ )
def lowerCAmelCase_ ( self : List[str] ,a__ : Optional[Any] ,a__ : Any ,a__ : str ,a__ : Tuple=None ,**a__ : Optional[int] ):
if self.training_tracker is not None:
a__ = {"Training Loss": "No log", "Validation Loss": "No log"}
for log in reversed(state.log_history ):
if "loss" in log:
a__ = log["loss"]
break
if self.first_column == "Epoch":
a__ = int(state.epoch )
else:
a__ = state.global_step
a__ = "eval"
for k in metrics:
if k.endswith("_loss" ):
a__ = re.sub(r"\_loss$" ,"" ,a__ )
a__ = metrics.pop("total_flos" ,a__ )
a__ = metrics.pop("epoch" ,a__ )
a__ = metrics.pop(f'{metric_key_prefix}_runtime' ,a__ )
a__ = metrics.pop(f'{metric_key_prefix}_samples_per_second' ,a__ )
a__ = metrics.pop(f'{metric_key_prefix}_steps_per_second' ,a__ )
a__ = metrics.pop(f'{metric_key_prefix}_jit_compilation_time' ,a__ )
for k, v in metrics.items():
if k == f'{metric_key_prefix}_loss':
a__ = v
else:
a__ = k.split("_" )
a__ = " ".join([part.capitalize() for part in splits[1:]] )
a__ = v
self.training_tracker.write_line(a__ )
self.training_tracker.remove_child()
a__ = None
# Evaluation takes a long time so we should force the next update.
a__ = True
def lowerCAmelCase_ ( self : Optional[Any] ,a__ : List[Any] ,a__ : Tuple ,a__ : List[Any] ,**a__ : Optional[int] ):
self.training_tracker.update(
state.global_step ,comment=f'Epoch {int(state.epoch )}/{state.num_train_epochs}' ,force_update=a__ )
a__ = None
| 710 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
UpperCamelCase_ : Tuple = {
"""configuration_xlm_roberta_xl""": [
"""XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP""",
"""XLMRobertaXLConfig""",
"""XLMRobertaXLOnnxConfig""",
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase_ : Optional[int] = [
"""XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""XLMRobertaXLForCausalLM""",
"""XLMRobertaXLForMaskedLM""",
"""XLMRobertaXLForMultipleChoice""",
"""XLMRobertaXLForQuestionAnswering""",
"""XLMRobertaXLForSequenceClassification""",
"""XLMRobertaXLForTokenClassification""",
"""XLMRobertaXLModel""",
"""XLMRobertaXLPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_xlm_roberta_xl import (
XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP,
XLMRobertaXLConfig,
XLMRobertaXLOnnxConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_xlm_roberta_xl import (
XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
XLMRobertaXLForCausalLM,
XLMRobertaXLForMaskedLM,
XLMRobertaXLForMultipleChoice,
XLMRobertaXLForQuestionAnswering,
XLMRobertaXLForSequenceClassification,
XLMRobertaXLForTokenClassification,
XLMRobertaXLModel,
XLMRobertaXLPreTrainedModel,
)
else:
import sys
UpperCamelCase_ : List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
| 394 | 0 |
import math
import time
from typing import Dict, List, Optional
from torch.utils.data import Dataset
from transformers import SeqaSeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics
if is_torch_tpu_available(check_device=False):
import torch_xla.core.xla_model as xm
import torch_xla.debug.metrics as met
class _snake_case ( _A ):
def __init__( self ,*UpperCamelCase ,UpperCamelCase=None ,UpperCamelCase=None ,**UpperCamelCase ) -> Optional[int]:
super().__init__(*UpperCamelCase ,**UpperCamelCase )
snake_case__ :Optional[Any] = eval_examples
snake_case__ :str = post_process_function
def lowerCAmelCase_ ( self ,UpperCamelCase = None ,UpperCamelCase=None ,UpperCamelCase = None ,UpperCamelCase = "eval" ,**UpperCamelCase ,) -> Dict[str, float]:
snake_case__ :Optional[Any] = gen_kwargs.copy()
snake_case__ :List[str] = (
gen_kwargs["max_length"] if gen_kwargs.get("max_length" ) is not None else self.args.generation_max_length
)
snake_case__ :Any = (
gen_kwargs["num_beams"] if gen_kwargs.get("num_beams" ) is not None else self.args.generation_num_beams
)
snake_case__ :int = gen_kwargs
snake_case__ :List[str] = self.eval_dataset if eval_dataset is None else eval_dataset
snake_case__ :int = self.get_eval_dataloader(UpperCamelCase )
snake_case__ :List[Any] = self.eval_examples if eval_examples is None else eval_examples
# Temporarily disable metric computation, we will do it in the loop here.
snake_case__ :Tuple = self.compute_metrics
snake_case__ :Tuple = None
snake_case__ :Tuple = time.time()
snake_case__ :List[str] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
try:
snake_case__ :Optional[int] = eval_loop(
UpperCamelCase ,description="Evaluation" ,prediction_loss_only=True if compute_metrics is None else None ,ignore_keys=UpperCamelCase ,metric_key_prefix=UpperCamelCase ,)
finally:
snake_case__ :Tuple = compute_metrics
snake_case__ :int = self.args.eval_batch_size * self.args.world_size
if f'{metric_key_prefix}_jit_compilation_time' in output.metrics:
start_time += output.metrics[f'{metric_key_prefix}_jit_compilation_time']
output.metrics.update(
speed_metrics(
UpperCamelCase ,UpperCamelCase ,num_samples=output.num_samples ,num_steps=math.ceil(output.num_samples / total_batch_size ) ,) )
if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
# Only the main node write the results by default
snake_case__ :Optional[Any] = self.post_process_function(UpperCamelCase ,UpperCamelCase ,UpperCamelCase )
snake_case__ :str = self.compute_metrics(UpperCamelCase )
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys() ):
if not key.startswith(f'{metric_key_prefix}_' ):
snake_case__ :int = metrics.pop(UpperCamelCase )
metrics.update(output.metrics )
else:
snake_case__ :Optional[Any] = output.metrics
if self.args.should_log:
# Only the main node log the results by default
self.log(UpperCamelCase )
if self.args.tpu_metrics_debug or self.args.debug:
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report() )
snake_case__ :int = self.callback_handler.on_evaluate(self.args ,self.state ,self.control ,UpperCamelCase )
return metrics
def lowerCAmelCase_ ( self ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase=None ,UpperCamelCase = "test" ,**UpperCamelCase ) -> Any:
snake_case__ :int = gen_kwargs.copy()
snake_case__ :List[str] = self.get_test_dataloader(UpperCamelCase )
# Temporarily disable metric computation, we will do it in the loop here.
snake_case__ :Optional[Any] = self.compute_metrics
snake_case__ :Optional[Any] = None
snake_case__ :Union[str, Any] = time.time()
snake_case__ :Dict = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
try:
snake_case__ :Optional[int] = eval_loop(
UpperCamelCase ,description="Prediction" ,prediction_loss_only=True if compute_metrics is None else None ,ignore_keys=UpperCamelCase ,metric_key_prefix=UpperCamelCase ,)
finally:
snake_case__ :str = compute_metrics
snake_case__ :int = self.args.eval_batch_size * self.args.world_size
if f'{metric_key_prefix}_jit_compilation_time' in output.metrics:
start_time += output.metrics[f'{metric_key_prefix}_jit_compilation_time']
output.metrics.update(
speed_metrics(
UpperCamelCase ,UpperCamelCase ,num_samples=output.num_samples ,num_steps=math.ceil(output.num_samples / total_batch_size ) ,) )
if self.post_process_function is None or self.compute_metrics is None:
return output
snake_case__ :Any = self.post_process_function(UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,"predict" )
snake_case__ :Dict = self.compute_metrics(UpperCamelCase )
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys() ):
if not key.startswith(f'{metric_key_prefix}_' ):
snake_case__ :Any = metrics.pop(UpperCamelCase )
metrics.update(output.metrics )
return PredictionOutput(predictions=predictions.predictions ,label_ids=predictions.label_ids ,metrics=UpperCamelCase ) | 241 |
import unittest
import numpy as np
import torch
from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device
from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
class _snake_case ( _A , unittest.TestCase ):
_A = DDIMPipeline
_A = UNCONDITIONAL_IMAGE_GENERATION_PARAMS
_A = PipelineTesterMixin.required_optional_params - {
'num_images_per_prompt',
'latents',
'callback',
'callback_steps',
}
_A = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS
_A = False
def lowerCAmelCase_ ( self ) -> Any:
torch.manual_seed(0 )
snake_case__ :List[str] = 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") ,)
snake_case__ :int = DDIMScheduler()
snake_case__ :List[Any] = {"unet": unet, "scheduler": scheduler}
return components
def lowerCAmelCase_ ( self ,UpperCamelCase ,UpperCamelCase=0 ) -> Optional[Any]:
if str(UpperCamelCase ).startswith("mps" ):
snake_case__ :Dict = torch.manual_seed(UpperCamelCase )
else:
snake_case__ :Union[str, Any] = torch.Generator(device=UpperCamelCase ).manual_seed(UpperCamelCase )
snake_case__ :List[str] = {
"batch_size": 1,
"generator": generator,
"num_inference_steps": 2,
"output_type": "numpy",
}
return inputs
def lowerCAmelCase_ ( self ) -> int:
snake_case__ :Tuple = "cpu"
snake_case__ :int = self.get_dummy_components()
snake_case__ :str = self.pipeline_class(**UpperCamelCase )
pipe.to(UpperCamelCase )
pipe.set_progress_bar_config(disable=UpperCamelCase )
snake_case__ :Optional[Any] = self.get_dummy_inputs(UpperCamelCase )
snake_case__ :Dict = pipe(**UpperCamelCase ).images
snake_case__ :Optional[int] = image[0, -3:, -3:, -1]
self.assertEqual(image.shape ,(1, 32, 32, 3) )
snake_case__ :Tuple = np.array(
[1.000E00, 5.717E-01, 4.717E-01, 1.000E00, 0.000E00, 1.000E00, 3.000E-04, 0.000E00, 9.000E-04] )
snake_case__ :Dict = np.abs(image_slice.flatten() - expected_slice ).max()
self.assertLessEqual(UpperCamelCase ,1E-3 )
def lowerCAmelCase_ ( self ) -> Any:
super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 )
def lowerCAmelCase_ ( self ) -> List[Any]:
super().test_save_load_local(expected_max_difference=3E-3 )
def lowerCAmelCase_ ( self ) -> Tuple:
super().test_save_load_optional_components(expected_max_difference=3E-3 )
def lowerCAmelCase_ ( self ) -> Dict:
super().test_inference_batch_single_identical(expected_max_diff=3E-3 )
@slow
@require_torch_gpu
class _snake_case ( unittest.TestCase ):
def lowerCAmelCase_ ( self ) -> str:
snake_case__ :Optional[int] = "google/ddpm-cifar10-32"
snake_case__ :int = UNetaDModel.from_pretrained(UpperCamelCase )
snake_case__ :List[str] = DDIMScheduler()
snake_case__ :Any = DDIMPipeline(unet=UpperCamelCase ,scheduler=UpperCamelCase )
ddim.to(UpperCamelCase )
ddim.set_progress_bar_config(disable=UpperCamelCase )
snake_case__ :Dict = torch.manual_seed(0 )
snake_case__ :Optional[Any] = ddim(generator=UpperCamelCase ,eta=0.0 ,output_type="numpy" ).images
snake_case__ :int = image[0, -3:, -3:, -1]
assert image.shape == (1, 32, 32, 3)
snake_case__ :str = np.array([0.1723, 0.1617, 0.1600, 0.1626, 0.1497, 0.1513, 0.1505, 0.1442, 0.1453] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def lowerCAmelCase_ ( self ) -> Any:
snake_case__ :int = "google/ddpm-ema-bedroom-256"
snake_case__ :Tuple = UNetaDModel.from_pretrained(UpperCamelCase )
snake_case__ :int = DDIMScheduler.from_pretrained(UpperCamelCase )
snake_case__ :Union[str, Any] = DDIMPipeline(unet=UpperCamelCase ,scheduler=UpperCamelCase )
ddpm.to(UpperCamelCase )
ddpm.set_progress_bar_config(disable=UpperCamelCase )
snake_case__ :int = torch.manual_seed(0 )
snake_case__ :Optional[int] = ddpm(generator=UpperCamelCase ,output_type="numpy" ).images
snake_case__ :Tuple = image[0, -3:, -3:, -1]
assert image.shape == (1, 256, 256, 3)
snake_case__ :Optional[int] = np.array([0.0060, 0.0201, 0.0344, 0.0024, 0.0018, 0.0002, 0.0022, 0.0000, 0.0069] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 | 241 | 1 |
'''simple docstring'''
from PIL import Image
def UpperCAmelCase_ ( A ):
'''simple docstring'''
_a , _a : List[Any] = image.size
_a : str = 0
_a : Any = image.load()
for i in range(A ):
for j in range(A ):
_a : int = pixels[j, i]
mean += pixel
mean //= width * height
for j in range(A ):
for i in range(A ):
_a : int = 2_5_5 if pixels[i, j] > mean else 0
return image
if __name__ == "__main__":
UpperCAmelCase_ : Dict = mean_threshold(Image.open("path_to_image").convert("L"))
image.save("output_image_path")
| 424 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCAmelCase_ : List[str] = logging.get_logger(__name__)
UpperCAmelCase_ : Optional[int] = {
# See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert
}
class a ( snake_case__ ):
'''simple docstring'''
__lowerCAmelCase : Union[str, Any] = """megatron-bert"""
def __init__( self , lowerCamelCase_=2_9_0_5_6 , lowerCamelCase_=1_0_2_4 , lowerCamelCase_=2_4 , lowerCamelCase_=1_6 , lowerCamelCase_=4_0_9_6 , lowerCamelCase_="gelu" , lowerCamelCase_=0.1 , lowerCamelCase_=0.1 , lowerCamelCase_=5_1_2 , lowerCamelCase_=2 , lowerCamelCase_=0.02 , lowerCamelCase_=1e-12 , lowerCamelCase_=0 , lowerCamelCase_="absolute" , lowerCamelCase_=True , **lowerCamelCase_ , ) -> List[str]:
super().__init__(pad_token_id=lowerCamelCase_ , **lowerCamelCase_ )
_a : Union[str, Any] = vocab_size
_a : Any = hidden_size
_a : Tuple = num_hidden_layers
_a : Dict = num_attention_heads
_a : str = hidden_act
_a : Dict = intermediate_size
_a : Any = hidden_dropout_prob
_a : int = attention_probs_dropout_prob
_a : str = max_position_embeddings
_a : int = type_vocab_size
_a : Tuple = initializer_range
_a : Optional[Any] = layer_norm_eps
_a : str = position_embedding_type
_a : str = use_cache
| 424 | 1 |
'''simple docstring'''
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_tf_available():
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING
if is_torch_available():
import torch
from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING
lowerCAmelCase_ : List[Any] = logging.get_logger(__name__)
@add_end_docstrings(__a )
class UpperCamelCase__ ( __a ):
def __init__( self : Union[str, Any] , *lowerCamelCase : Optional[int] , **lowerCamelCase : str ):
'''simple docstring'''
super().__init__(*A__ , **A__ )
requires_backends(self , "vision" )
self.check_model_type(
TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == "tf" else MODEL_FOR_VISION_2_SEQ_MAPPING )
def __a ( self : Tuple , lowerCamelCase : str=None , lowerCamelCase : Optional[Any]=None , lowerCamelCase : Union[str, Any]=None ):
'''simple docstring'''
a__ = {}
a__ = {}
if prompt is not None:
a__ = prompt
if generate_kwargs is not None:
a__ = generate_kwargs
if max_new_tokens is not None:
if "generate_kwargs" not in forward_kwargs:
a__ = {}
if "max_new_tokens" in forward_kwargs["generate_kwargs"]:
raise ValueError(
"\'max_new_tokens\' is defined twice, once in \'generate_kwargs\' and once as a direct parameter,"
" please use only one" )
a__ = max_new_tokens
return preprocess_params, forward_kwargs, {}
def __call__( self : Union[str, Any] , lowerCamelCase : Optional[int] , **lowerCamelCase : Any ):
'''simple docstring'''
return super().__call__(A__ , **A__ )
def __a ( self : Optional[int] , lowerCamelCase : Tuple , lowerCamelCase : Dict=None ):
'''simple docstring'''
a__ = load_image(A__ )
if prompt is not None:
if not isinstance(A__ , A__ ):
raise ValueError(
F'''Received an invalid text input, got - {type(A__ )} - but expected a single string. '''
"Note also that one single text can be provided for conditional image to text generation." )
a__ = self.model.config.model_type
if model_type == "git":
a__ = self.image_processor(images=A__ , return_tensors=self.framework )
a__ = self.tokenizer(text=A__ , add_special_tokens=A__ ).input_ids
a__ = [self.tokenizer.cls_token_id] + input_ids
a__ = torch.tensor(A__ ).unsqueeze(0 )
model_inputs.update({"input_ids": input_ids} )
elif model_type == "pix2struct":
a__ = self.image_processor(images=A__ , header_text=A__ , return_tensors=self.framework )
elif model_type != "vision-encoder-decoder":
# vision-encoder-decoder does not support conditional generation
a__ = self.image_processor(images=A__ , return_tensors=self.framework )
a__ = self.tokenizer(A__ , return_tensors=self.framework )
model_inputs.update(A__ )
else:
raise ValueError(F'''Model type {model_type} does not support conditional text generation''' )
else:
a__ = self.image_processor(images=A__ , return_tensors=self.framework )
if self.model.config.model_type == "git" and prompt is None:
a__ = None
return model_inputs
def __a ( self : List[Any] , lowerCamelCase : int , lowerCamelCase : Dict=None ):
'''simple docstring'''
# Git model sets `model_inputs["input_ids"] = None` in `preprocess` (when `prompt=None`). In batch model, the
# pipeline will group them into a list of `None`, which fail `_forward`. Avoid this by checking it first.
if (
"input_ids" in model_inputs
and isinstance(model_inputs["input_ids"] , A__ )
and all(x is None for x in model_inputs["input_ids"] )
):
a__ = None
if generate_kwargs is None:
a__ = {}
# FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py`
# parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas
# the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name`
# in the `_prepare_model_inputs` method.
a__ = model_inputs.pop(self.model.main_input_name )
a__ = self.model.generate(A__ , **A__ , **A__ )
return model_outputs
def __a ( self : Tuple , lowerCamelCase : List[Any] ):
'''simple docstring'''
a__ = []
for output_ids in model_outputs:
a__ = {
"generated_text": self.tokenizer.decode(
A__ , skip_special_tokens=A__ , )
}
records.append(A__ )
return records
| 489 |
'''simple docstring'''
import shutil
import tempfile
import unittest
from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available
from transformers.testing_utils import (
get_tests_dir,
nested_simplify,
require_sentencepiece,
require_tokenizers,
require_torch,
)
from ...test_tokenization_common import TokenizerTesterMixin
_lowercase = get_tests_dir('fixtures/test_sentencepiece.model')
if is_torch_available():
from transformers.models.mbart.modeling_mbart import shift_tokens_right
_lowercase = 250_004
_lowercase = 250_020
@require_sentencepiece
@require_tokenizers
class _lowercase ( __a , unittest.TestCase ):
_UpperCAmelCase = MBartTokenizer
_UpperCAmelCase = MBartTokenizerFast
_UpperCAmelCase = True
_UpperCAmelCase = True
def UpperCamelCase ( self ) -> str:
super().setUp()
# We have a SentencePiece fixture for testing
snake_case = MBartTokenizer(A__ , keep_accents=A__ )
tokenizer.save_pretrained(self.tmpdirname )
def UpperCamelCase ( self ) -> int:
snake_case = MBartTokenizer(A__ , keep_accents=A__ )
snake_case = tokenizer.tokenize('''This is a test''' )
self.assertListEqual(A__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(A__ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , )
snake_case = 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''',
'''é''',
'''.''',
] , )
snake_case = tokenizer.convert_tokens_to_ids(A__ )
self.assertListEqual(
A__ , [
value + tokenizer.fairseq_offset
for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4]
# ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^
] , )
snake_case = 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>''',
'''.''',
] , )
def UpperCamelCase ( self ) -> Dict:
if not self.test_slow_tokenizer:
# as we don't have a slow version, we can't compare the outputs between slow and fast versions
return
snake_case = (self.rust_tokenizer_class, '''hf-internal-testing/tiny-random-mbart''', {})
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ):
snake_case = self.rust_tokenizer_class.from_pretrained(A__ , **A__ )
snake_case = self.tokenizer_class.from_pretrained(A__ , **A__ )
snake_case = tempfile.mkdtemp()
snake_case = tokenizer_r.save_pretrained(A__ )
snake_case = tokenizer_p.save_pretrained(A__ )
# Checks it save with the same files + the tokenizer.json file for the fast one
self.assertTrue(any('''tokenizer.json''' in f for f in tokenizer_r_files ) )
snake_case = tuple(f for f in tokenizer_r_files if '''tokenizer.json''' not in f )
self.assertSequenceEqual(A__ , A__ )
# Checks everything loads correctly in the same way
snake_case = tokenizer_r.from_pretrained(A__ )
snake_case = tokenizer_p.from_pretrained(A__ )
# Check special tokens are set accordingly on Rust and Python
for key in tokenizer_pp.special_tokens_map:
self.assertTrue(hasattr(A__ , A__ ) )
# self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key))
# self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id"))
shutil.rmtree(A__ )
# Save tokenizer rust, legacy_format=True
snake_case = tempfile.mkdtemp()
snake_case = tokenizer_r.save_pretrained(A__ , legacy_format=A__ )
snake_case = tokenizer_p.save_pretrained(A__ )
# Checks it save with the same files
self.assertSequenceEqual(A__ , A__ )
# Checks everything loads correctly in the same way
snake_case = tokenizer_r.from_pretrained(A__ )
snake_case = tokenizer_p.from_pretrained(A__ )
# Check special tokens are set accordingly on Rust and Python
for key in tokenizer_pp.special_tokens_map:
self.assertTrue(hasattr(A__ , A__ ) )
shutil.rmtree(A__ )
# Save tokenizer rust, legacy_format=False
snake_case = tempfile.mkdtemp()
snake_case = tokenizer_r.save_pretrained(A__ , legacy_format=A__ )
snake_case = tokenizer_p.save_pretrained(A__ )
# Checks it saved the tokenizer.json file
self.assertTrue(any('''tokenizer.json''' in f for f in tokenizer_r_files ) )
# Checks everything loads correctly in the same way
snake_case = tokenizer_r.from_pretrained(A__ )
snake_case = tokenizer_p.from_pretrained(A__ )
# Check special tokens are set accordingly on Rust and Python
for key in tokenizer_pp.special_tokens_map:
self.assertTrue(hasattr(A__ , A__ ) )
shutil.rmtree(A__ )
@require_torch
@require_sentencepiece
@require_tokenizers
class _lowercase ( unittest.TestCase ):
_UpperCAmelCase = '''facebook/mbart-large-en-ro'''
_UpperCAmelCase = [
''' UN Chief Says There Is No Military Solution in Syria''',
''' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.''',
]
_UpperCAmelCase = [
'''Şeful ONU declară că nu există o soluţie militară în Siria''',
'''Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei'''
''' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor'''
''' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.''',
]
_UpperCAmelCase = [8_274, 127_873, 25_916, 7, 8_622, 2_071, 438, 67_485, 53, 187_895, 23, 51_712, 2, EN_CODE]
@classmethod
def UpperCamelCase ( cls ) -> Optional[Any]:
snake_case = MBartTokenizer.from_pretrained(
cls.checkpoint_name , src_lang='''en_XX''' , tgt_lang='''ro_RO''' )
snake_case = 1
return cls
def UpperCamelCase ( self ) -> List[Any]:
self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''ar_AR'''] , 25_00_01 )
self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''en_EN'''] , 25_00_04 )
self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''ro_RO'''] , 25_00_20 )
def UpperCamelCase ( self ) -> Optional[Any]:
snake_case = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0]
self.assertListEqual(self.expected_src_tokens , A__ )
def UpperCamelCase ( self ) -> Union[str, Any]:
self.assertIn(A__ , self.tokenizer.all_special_ids )
snake_case = [RO_CODE, 8_84, 90_19, 96, 9, 9_16, 8_67_92, 36, 1_87_43, 1_55_96, 5, 2]
snake_case = self.tokenizer.decode(A__ , skip_special_tokens=A__ )
snake_case = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=A__ )
self.assertEqual(A__ , A__ )
self.assertNotIn(self.tokenizer.eos_token , A__ )
def UpperCamelCase ( self ) -> Tuple:
snake_case = ['''this is gunna be a long sentence ''' * 20]
assert isinstance(src_text[0] , A__ )
snake_case = 10
snake_case = self.tokenizer(A__ , max_length=A__ , truncation=A__ ).input_ids[0]
self.assertEqual(ids[-2] , 2 )
self.assertEqual(ids[-1] , A__ )
self.assertEqual(len(A__ ) , A__ )
def UpperCamelCase ( self ) -> Union[str, Any]:
self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['''<mask>''', '''ar_AR'''] ) , [25_00_26, 25_00_01] )
def UpperCamelCase ( self ) -> Dict:
snake_case = tempfile.mkdtemp()
snake_case = self.tokenizer.fairseq_tokens_to_ids
self.tokenizer.save_pretrained(A__ )
snake_case = MBartTokenizer.from_pretrained(A__ )
self.assertDictEqual(new_tok.fairseq_tokens_to_ids , A__ )
@require_torch
def UpperCamelCase ( self ) -> Dict:
snake_case = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=A__ , return_tensors='''pt''' )
snake_case = shift_tokens_right(batch['''labels'''] , self.tokenizer.pad_token_id )
# fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4
assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE]
assert batch.decoder_input_ids[1][0].tolist() == RO_CODE
assert batch.decoder_input_ids[1][-1] == 2
assert batch.labels[1][-2:].tolist() == [2, RO_CODE]
@require_torch
def UpperCamelCase ( self ) -> List[Any]:
snake_case = self.tokenizer(
self.src_text , text_target=self.tgt_text , padding=A__ , truncation=A__ , max_length=len(self.expected_src_tokens ) , return_tensors='''pt''' , )
snake_case = shift_tokens_right(batch['''labels'''] , self.tokenizer.pad_token_id )
self.assertIsInstance(A__ , A__ )
self.assertEqual((2, 14) , batch.input_ids.shape )
self.assertEqual((2, 14) , batch.attention_mask.shape )
snake_case = batch.input_ids.tolist()[0]
self.assertListEqual(self.expected_src_tokens , A__ )
self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS
# Test that special tokens are reset
self.assertEqual(self.tokenizer.prefix_tokens , [] )
self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] )
def UpperCamelCase ( self ) -> Dict:
snake_case = self.tokenizer(self.src_text , padding=A__ , truncation=A__ , max_length=3 , return_tensors='''pt''' )
snake_case = self.tokenizer(
text_target=self.tgt_text , padding=A__ , truncation=A__ , max_length=10 , return_tensors='''pt''' )
snake_case = targets['''input_ids''']
snake_case = shift_tokens_right(A__ , self.tokenizer.pad_token_id )
self.assertEqual(batch.input_ids.shape[1] , 3 )
self.assertEqual(batch.decoder_input_ids.shape[1] , 10 )
@require_torch
def UpperCamelCase ( self ) -> Union[str, Any]:
snake_case = self.tokenizer._build_translation_inputs(
'''A test''' , return_tensors='''pt''' , src_lang='''en_XX''' , tgt_lang='''ar_AR''' )
self.assertEqual(
nested_simplify(A__ ) , {
# A, test, EOS, en_XX
'''input_ids''': [[62, 30_34, 2, 25_00_04]],
'''attention_mask''': [[1, 1, 1, 1]],
# ar_AR
'''forced_bos_token_id''': 25_00_01,
} , )
| 342 | 0 |
import os
from datetime import datetime as dt
from github import Github
UpperCAmelCase = [
'''good first issue''',
'''good second issue''',
'''good difficult issue''',
'''enhancement''',
'''new pipeline/model''',
'''new scheduler''',
'''wip''',
]
def UpperCAmelCase_ ( ):
lowercase = Github(os.environ['GITHUB_TOKEN'] )
lowercase = g.get_repo('huggingface/diffusers' )
lowercase = repo.get_issues(state='open' )
for issue in open_issues:
lowercase = sorted(issue.get_comments() , key=lambda __SCREAMING_SNAKE_CASE : i.created_at , reverse=__SCREAMING_SNAKE_CASE )
lowercase = comments[0] if len(__SCREAMING_SNAKE_CASE ) > 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()
| 705 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_torch_available,
is_vision_available,
)
UpperCAmelCase = {'''configuration_deit''': ['''DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DeiTConfig''', '''DeiTOnnxConfig''']}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase = ['''DeiTFeatureExtractor''']
UpperCAmelCase = ['''DeiTImageProcessor''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase = [
'''DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''DeiTForImageClassification''',
'''DeiTForImageClassificationWithTeacher''',
'''DeiTForMaskedImageModeling''',
'''DeiTModel''',
'''DeiTPreTrainedModel''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase = [
'''TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TFDeiTForImageClassification''',
'''TFDeiTForImageClassificationWithTeacher''',
'''TFDeiTForMaskedImageModeling''',
'''TFDeiTModel''',
'''TFDeiTPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_deit import DeiTFeatureExtractor
from .image_processing_deit import DeiTImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_deit import (
DEIT_PRETRAINED_MODEL_ARCHIVE_LIST,
DeiTForImageClassification,
DeiTForImageClassificationWithTeacher,
DeiTForMaskedImageModeling,
DeiTModel,
DeiTPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_deit import (
TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFDeiTForImageClassification,
TFDeiTForImageClassificationWithTeacher,
TFDeiTForMaskedImageModeling,
TFDeiTModel,
TFDeiTPreTrainedModel,
)
else:
import sys
UpperCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 565 | 0 |
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer
from ...utils import logging
_snake_case = logging.get_logger(__name__)
_snake_case = '''▁'''
_snake_case = {'''vocab_file''': '''sentencepiece.bpe.model'''}
_snake_case = {
'''vocab_file''': {
'''facebook/nllb-200-distilled-600M''': (
'''https://huggingface.co/facebook/nllb-200-distilled-600M/blob/main/sentencepiece.bpe.model'''
),
}
}
_snake_case = {
'''facebook/nllb-200-distilled-600M''': 10_24,
}
# fmt: off
_snake_case = ['''ace_Arab''', '''ace_Latn''', '''acm_Arab''', '''acq_Arab''', '''aeb_Arab''', '''afr_Latn''', '''ajp_Arab''', '''aka_Latn''', '''amh_Ethi''', '''apc_Arab''', '''arb_Arab''', '''ars_Arab''', '''ary_Arab''', '''arz_Arab''', '''asm_Beng''', '''ast_Latn''', '''awa_Deva''', '''ayr_Latn''', '''azb_Arab''', '''azj_Latn''', '''bak_Cyrl''', '''bam_Latn''', '''ban_Latn''', '''bel_Cyrl''', '''bem_Latn''', '''ben_Beng''', '''bho_Deva''', '''bjn_Arab''', '''bjn_Latn''', '''bod_Tibt''', '''bos_Latn''', '''bug_Latn''', '''bul_Cyrl''', '''cat_Latn''', '''ceb_Latn''', '''ces_Latn''', '''cjk_Latn''', '''ckb_Arab''', '''crh_Latn''', '''cym_Latn''', '''dan_Latn''', '''deu_Latn''', '''dik_Latn''', '''dyu_Latn''', '''dzo_Tibt''', '''ell_Grek''', '''eng_Latn''', '''epo_Latn''', '''est_Latn''', '''eus_Latn''', '''ewe_Latn''', '''fao_Latn''', '''pes_Arab''', '''fij_Latn''', '''fin_Latn''', '''fon_Latn''', '''fra_Latn''', '''fur_Latn''', '''fuv_Latn''', '''gla_Latn''', '''gle_Latn''', '''glg_Latn''', '''grn_Latn''', '''guj_Gujr''', '''hat_Latn''', '''hau_Latn''', '''heb_Hebr''', '''hin_Deva''', '''hne_Deva''', '''hrv_Latn''', '''hun_Latn''', '''hye_Armn''', '''ibo_Latn''', '''ilo_Latn''', '''ind_Latn''', '''isl_Latn''', '''ita_Latn''', '''jav_Latn''', '''jpn_Jpan''', '''kab_Latn''', '''kac_Latn''', '''kam_Latn''', '''kan_Knda''', '''kas_Arab''', '''kas_Deva''', '''kat_Geor''', '''knc_Arab''', '''knc_Latn''', '''kaz_Cyrl''', '''kbp_Latn''', '''kea_Latn''', '''khm_Khmr''', '''kik_Latn''', '''kin_Latn''', '''kir_Cyrl''', '''kmb_Latn''', '''kon_Latn''', '''kor_Hang''', '''kmr_Latn''', '''lao_Laoo''', '''lvs_Latn''', '''lij_Latn''', '''lim_Latn''', '''lin_Latn''', '''lit_Latn''', '''lmo_Latn''', '''ltg_Latn''', '''ltz_Latn''', '''lua_Latn''', '''lug_Latn''', '''luo_Latn''', '''lus_Latn''', '''mag_Deva''', '''mai_Deva''', '''mal_Mlym''', '''mar_Deva''', '''min_Latn''', '''mkd_Cyrl''', '''plt_Latn''', '''mlt_Latn''', '''mni_Beng''', '''khk_Cyrl''', '''mos_Latn''', '''mri_Latn''', '''zsm_Latn''', '''mya_Mymr''', '''nld_Latn''', '''nno_Latn''', '''nob_Latn''', '''npi_Deva''', '''nso_Latn''', '''nus_Latn''', '''nya_Latn''', '''oci_Latn''', '''gaz_Latn''', '''ory_Orya''', '''pag_Latn''', '''pan_Guru''', '''pap_Latn''', '''pol_Latn''', '''por_Latn''', '''prs_Arab''', '''pbt_Arab''', '''quy_Latn''', '''ron_Latn''', '''run_Latn''', '''rus_Cyrl''', '''sag_Latn''', '''san_Deva''', '''sat_Beng''', '''scn_Latn''', '''shn_Mymr''', '''sin_Sinh''', '''slk_Latn''', '''slv_Latn''', '''smo_Latn''', '''sna_Latn''', '''snd_Arab''', '''som_Latn''', '''sot_Latn''', '''spa_Latn''', '''als_Latn''', '''srd_Latn''', '''srp_Cyrl''', '''ssw_Latn''', '''sun_Latn''', '''swe_Latn''', '''swh_Latn''', '''szl_Latn''', '''tam_Taml''', '''tat_Cyrl''', '''tel_Telu''', '''tgk_Cyrl''', '''tgl_Latn''', '''tha_Thai''', '''tir_Ethi''', '''taq_Latn''', '''taq_Tfng''', '''tpi_Latn''', '''tsn_Latn''', '''tso_Latn''', '''tuk_Latn''', '''tum_Latn''', '''tur_Latn''', '''twi_Latn''', '''tzm_Tfng''', '''uig_Arab''', '''ukr_Cyrl''', '''umb_Latn''', '''urd_Arab''', '''uzn_Latn''', '''vec_Latn''', '''vie_Latn''', '''war_Latn''', '''wol_Latn''', '''xho_Latn''', '''ydd_Hebr''', '''yor_Latn''', '''yue_Hant''', '''zho_Hans''', '''zho_Hant''', '''zul_Latn''']
class UpperCAmelCase_ ( UpperCamelCase ):
'''simple docstring'''
__A : Dict = VOCAB_FILES_NAMES
__A : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__A : List[str] = PRETRAINED_VOCAB_FILES_MAP
__A : Optional[Any] = ["input_ids", "attention_mask"]
__A : List[int] = []
__A : List[int] = []
def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A=None , __A=None , __A=None , __A = None , __A=None , __A=False , **__A , ):
"""simple docstring"""
lowerCamelCase : str = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token
lowerCamelCase : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs
lowerCamelCase : Optional[int] = legacy_behaviour
super().__init__(
bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , tokenizer_file=__A , src_lang=__A , tgt_lang=__A , additional_special_tokens=__A , sp_model_kwargs=self.sp_model_kwargs , legacy_behaviour=__A , **__A , )
lowerCamelCase : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(str(__A ) )
lowerCamelCase : int = vocab_file
# Original fairseq vocab and spm vocab must be "aligned":
# Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
# -------- | ------- | ------- | ------ | ------- | ---- | ---- | ---- | ---- | ---- | ----
# fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | 'an' | '▁n' | '▁m' | '▁t' | '▁k' | '▁a'
# spm | '<unk>' | '<s>' | '</s>' | 'an' | '▁n' | '▁m' | '▁t' | '▁k' | '▁a' | '▁s'
# Mimic fairseq token-to-id alignment for the first 4 token
lowerCamelCase : Tuple = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3}
# The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
lowerCamelCase : Dict = 1
lowerCamelCase : Optional[int] = len(self.sp_model )
lowerCamelCase : int = {
code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__A )
}
lowerCamelCase : int = {v: k for k, v in self.lang_code_to_id.items()}
lowerCamelCase : Dict = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset
self.fairseq_tokens_to_ids.update(self.lang_code_to_id )
lowerCamelCase : int = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
lowerCamelCase : Optional[Any] = list(self.lang_code_to_id.keys() )
if additional_special_tokens is not None:
# Only add those special tokens if they are not already there.
self._additional_special_tokens.extend(
[t for t in additional_special_tokens if t not in self._additional_special_tokens] )
lowerCamelCase : Optional[Any] = src_lang if src_lang is not None else "eng_Latn"
lowerCamelCase : List[str] = self.lang_code_to_id[self._src_lang]
lowerCamelCase : int = tgt_lang
self.set_src_lang_special_tokens(self._src_lang )
def __getstate__( self ):
"""simple docstring"""
lowerCamelCase : str = self.__dict__.copy()
lowerCamelCase : Any = None
lowerCamelCase : Optional[Any] = self.sp_model.serialized_model_proto()
return state
def __setstate__( self , __A ):
"""simple docstring"""
lowerCamelCase : List[str] = d
# for backward compatibility
if not hasattr(self , "sp_model_kwargs" ):
lowerCamelCase : Optional[int] = {}
lowerCamelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.LoadFromSerializedProto(self.sp_model_proto )
@property
def _snake_case ( self ):
"""simple docstring"""
return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token
@property
def _snake_case ( self ):
"""simple docstring"""
return self._src_lang
@src_lang.setter
def _snake_case ( self , __A ):
"""simple docstring"""
lowerCamelCase : List[str] = new_src_lang
self.set_src_lang_special_tokens(self._src_lang )
def _snake_case ( self , __A , __A = None , __A = False ):
"""simple docstring"""
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A )
lowerCamelCase : Optional[Any] = [1] * len(self.prefix_tokens )
lowerCamelCase : List[str] = [1] * len(self.suffix_tokens )
if token_ids_a is None:
return prefix_ones + ([0] * len(__A )) + suffix_ones
return prefix_ones + ([0] * len(__A )) + ([0] * len(__A )) + suffix_ones
def _snake_case ( self , __A , __A = None ):
"""simple docstring"""
if token_ids_a is None:
return self.prefix_tokens + token_ids_a + self.suffix_tokens
# We don't expect to process pairs, but leave the pair logic for API consistency
return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens
def _snake_case ( self , __A , __A = None ):
"""simple docstring"""
lowerCamelCase : Optional[int] = [self.sep_token_id]
lowerCamelCase : Optional[int] = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
def _snake_case ( self , __A , __A , __A , __A , **__A ):
"""simple docstring"""
if src_lang is None or tgt_lang is None:
raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" )
lowerCamelCase : Optional[int] = src_lang
lowerCamelCase : Dict = self(__A , add_special_tokens=__A , return_tensors=__A , **__A )
lowerCamelCase : List[Any] = self.convert_tokens_to_ids(__A )
lowerCamelCase : int = tgt_lang_id
return inputs
def _snake_case ( self ):
"""simple docstring"""
lowerCamelCase : Tuple = {self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def _snake_case ( self , __A ):
"""simple docstring"""
return self.sp_model.encode(__A , out_type=__A )
def _snake_case ( self , __A ):
"""simple docstring"""
if token in self.fairseq_tokens_to_ids:
return self.fairseq_tokens_to_ids[token]
lowerCamelCase : Dict = self.sp_model.PieceToId(__A )
# Need to return unknown token if the SP model returned 0
return spm_id + self.fairseq_offset if spm_id else self.unk_token_id
def _snake_case ( self , __A ):
"""simple docstring"""
if index in self.fairseq_ids_to_tokens:
return self.fairseq_ids_to_tokens[index]
return self.sp_model.IdToPiece(index - self.fairseq_offset )
def _snake_case ( self , __A ):
"""simple docstring"""
lowerCamelCase : str = "".join(__A ).replace(__A , " " ).strip()
return out_string
def _snake_case ( self , __A , __A = None ):
"""simple docstring"""
if not os.path.isdir(__A ):
logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" )
return
lowerCamelCase : Optional[Any] = os.path.join(
__A , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , __A )
elif not os.path.isfile(self.vocab_file ):
with open(__A , "wb" ) as fi:
lowerCamelCase : List[Any] = self.sp_model.serialized_model_proto()
fi.write(__A )
return (out_vocab_file,)
def _snake_case ( self , __A , __A = "eng_Latn" , __A = None , __A = "fra_Latn" , **__A , ):
"""simple docstring"""
lowerCamelCase : Union[str, Any] = src_lang
lowerCamelCase : Dict = tgt_lang
return super().prepare_seqaseq_batch(__A , __A , **__A )
def _snake_case ( self ):
"""simple docstring"""
return self.set_src_lang_special_tokens(self.src_lang )
def _snake_case ( self ):
"""simple docstring"""
return self.set_tgt_lang_special_tokens(self.tgt_lang )
def _snake_case ( self , __A ):
"""simple docstring"""
lowerCamelCase : List[str] = self.lang_code_to_id[src_lang]
if self.legacy_behaviour:
lowerCamelCase : Any = []
lowerCamelCase : Tuple = [self.eos_token_id, self.cur_lang_code]
else:
lowerCamelCase : List[Any] = [self.cur_lang_code]
lowerCamelCase : Optional[int] = [self.eos_token_id]
def _snake_case ( self , __A ):
"""simple docstring"""
lowerCamelCase : str = self.lang_code_to_id[lang]
if self.legacy_behaviour:
lowerCamelCase : Tuple = []
lowerCamelCase : Tuple = [self.eos_token_id, self.cur_lang_code]
else:
lowerCamelCase : int = [self.cur_lang_code]
lowerCamelCase : Tuple = [self.eos_token_id]
| 340 |
import json
import os
import unittest
from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer
from ...test_tokenization_common import TokenizerTesterMixin
class UpperCAmelCase_ ( UpperCamelCase , unittest.TestCase ):
'''simple docstring'''
__A : Dict = CTRLTokenizer
__A : str = False
__A : int = False
def _snake_case ( self ):
"""simple docstring"""
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
lowerCamelCase : Any = ["adapt", "re@@", "a@@", "apt", "c@@", "t", "<unk>"]
lowerCamelCase : List[str] = dict(zip(__A , range(len(__A ) ) ) )
lowerCamelCase : Tuple = ["#version: 0.2", "a p", "ap t</w>", "r e", "a d", "ad apt</w>", ""]
lowerCamelCase : Optional[int] = {"unk_token": "<unk>"}
lowerCamelCase : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
lowerCamelCase : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] )
with open(self.vocab_file , "w" , encoding="utf-8" ) as fp:
fp.write(json.dumps(__A ) + "\n" )
with open(self.merges_file , "w" , encoding="utf-8" ) as fp:
fp.write("\n".join(__A ) )
def _snake_case ( self , **__A ):
"""simple docstring"""
kwargs.update(self.special_tokens_map )
return CTRLTokenizer.from_pretrained(self.tmpdirname , **__A )
def _snake_case ( self , __A ):
"""simple docstring"""
lowerCamelCase : Union[str, Any] = "adapt react readapt apt"
lowerCamelCase : Optional[Any] = "adapt react readapt apt"
return input_text, output_text
def _snake_case ( self ):
"""simple docstring"""
lowerCamelCase : str = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map )
lowerCamelCase : List[Any] = "adapt react readapt apt"
lowerCamelCase : str = "adapt re@@ a@@ c@@ t re@@ adapt apt".split()
lowerCamelCase : Union[str, Any] = tokenizer.tokenize(__A )
self.assertListEqual(__A , __A )
lowerCamelCase : Optional[int] = tokens + [tokenizer.unk_token]
lowerCamelCase : List[Any] = [0, 1, 2, 4, 5, 1, 0, 3, 6]
self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A )
| 340 | 1 |
'''simple docstring'''
from transformers import BertTokenizerFast
from .custom_tokenization import CustomTokenizer
class __SCREAMING_SNAKE_CASE ( lowercase):
__SCREAMING_SNAKE_CASE : Any = CustomTokenizer
pass
| 714 |
import os
from typing import Optional
import fsspec
from fsspec.archive import AbstractArchiveFileSystem
from fsspec.utils import DEFAULT_BLOCK_SIZE
class __SCREAMING_SNAKE_CASE ( lowercase):
__SCREAMING_SNAKE_CASE : str = """"""
__SCREAMING_SNAKE_CASE : str = (
None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz
)
__SCREAMING_SNAKE_CASE : str = None # compression type in fsspec. ex: "gzip"
__SCREAMING_SNAKE_CASE : str = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz
def __init__( self : Tuple , __UpperCamelCase : str = "" , __UpperCamelCase : Optional[str] = None , __UpperCamelCase : Optional[dict] = None , **__UpperCamelCase : Union[str, Any] ):
super().__init__(self , **__UpperCamelCase )
# always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode
_UpperCAmelCase = fsspec.open(
__UpperCamelCase , mode="rb" , protocol=__UpperCamelCase , compression=self.compression , client_kwargs={
"requote_redirect_url": False, # see https://github.com/huggingface/datasets/pull/5459
"trust_env": True, # Enable reading proxy env variables.
**(target_options or {}).pop("client_kwargs" , {} ), # To avoid issues if it was already passed.
} , **(target_options or {}) , )
_UpperCAmelCase = os.path.basename(self.file.path.split("::" )[0] )
_UpperCAmelCase = (
self.compressed_name[: self.compressed_name.rindex("." )]
if "." in self.compressed_name
else self.compressed_name
)
_UpperCAmelCase = None
@classmethod
def UpperCAmelCase__ ( cls : str , __UpperCamelCase : Union[str, Any] ):
# compressed file paths are always relative to the archive root
return super()._strip_protocol(__UpperCamelCase ).lstrip("/" )
def UpperCAmelCase__ ( self : List[Any] ):
if self.dir_cache is None:
_UpperCAmelCase = {**self.file.fs.info(self.file.path ), "name": self.uncompressed_name}
_UpperCAmelCase = {f["name"]: f}
def UpperCAmelCase__ ( self : Union[str, Any] , __UpperCamelCase : str ):
return self.file.open().read()
def UpperCAmelCase__ ( self : Optional[Any] , __UpperCamelCase : str , __UpperCamelCase : str = "rb" , __UpperCamelCase : Optional[Any]=None , __UpperCamelCase : Optional[int]=True , __UpperCamelCase : str=None , **__UpperCamelCase : List[Any] , ):
_UpperCAmelCase = self._strip_protocol(__UpperCamelCase )
if mode != "rb":
raise ValueError(F'''Tried to read with mode {mode} on file {self.file.path} opened with mode \'rb\'''' )
return self.file.open()
class __SCREAMING_SNAKE_CASE ( lowercase):
__SCREAMING_SNAKE_CASE : int = """bz2"""
__SCREAMING_SNAKE_CASE : int = """bz2"""
__SCREAMING_SNAKE_CASE : Optional[Any] = """.bz2"""
class __SCREAMING_SNAKE_CASE ( lowercase):
__SCREAMING_SNAKE_CASE : List[Any] = """gzip"""
__SCREAMING_SNAKE_CASE : int = """gzip"""
__SCREAMING_SNAKE_CASE : List[str] = """.gz"""
class __SCREAMING_SNAKE_CASE ( lowercase):
__SCREAMING_SNAKE_CASE : Any = """lz4"""
__SCREAMING_SNAKE_CASE : int = """lz4"""
__SCREAMING_SNAKE_CASE : Dict = """.lz4"""
class __SCREAMING_SNAKE_CASE ( lowercase):
__SCREAMING_SNAKE_CASE : Tuple = """xz"""
__SCREAMING_SNAKE_CASE : int = """xz"""
__SCREAMING_SNAKE_CASE : Dict = """.xz"""
class __SCREAMING_SNAKE_CASE ( lowercase):
__SCREAMING_SNAKE_CASE : List[str] = """zstd"""
__SCREAMING_SNAKE_CASE : List[Any] = """zstd"""
__SCREAMING_SNAKE_CASE : Optional[int] = """.zst"""
def __init__( self : Any , __UpperCamelCase : str , __UpperCamelCase : str = "rb" , __UpperCamelCase : Optional[str] = None , __UpperCamelCase : Optional[dict] = None , __UpperCamelCase : int = DEFAULT_BLOCK_SIZE , **__UpperCamelCase : Optional[Any] , ):
super().__init__(
fo=__UpperCamelCase , mode=__UpperCamelCase , target_protocol=__UpperCamelCase , target_options=__UpperCamelCase , block_size=__UpperCamelCase , **__UpperCamelCase , )
# We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2:
#
# File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open
# out.close = close
# AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only
#
# see https://github.com/intake/filesystem_spec/issues/725
_UpperCAmelCase = self.file.__enter__
class __SCREAMING_SNAKE_CASE :
def __init__( self : int , __UpperCamelCase : Optional[Any] ):
_UpperCAmelCase = file_
def __enter__( self : str ):
self._file.__enter__()
return self
def __exit__( self : Optional[int] , *__UpperCamelCase : List[Any] , **__UpperCamelCase : Dict ):
self._file.__exit__(*__UpperCamelCase , **__UpperCamelCase )
def __iter__( self : Any ):
return iter(self._file )
def UpperCAmelCase__ ( self : List[Any] ):
return next(self._file )
def __getattr__( self : List[Any] , __UpperCamelCase : Optional[Any] ):
return getattr(self._file , __UpperCamelCase )
def fixed_enter(*__UpperCamelCase : int , **__UpperCamelCase : Union[str, Any] ):
return WrappedFile(_enter(*__UpperCamelCase , **__UpperCamelCase ) )
_UpperCAmelCase = fixed_enter
| 129 | 0 |
"""simple docstring"""
import argparse
import hashlib # hashlib is only used inside the Test class
import struct
class __snake_case :
def __init__( self: str , A_: Optional[Any] ):
__lowerCamelCase = data
__lowerCamelCase = [0X6745_2301, 0XEFCD_AB89, 0X98BA_DCFE, 0X1032_5476, 0XC3D2_E1F0]
@staticmethod
def __a ( A_: int , A_: List[Any] ):
return ((n << b) | (n >> (32 - b))) & 0XFFFF_FFFF
def __a ( self: Optional[int] ):
__lowerCamelCase = b"""\x80""" + b"""\x00""" * (63 - (len(self.data ) + 8) % 64)
__lowerCamelCase = self.data + padding + struct.pack(""">Q""" , 8 * len(self.data ) )
return padded_data
def __a ( self: Tuple ):
return [
self.padded_data[i : i + 64] for i in range(0 , len(self.padded_data ) , 64 )
]
def __a ( self: Dict , A_: Union[str, Any] ):
__lowerCamelCase = list(struct.unpack(""">16L""" , A_ ) ) + [0] * 64
for i in range(16 , 80 ):
__lowerCamelCase = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]) , 1 )
return w
def __a ( self: str ):
__lowerCamelCase = self.padding()
__lowerCamelCase = self.split_blocks()
for block in self.blocks:
__lowerCamelCase = self.expand_block(A_ )
__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase = self.h
for i in range(0 , 80 ):
if 0 <= i < 20:
__lowerCamelCase = (b & c) | ((~b) & d)
__lowerCamelCase = 0X5A82_7999
elif 20 <= i < 40:
__lowerCamelCase = b ^ c ^ d
__lowerCamelCase = 0X6ED9_EBA1
elif 40 <= i < 60:
__lowerCamelCase = (b & c) | (b & d) | (c & d)
__lowerCamelCase = 0X8F1B_BCDC
elif 60 <= i < 80:
__lowerCamelCase = b ^ c ^ d
__lowerCamelCase = 0XCA62_C1D6
__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase = (
self.rotate(A_ , 5 ) + f + e + k + expanded_block[i] & 0XFFFF_FFFF,
a,
self.rotate(A_ , 30 ),
c,
d,
)
__lowerCamelCase = (
self.h[0] + a & 0XFFFF_FFFF,
self.h[1] + b & 0XFFFF_FFFF,
self.h[2] + c & 0XFFFF_FFFF,
self.h[3] + d & 0XFFFF_FFFF,
self.h[4] + e & 0XFFFF_FFFF,
)
return ("{:08x}" * 5).format(*self.h )
def a_ ( ):
__lowerCamelCase = B"""Test String"""
assert SHAaHash(lowercase__ ).final_hash() == hashlib.shaa(lowercase__ ).hexdigest() # noqa: S324
def a_ ( ):
__lowerCamelCase = argparse.ArgumentParser(description="""Process some strings or files""" )
parser.add_argument(
"""--string""", dest="""input_string""", default="""Hello World!! Welcome to Cryptography""", help="""Hash the string""", )
parser.add_argument("""--file""", dest="""input_file""", help="""Hash contents of a file""" )
__lowerCamelCase = parser.parse_args()
__lowerCamelCase = args.input_string
# In any case hash input should be a bytestring
if args.input_file:
with open(args.input_file, """rb""" ) as f:
__lowerCamelCase = f.read()
else:
__lowerCamelCase = bytes(lowercase__, """utf-8""" )
print(SHAaHash(lowercase__ ).final_hash() )
if __name__ == "__main__":
main()
import doctest
doctest.testmod()
| 281 |
"""simple docstring"""
from __future__ import annotations
def a_ ( lowercase__ :list[float] ):
if len(lowercase__ ) < 2:
raise ValueError("""Monogons and Digons are not polygons in the Euclidean space""" )
if any(i <= 0 for i in nums ):
raise ValueError("""All values must be greater than 0""" )
__lowerCamelCase = nums.copy()
copy_nums.sort()
return copy_nums[-1] < sum(copy_nums[:-1] )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 281 | 1 |
import random
import unittest
from torch.utils.data import BatchSampler, DataLoader, IterableDataset
from accelerate import Accelerator
from accelerate.data_loader import (
BatchSamplerShard,
DataLoaderDispatcher,
DataLoaderShard,
IterableDatasetShard,
SkipBatchSampler,
SkipDataLoader,
skip_first_batches,
)
class lowerCAmelCase_ ( snake_case__ ):
def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int]=0.01 , SCREAMING_SNAKE_CASE_ : List[Any]=1_000 ):
lowerCAmelCase__ = p_stop
lowerCAmelCase__ = max_length
def __iter__( self : List[Any] ):
lowerCAmelCase__ = 0
lowerCAmelCase__ = False
while not stop and count < self.max_length:
yield count
count += 1
lowerCAmelCase__ = random.random() < self.p_stop
class lowerCAmelCase_ ( unittest.TestCase ):
def __snake_case ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Tuple=False , SCREAMING_SNAKE_CASE_ : int=True ):
lowerCAmelCase__ = [
BatchSamplerShard(SCREAMING_SNAKE_CASE_ , 2 , SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ , even_batches=SCREAMING_SNAKE_CASE_ )
for i in range(2 )
]
lowerCAmelCase__ = [list(SCREAMING_SNAKE_CASE_ ) for batch_sampler_shard in batch_sampler_shards]
if not split_batches:
self.assertListEqual([len(SCREAMING_SNAKE_CASE_ ) for shard in batch_sampler_shards] , [len(SCREAMING_SNAKE_CASE_ ) for e in expected] )
self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
def __snake_case ( self : Optional[Any] ):
# Check the shards when the dataset is a round multiple of total batch size.
lowerCAmelCase__ = BatchSampler(range(24 ) , batch_size=3 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]],
[[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = BatchSampler(range(24 ) , batch_size=3 , drop_last=SCREAMING_SNAKE_CASE_ )
# Expected shouldn't change
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Check the shards when the dataset is a round multiple of batch size but not total batch size.
lowerCAmelCase__ = BatchSampler(range(21 ) , batch_size=3 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]],
[[3, 4, 5], [9, 10, 11], [15, 16, 17], [0, 1, 2]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = BatchSampler(range(21 ) , batch_size=3 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1, 2], [6, 7, 8], [12, 13, 14]],
[[3, 4, 5], [9, 10, 11], [15, 16, 17]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Check the shards when the dataset is not a round multiple of batch size but has a multiple of
# num_processes batch.
lowerCAmelCase__ = BatchSampler(range(22 ) , batch_size=3 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]],
[[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 0, 1]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = BatchSampler(range(22 ) , batch_size=3 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1, 2], [6, 7, 8], [12, 13, 14]],
[[3, 4, 5], [9, 10, 11], [15, 16, 17]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of
# num_processes batch.
lowerCAmelCase__ = BatchSampler(range(20 ) , batch_size=3 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 0]],
[[3, 4, 5], [9, 10, 11], [15, 16, 17], [1, 2, 3]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = BatchSampler(range(20 ) , batch_size=3 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1, 2], [6, 7, 8], [12, 13, 14]],
[[3, 4, 5], [9, 10, 11], [15, 16, 17]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Check the shards when the dataset is very small.
lowerCAmelCase__ = BatchSampler(range(2 ) , batch_size=3 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [[[0, 1, 0]], [[1, 0, 1]]]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = BatchSampler(range(2 ) , batch_size=3 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [[], []]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
def __snake_case ( self : List[str] ):
# Check the shards when the dataset is a round multiple of batch size.
lowerCAmelCase__ = BatchSampler(range(24 ) , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]],
[[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = BatchSampler(range(24 ) , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ )
# Expected shouldn't change
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ )
# Check the shards when the dataset is not a round multiple of batch size.
lowerCAmelCase__ = BatchSampler(range(22 ) , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]],
[[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [0, 1]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = BatchSampler(range(22 ) , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]],
[[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ )
# Check the shards when the dataset is not a round multiple of batch size or num_processes.
lowerCAmelCase__ = BatchSampler(range(21 ) , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 0]],
[[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [1, 2]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = BatchSampler(range(21 ) , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]],
[[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ )
# Check the shards when the dataset is very small.
lowerCAmelCase__ = BatchSampler(range(2 ) , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [[[0, 1]], [[0, 1]]]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = BatchSampler(range(2 ) , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [[], []]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ )
def __snake_case ( self : Union[str, Any] ):
# Check the shards when the dataset is a round multiple of total batch size.
lowerCAmelCase__ = BatchSampler(range(24 ) , batch_size=3 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]],
[[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , even_batches=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = BatchSampler(range(24 ) , batch_size=3 , drop_last=SCREAMING_SNAKE_CASE_ )
# Expected shouldn't change
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , even_batches=SCREAMING_SNAKE_CASE_ )
# Check the shards when the dataset is a round multiple of batch size but not total batch size.
lowerCAmelCase__ = BatchSampler(range(21 ) , batch_size=3 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]],
[[3, 4, 5], [9, 10, 11], [15, 16, 17]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , even_batches=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = BatchSampler(range(21 ) , batch_size=3 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1, 2], [6, 7, 8], [12, 13, 14]],
[[3, 4, 5], [9, 10, 11], [15, 16, 17]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , even_batches=SCREAMING_SNAKE_CASE_ )
# Check the shards when the dataset is not a round multiple of batch size but has a multiple of
# num_processes batch.
lowerCAmelCase__ = BatchSampler(range(22 ) , batch_size=3 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]],
[[3, 4, 5], [9, 10, 11], [15, 16, 17], [21]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , even_batches=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = BatchSampler(range(22 ) , batch_size=3 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1, 2], [6, 7, 8], [12, 13, 14]],
[[3, 4, 5], [9, 10, 11], [15, 16, 17]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , even_batches=SCREAMING_SNAKE_CASE_ )
# Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of
# num_processes batch.
lowerCAmelCase__ = BatchSampler(range(20 ) , batch_size=3 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19]],
[[3, 4, 5], [9, 10, 11], [15, 16, 17]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , even_batches=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = BatchSampler(range(20 ) , batch_size=3 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1, 2], [6, 7, 8], [12, 13, 14]],
[[3, 4, 5], [9, 10, 11], [15, 16, 17]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , even_batches=SCREAMING_SNAKE_CASE_ )
# Check the shards when the dataset is very small.
lowerCAmelCase__ = BatchSampler(range(2 ) , batch_size=3 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [[[0, 1]], []]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , even_batches=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = BatchSampler(range(2 ) , batch_size=3 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [[], []]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , even_batches=SCREAMING_SNAKE_CASE_ )
def __snake_case ( self : List[str] ):
# Check the shards when the dataset is a round multiple of batch size.
lowerCAmelCase__ = BatchSampler(range(24 ) , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]],
[[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ , even_batches=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = BatchSampler(range(24 ) , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ )
# Expected shouldn't change
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ , even_batches=SCREAMING_SNAKE_CASE_ )
# Check the shards when the dataset is not a round multiple of batch size.
lowerCAmelCase__ = BatchSampler(range(22 ) , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]],
[[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ , even_batches=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = BatchSampler(range(22 ) , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]],
[[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ , even_batches=SCREAMING_SNAKE_CASE_ )
# Check the shards when the dataset is not a round multiple of batch size or num_processes.
lowerCAmelCase__ = BatchSampler(range(21 ) , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20]],
[[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ , even_batches=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = BatchSampler(range(21 ) , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
[[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]],
[[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]],
]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ , even_batches=SCREAMING_SNAKE_CASE_ )
# Check the shards when the dataset is very small.
lowerCAmelCase__ = BatchSampler(range(2 ) , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [[[0, 1]], []]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ , even_batches=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = BatchSampler(range(2 ) , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [[], []]
self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ , even_batches=SCREAMING_SNAKE_CASE_ )
def __snake_case ( self : Optional[Any] ):
lowerCAmelCase__ = [[0, 1, 2], [3, 4], [5, 6, 7, 8], [9, 10, 11], [12, 13]]
lowerCAmelCase__ = [BatchSamplerShard(SCREAMING_SNAKE_CASE_ , 2 , SCREAMING_SNAKE_CASE_ , even_batches=SCREAMING_SNAKE_CASE_ ) for i in range(2 )]
self.assertEqual(len(batch_sampler_shards[0] ) , 3 )
self.assertEqual(len(batch_sampler_shards[1] ) , 2 )
self.assertListEqual(list(batch_sampler_shards[0] ) , [[0, 1, 2], [5, 6, 7, 8], [12, 13]] )
self.assertListEqual(list(batch_sampler_shards[1] ) , [[3, 4], [9, 10, 11]] )
def __snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Union[str, Any]=False , SCREAMING_SNAKE_CASE_ : int=2 , SCREAMING_SNAKE_CASE_ : List[Any]=False ):
random.seed(SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = list(SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = [
IterableDatasetShard(
SCREAMING_SNAKE_CASE_ , batch_size=SCREAMING_SNAKE_CASE_ , drop_last=SCREAMING_SNAKE_CASE_ , num_processes=SCREAMING_SNAKE_CASE_ , process_index=SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ , )
for i in range(SCREAMING_SNAKE_CASE_ )
]
lowerCAmelCase__ = []
for iterable_dataset_shard in iterable_dataset_shards:
# Since our random iterable dataset will be... random... we need to use a seed to get reproducible results.
random.seed(SCREAMING_SNAKE_CASE_ )
iterable_dataset_lists.append(list(SCREAMING_SNAKE_CASE_ ) )
lowerCAmelCase__ = batch_size // num_processes if split_batches else batch_size
# All iterable dataset shard should have the same length, a round multiple of shard_batch_size
lowerCAmelCase__ = iterable_dataset_lists[0]
for l in iterable_dataset_lists[1:]:
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) )
self.assertTrue(len(SCREAMING_SNAKE_CASE_ ) % shard_batch_size == 0 )
lowerCAmelCase__ = []
for idx in range(0 , len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ):
for l in iterable_dataset_lists:
observed += l[idx : idx + shard_batch_size]
if not drop_last:
while len(SCREAMING_SNAKE_CASE_ ) < len(SCREAMING_SNAKE_CASE_ ):
reference += reference
self.assertListEqual(SCREAMING_SNAKE_CASE_ , reference[: len(SCREAMING_SNAKE_CASE_ )] )
def __snake_case ( self : Optional[int] ):
lowerCAmelCase__ = 42
lowerCAmelCase__ = RandomIterableDataset()
self.check_iterable_dataset_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ )
self.check_iterable_dataset_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ )
self.check_iterable_dataset_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ )
self.check_iterable_dataset_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ )
# Edge case with a very small dataset
lowerCAmelCase__ = RandomIterableDataset(max_length=2 )
self.check_iterable_dataset_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ )
self.check_iterable_dataset_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ )
self.check_iterable_dataset_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ )
self.check_iterable_dataset_shards(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ )
def __snake_case ( self : List[str] ):
lowerCAmelCase__ = BatchSampler(range(16 ) , batch_size=4 , drop_last=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = SkipBatchSampler(SCREAMING_SNAKE_CASE_ , 2 )
self.assertListEqual(list(SCREAMING_SNAKE_CASE_ ) , [[8, 9, 10, 11], [12, 13, 14, 15]] )
def __snake_case ( self : List[Any] ):
lowerCAmelCase__ = SkipDataLoader(list(range(16 ) ) , batch_size=4 , skip_batches=2 )
self.assertListEqual([t.tolist() for t in dataloader] , [[8, 9, 10, 11], [12, 13, 14, 15]] )
def __snake_case ( self : List[Any] ):
lowerCAmelCase__ = DataLoader(list(range(16 ) ) , batch_size=4 )
lowerCAmelCase__ = skip_first_batches(SCREAMING_SNAKE_CASE_ , num_batches=2 )
self.assertListEqual([t.tolist() for t in new_dataloader] , [[8, 9, 10, 11], [12, 13, 14, 15]] )
def __snake_case ( self : Tuple ):
lowerCAmelCase__ = DataLoaderShard(list(range(16 ) ) , batch_size=4 )
for idx, _ in enumerate(SCREAMING_SNAKE_CASE_ ):
self.assertEqual(dataloader.end_of_dataloader , idx == 3 )
# Test it also works on the second iteration
for idx, _ in enumerate(SCREAMING_SNAKE_CASE_ ):
self.assertEqual(dataloader.end_of_dataloader , idx == 3 )
def __snake_case ( self : str ):
Accelerator()
lowerCAmelCase__ = DataLoaderDispatcher(range(16 ) , batch_size=4 )
for idx, _ in enumerate(SCREAMING_SNAKE_CASE_ ):
self.assertEqual(dataloader.end_of_dataloader , idx == 3 )
# Test it also works on the second iteration
for idx, _ in enumerate(SCREAMING_SNAKE_CASE_ ):
self.assertEqual(dataloader.end_of_dataloader , idx == 3 )
| 719 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
_UpperCAmelCase : str = {
"configuration_blenderbot_small": [
"BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP",
"BlenderbotSmallConfig",
"BlenderbotSmallOnnxConfig",
],
"tokenization_blenderbot_small": ["BlenderbotSmallTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCAmelCase : List[str] = ["BlenderbotSmallTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCAmelCase : List[str] = [
"BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST",
"BlenderbotSmallForCausalLM",
"BlenderbotSmallForConditionalGeneration",
"BlenderbotSmallModel",
"BlenderbotSmallPreTrainedModel",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCAmelCase : Dict = [
"TFBlenderbotSmallForConditionalGeneration",
"TFBlenderbotSmallModel",
"TFBlenderbotSmallPreTrainedModel",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCAmelCase : List[str] = [
"FlaxBlenderbotSmallForConditionalGeneration",
"FlaxBlenderbotSmallModel",
"FlaxBlenderbotSmallPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_blenderbot_small import (
BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP,
BlenderbotSmallConfig,
BlenderbotSmallOnnxConfig,
)
from .tokenization_blenderbot_small import BlenderbotSmallTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_blenderbot_small_fast import BlenderbotSmallTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_blenderbot_small import (
BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST,
BlenderbotSmallForCausalLM,
BlenderbotSmallForConditionalGeneration,
BlenderbotSmallModel,
BlenderbotSmallPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_blenderbot_small import (
TFBlenderbotSmallForConditionalGeneration,
TFBlenderbotSmallModel,
TFBlenderbotSmallPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_blenderbot_small import (
FlaxBlenderbotSmallForConditionalGeneration,
FlaxBlenderbotSmallModel,
FlaxBlenderbotSmallPreTrainedModel,
)
else:
import sys
_UpperCAmelCase : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 288 | 0 |
"""simple docstring"""
from typing import List, Optional, Union
from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class UpperCAmelCase_ ( A_):
lowerCamelCase__ : List[Any] = ["image_processor", "tokenizer"]
lowerCamelCase__ : Optional[Any] = "BlipImageProcessor"
lowerCamelCase__ : List[str] = ("BertTokenizer", "BertTokenizerFast")
def __init__( self , a , a ) -> List[str]:
lowercase__ : Dict = False
super().__init__(a , a )
lowercase__ : Optional[Any] = self.image_processor
def __call__( self , a = None , a = None , a = True , a = False , a = None , a = None , a = 0 , a = None , a = None , a = False , a = False , a = False , a = False , a = False , a = True , a = None , **a , ) -> BatchEncoding:
if images is None and text is None:
raise ValueError('You have to specify either images or text.' )
# Get only text
if images is None:
lowercase__ : Any = self.tokenizer
lowercase__ : str = self.tokenizer(
text=a , add_special_tokens=a , padding=a , truncation=a , max_length=a , stride=a , pad_to_multiple_of=a , return_attention_mask=a , return_overflowing_tokens=a , return_special_tokens_mask=a , return_offsets_mapping=a , return_token_type_ids=a , return_length=a , verbose=a , return_tensors=a , **a , )
return text_encoding
# add pixel_values
lowercase__ : Dict = self.image_processor(a , return_tensors=a )
if text is not None:
lowercase__ : Optional[Any] = self.tokenizer(
text=a , add_special_tokens=a , padding=a , truncation=a , max_length=a , stride=a , pad_to_multiple_of=a , return_attention_mask=a , return_overflowing_tokens=a , return_special_tokens_mask=a , return_offsets_mapping=a , return_token_type_ids=a , return_length=a , verbose=a , return_tensors=a , **a , )
else:
lowercase__ : List[Any] = None
if text_encoding is not None:
encoding_image_processor.update(a )
return encoding_image_processor
def _UpperCAmelCase ( self , *a , **a ) -> Optional[int]:
return self.tokenizer.batch_decode(*a , **a )
def _UpperCAmelCase ( self , *a , **a ) -> Optional[int]:
return self.tokenizer.decode(*a , **a )
@property
def _UpperCAmelCase ( self ) -> Tuple:
lowercase__ : str = self.tokenizer.model_input_names
lowercase__ : Optional[Any] = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
| 599 |
"""simple docstring"""
from typing import Dict, List
from nltk.translate import gleu_score
import datasets
from datasets import MetricInfo
UpperCAmelCase = """\
@misc{wu2016googles,
title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},
author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey
and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin
Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto
Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and
Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes
and Jeffrey Dean},
year={2016},
eprint={1609.08144},
archivePrefix={arXiv},
primaryClass={cs.CL}
}
"""
UpperCAmelCase = """\
The BLEU score has some undesirable properties when used for single
sentences, as it was designed to be a corpus measure. We therefore
use a slightly different score for our RL experiments which we call
the 'GLEU score'. For the GLEU score, we record all sub-sequences of
1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then
compute a recall, which is the ratio of the number of matching n-grams
to the number of total n-grams in the target (ground truth) sequence,
and a precision, which is the ratio of the number of matching n-grams
to the number of total n-grams in the generated output sequence. Then
GLEU score is simply the minimum of recall and precision. This GLEU
score's range is always between 0 (no matches) and 1 (all match) and
it is symmetrical when switching output and target. According to
our experiments, GLEU score correlates quite well with the BLEU
metric on a corpus level but does not have its drawbacks for our per
sentence reward objective.
"""
UpperCAmelCase = """\
Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.
Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching
tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.
Args:
predictions (list of str): list of translations to score.
Each translation should be tokenized into a list of tokens.
references (list of list of str): list of lists of references for each translation.
Each reference should be tokenized into a list of tokens.
min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.
max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.
Returns:
'google_bleu': google_bleu score
Examples:
Example 1:
>>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',
... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']
>>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']
>>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
... 'interested', 'in', 'world', 'history']
>>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
... 'because', 'he', 'read', 'the', 'book']
>>> list_of_references = [[ref1a], [ref2a]]
>>> hypotheses = [hyp1, hyp2]
>>> google_bleu = datasets.load_metric(\"google_bleu\")
>>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
>>> print(round(results[\"google_bleu\"], 2))
0.44
Example 2:
>>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',
... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']
>>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']
>>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
... 'heed', 'the', 'cat', 'commands']
>>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
... 'of', 'the', 'cat']
>>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
... 'interested', 'in', 'world', 'history']
>>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
... 'because', 'he', 'read', 'the', 'book']
>>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
>>> hypotheses = [hyp1, hyp2]
>>> google_bleu = datasets.load_metric(\"google_bleu\")
>>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
>>> print(round(results[\"google_bleu\"], 2))
0.61
Example 3:
>>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',
... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']
>>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']
>>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
... 'heed', 'the', 'cat', 'commands']
>>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
... 'of', 'the', 'cat']
>>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
... 'interested', 'in', 'world', 'history']
>>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
... 'because', 'he', 'read', 'the', 'book']
>>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
>>> hypotheses = [hyp1, hyp2]
>>> google_bleu = datasets.load_metric(\"google_bleu\")
>>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)
>>> print(round(results[\"google_bleu\"], 2))
0.53
Example 4:
>>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',
... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']
>>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']
>>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
... 'heed', 'the', 'cat', 'commands']
>>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
... 'of', 'the', 'cat']
>>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
... 'interested', 'in', 'world', 'history']
>>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
... 'because', 'he', 'read', 'the', 'book']
>>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
>>> hypotheses = [hyp1, hyp2]
>>> google_bleu = datasets.load_metric(\"google_bleu\")
>>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)
>>> print(round(results[\"google_bleu\"], 2))
0.4
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION )
class lowercase__ ( datasets.Metric ):
def UpperCamelCase_ ( self) -> MetricInfo:
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"""predictions""": datasets.Sequence(datasets.Value("""string""" , id="""token""") , id="""sequence"""),
"""references""": datasets.Sequence(
datasets.Sequence(datasets.Value("""string""" , id="""token""") , id="""sequence""") , id="""references"""),
}) , )
def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 1 , SCREAMING_SNAKE_CASE = 4 , ) -> Dict[str, float]:
return {
"google_bleu": gleu_score.corpus_gleu(
list_of_references=SCREAMING_SNAKE_CASE , hypotheses=SCREAMING_SNAKE_CASE , min_len=SCREAMING_SNAKE_CASE , max_len=SCREAMING_SNAKE_CASE)
}
| 88 | 0 |
import argparse
import torch
from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration
from transformers.utils import logging
logging.set_verbosity_info()
lowercase = logging.get_logger(__name__)
lowercase = [
["attention", "attn"],
["encoder_attention", "encoder_attn"],
["q_lin", "q_proj"],
["k_lin", "k_proj"],
["v_lin", "v_proj"],
["out_lin", "out_proj"],
["norm_embeddings", "layernorm_embedding"],
["position_embeddings", "embed_positions"],
["embeddings", "embed_tokens"],
["ffn.lin", "fc"],
]
def __UpperCAmelCase ( a_) -> Union[str, Any]:
if k == "embeddings.weight":
return "shared.weight"
for parlai_name, hf_name in PATTERNS:
snake_case_ = k.replace(a_ , a_)
if k.startswith('encoder'):
snake_case_ = k.replace('.attn' , '.self_attn')
snake_case_ = k.replace('norm1' , 'self_attn_layer_norm')
snake_case_ = k.replace('norm2' , 'final_layer_norm')
elif k.startswith('decoder'):
snake_case_ = k.replace('norm1' , 'self_attn_layer_norm')
snake_case_ = k.replace('norm2' , 'encoder_attn_layer_norm')
snake_case_ = k.replace('norm3' , 'final_layer_norm')
return k
def __UpperCAmelCase ( a_) -> str:
snake_case_ = [
'model.encoder.layernorm_embedding.weight',
'model.encoder.layernorm_embedding.bias',
'model.decoder.layernorm_embedding.weight',
'model.decoder.layernorm_embedding.bias',
]
for k in keys:
snake_case_ = sd.pop(a_)
snake_case_ = k.replace('layernorm_embedding' , 'layer_norm')
assert new_k not in sd
snake_case_ = v
lowercase = ["START"]
@torch.no_grad()
def __UpperCAmelCase ( a_ , a_ , a_) -> int:
snake_case_ = torch.load(a_ , map_location='cpu')
snake_case_ = model['model']
snake_case_ = BlenderbotConfig.from_json_file(a_)
snake_case_ = BlenderbotForConditionalGeneration(a_)
snake_case_ = m.model.state_dict().keys()
snake_case_ = []
snake_case_ = {}
for k, v in sd.items():
if k in IGNORE_KEYS:
continue
snake_case_ = rename_state_dict_key(a_)
if new_k not in valid_keys:
failures.append([k, new_k])
else:
snake_case_ = v
if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm
rename_layernorm_keys(a_)
m.model.load_state_dict(a_ , strict=a_)
m.half()
m.save_pretrained(a_)
if __name__ == "__main__":
lowercase = argparse.ArgumentParser()
# Required parameters
parser.add_argument("--src_path", type=str, help="like blenderbot-model.bin")
parser.add_argument("--save_dir", default="hf_blenderbot", type=str, help="Where to save converted model.")
parser.add_argument(
"--hf_config_json", default="blenderbot-3b-config.json", type=str, help="Path to config to use"
)
lowercase = parser.parse_args()
convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
| 700 |
def __UpperCAmelCase ( a_):
if not isinstance(a_ , a_):
raise ValueError('Input must be an integer')
if input_num <= 0:
raise ValueError('Input must be positive')
return sum(
divisor for divisor in range(1 , input_num // 2 + 1) if input_num % divisor == 0)
if __name__ == "__main__":
import doctest
doctest.testmod()
| 607 | 0 |
def lowerCamelCase__ ( _lowercase = 4000000 ):
'''simple docstring'''
UpperCAmelCase_ : Tuple = []
UpperCAmelCase_, UpperCAmelCase_ : int = 0, 1
while b <= n:
if b % 2 == 0:
even_fibs.append(__UpperCAmelCase )
UpperCAmelCase_, UpperCAmelCase_ : Optional[int] = b, a + b
return sum(__UpperCAmelCase )
if __name__ == "__main__":
print(F"""{solution() = }""") | 30 |
import numpy as np
import torch
from torch.utils.data import DataLoader
from accelerate.utils.dataclasses import DistributedType
class lowerCamelCase_ :
'''simple docstring'''
def __init__( self : Any , _lowerCAmelCase : Optional[int]=2 , _lowerCAmelCase : Any=3 , _lowerCAmelCase : Tuple=64 , _lowerCAmelCase : List[str]=None ):
SCREAMING_SNAKE_CASE_ = np.random.default_rng(_lowerCAmelCase )
SCREAMING_SNAKE_CASE_ = length
SCREAMING_SNAKE_CASE_ = rng.normal(size=(length,) ).astype(np.floataa )
SCREAMING_SNAKE_CASE_ = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa )
def __len__( self : Optional[int] ):
return self.length
def __getitem__( self : str , _lowerCAmelCase : Union[str, Any] ):
return {"x": self.x[i], "y": self.y[i]}
class lowerCamelCase_ ( torch.nn.Module ):
'''simple docstring'''
def __init__( self : Tuple , _lowerCAmelCase : Dict=0 , _lowerCAmelCase : List[str]=0 , _lowerCAmelCase : str=False ):
super().__init__()
SCREAMING_SNAKE_CASE_ = torch.nn.Parameter(torch.tensor([2, 3] ).float() )
SCREAMING_SNAKE_CASE_ = torch.nn.Parameter(torch.tensor([2, 3] ).float() )
SCREAMING_SNAKE_CASE_ = True
def lowerCAmelCase_ ( self : Dict , _lowerCAmelCase : Union[str, Any]=None ):
if self.first_batch:
print(F"Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}" )
SCREAMING_SNAKE_CASE_ = False
return x * self.a[0] + self.b[0]
class lowerCamelCase_ ( torch.nn.Module ):
'''simple docstring'''
def __init__( self : Optional[int] , _lowerCAmelCase : Any=0 , _lowerCAmelCase : Any=0 , _lowerCAmelCase : Optional[Any]=False ):
super().__init__()
SCREAMING_SNAKE_CASE_ = torch.nn.Parameter(torch.tensor(_lowerCAmelCase ).float() )
SCREAMING_SNAKE_CASE_ = torch.nn.Parameter(torch.tensor(_lowerCAmelCase ).float() )
SCREAMING_SNAKE_CASE_ = True
def lowerCAmelCase_ ( self : Optional[Any] , _lowerCAmelCase : Optional[int]=None ):
if self.first_batch:
print(F"Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}" )
SCREAMING_SNAKE_CASE_ = False
return x * self.a + self.b
def UpperCAmelCase_ ( __UpperCAmelCase : Dict , __UpperCAmelCase : int = 16 ) -> Union[str, Any]:
from datasets import load_dataset
from transformers import AutoTokenizer
SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained('bert-base-cased' )
SCREAMING_SNAKE_CASE_ = {'train': 'tests/test_samples/MRPC/train.csv', 'validation': 'tests/test_samples/MRPC/dev.csv'}
SCREAMING_SNAKE_CASE_ = load_dataset('csv' , data_files=__UpperCAmelCase )
SCREAMING_SNAKE_CASE_ = datasets['train'].unique('label' )
SCREAMING_SNAKE_CASE_ = {v: i for i, v in enumerate(__UpperCAmelCase )}
def tokenize_function(__UpperCAmelCase : Optional[int] ):
# max_length=None => use the model max length (it's actually the default)
SCREAMING_SNAKE_CASE_ = tokenizer(
examples['sentence1'] , examples['sentence2'] , truncation=__UpperCAmelCase , max_length=__UpperCAmelCase , padding='max_length' )
if "label" in examples:
SCREAMING_SNAKE_CASE_ = [label_to_id[l] for l in examples['label']]
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
SCREAMING_SNAKE_CASE_ = datasets.map(
__UpperCAmelCase , batched=__UpperCAmelCase , remove_columns=['sentence1', 'sentence2', 'label'] , )
def collate_fn(__UpperCAmelCase : Dict ):
# On TPU it's best to pad everything to the same length or training will be very slow.
if accelerator.distributed_type == DistributedType.TPU:
return tokenizer.pad(__UpperCAmelCase , padding='max_length' , max_length=1_28 , return_tensors='pt' )
return tokenizer.pad(__UpperCAmelCase , padding='longest' , return_tensors='pt' )
# Instantiate dataloaders.
SCREAMING_SNAKE_CASE_ = DataLoader(tokenized_datasets['train'] , shuffle=__UpperCAmelCase , collate_fn=__UpperCAmelCase , batch_size=2 )
SCREAMING_SNAKE_CASE_ = DataLoader(tokenized_datasets['validation'] , shuffle=__UpperCAmelCase , collate_fn=__UpperCAmelCase , batch_size=1 )
return train_dataloader, eval_dataloader | 31 | 0 |
"""simple docstring"""
from __future__ import annotations
lowercase__ = [True] * 1000001
lowercase__ = 2
while i * i <= 1000000:
if seive[i]:
for j in range(i * i, 1000001, i):
lowercase__ = False
i += 1
def __magic_name__ ( _lowerCamelCase : int ):
return seive[n]
def __magic_name__ ( _lowerCamelCase : int ):
return any(digit in """02468""" for digit in str(_lowerCamelCase ) )
def __magic_name__ ( _lowerCamelCase : int = 1_0_0_0_0_0_0 ):
__a : str = [2] # result already includes the number 2.
for num in range(3 , limit + 1 , 2 ):
if is_prime(_lowerCamelCase ) and not contains_an_even_digit(_lowerCamelCase ):
__a : str = str(_lowerCamelCase )
__a : str = [int(str_num[j:] + str_num[:j] ) for j in range(len(_lowerCamelCase ) )]
if all(is_prime(_lowerCamelCase ) for i in list_nums ):
result.append(_lowerCamelCase )
return result
def __magic_name__ ( ):
return len(find_circular_primes() )
if __name__ == "__main__":
print(f'{len(find_circular_primes()) = }')
| 63 |
"""simple docstring"""
import os
def __magic_name__ ( _lowerCamelCase : Dict ):
__a : List[str] = len(grid[0] )
__a : int = len(_lowerCamelCase )
__a : Tuple = 0
__a : List[Any] = 0
__a : List[str] = 0
# Check vertically, horizontally, diagonally at the same time (only works
# for nxn grid)
for i in range(_lowerCamelCase ):
for j in range(n_rows - 3 ):
__a : List[Any] = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i]
__a : Tuple = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3]
# Left-to-right diagonal (\) product
if i < n_columns - 3:
__a : List[Any] = (
grid[i][j]
* grid[i + 1][j + 1]
* grid[i + 2][j + 2]
* grid[i + 3][j + 3]
)
# Right-to-left diagonal(/) product
if i > 2:
__a : List[Any] = (
grid[i][j]
* grid[i - 1][j + 1]
* grid[i - 2][j + 2]
* grid[i - 3][j + 3]
)
__a : str = max(
_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
if max_product > largest:
__a : Optional[Any] = max_product
return largest
def __magic_name__ ( ):
__a : Tuple = []
with open(os.path.dirname(_lowerCamelCase ) + """/grid.txt""" ) as file:
for line in file:
grid.append(line.strip("""\n""" ).split(""" """ ) )
__a : Tuple = [[int(_lowerCamelCase ) for i in grid[j]] for j in range(len(_lowerCamelCase ) )]
return largest_product(_lowerCamelCase )
if __name__ == "__main__":
print(solution())
| 63 | 1 |
def lowerCAmelCase_ ( _snake_case : list , _snake_case : int , _snake_case : int = 0 , _snake_case : int = 0 ) -> int:
'''simple docstring'''
__magic_name__ : List[str] = right or len(_snake_case ) - 1
if left > right:
return -1
elif list_data[left] == key:
return left
elif list_data[right] == key:
return right
else:
return search(_snake_case , _snake_case , left + 1 , right - 1 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 124 |
import os
import numpy
import onnx
def lowerCAmelCase_ ( _snake_case : Tuple , _snake_case : int ) -> List[str]:
'''simple docstring'''
__magic_name__ : Dict = a.name
__magic_name__ : Optional[Any] = b.name
__magic_name__ : Optional[int] = ""
__magic_name__ : int = ""
__magic_name__ : Any = a == b
__magic_name__ : int = name_a
__magic_name__ : List[str] = name_b
return res
def lowerCAmelCase_ ( _snake_case : Any , _snake_case : Dict , _snake_case : str ) -> str:
'''simple docstring'''
for i, input_name in enumerate(node_proto.input ):
if input_name == name:
node_proto.input.insert(_snake_case , _snake_case )
node_proto.input.pop(i + 1 )
if node_proto.op_type == "If":
_graph_replace_input_with(node_proto.attribute[0].g , _snake_case , _snake_case )
_graph_replace_input_with(node_proto.attribute[1].g , _snake_case , _snake_case )
if node_proto.op_type == "Loop":
_graph_replace_input_with(node_proto.attribute[0].g , _snake_case , _snake_case )
def lowerCAmelCase_ ( _snake_case : Any , _snake_case : Optional[Any] , _snake_case : str ) -> Any:
'''simple docstring'''
for n in graph_proto.node:
_node_replace_input_with(_snake_case , _snake_case , _snake_case )
def lowerCAmelCase_ ( _snake_case : List[str] , _snake_case : List[str] , _snake_case : Union[str, Any] ) -> List[Any]:
'''simple docstring'''
__magic_name__ : Tuple = list(model.graph.initializer )
__magic_name__ : Any = list(model_without_ext.graph.initializer )
for i, ref_i in ind_to_replace:
assert inits_with_data[i].name == inits[i].name
assert inits_with_data[ref_i].name == inits[ref_i].name
assert i > ref_i
__magic_name__ : Dict = inits[i].name
__magic_name__ : List[Any] = inits[ref_i].name
model_without_ext.graph.initializer.remove(inits[i] )
# for n in model.graph.node:
_graph_replace_input_with(model_without_ext.graph , _snake_case , _snake_case )
def lowerCAmelCase_ ( _snake_case : str ) -> List[str]:
'''simple docstring'''
__magic_name__ : Union[str, Any] = os.path.dirname(_snake_case )
__magic_name__ : List[str] = os.path.basename(_snake_case )
__magic_name__ : Tuple = onnx.load(os.path.join(_snake_case , _snake_case ) )
__magic_name__ : Dict = list(model.graph.initializer )
__magic_name__ : Dict = set()
__magic_name__ : Any = {}
__magic_name__ : Tuple = []
__magic_name__ : Optional[int] = 0
for i in range(len(_snake_case ) ):
if i in dup_set:
continue
for j in range(i + 1 , len(_snake_case ) ):
if j in dup_set:
continue
if _is_equal_tensor_proto(inits[i] , inits[j] ):
dup_set.add(_snake_case )
dup_set.add(_snake_case )
__magic_name__ : Optional[int] = inits[j].data_type
__magic_name__ : Any = numpy.prod(inits[j].dims )
if dtype == 1:
mem_size *= 4
elif dtype == 6:
mem_size *= 4
elif dtype == 7 or dtype == 11:
mem_size *= 8
else:
print("unexpected data type: " , _snake_case )
total_reduced_size += mem_size
__magic_name__ : Optional[int] = inits[i].name
__magic_name__ : Optional[Any] = inits[j].name
if name_i in dup_map:
dup_map[name_i].append(_snake_case )
else:
__magic_name__ : Union[str, Any] = [name_j]
ind_to_replace.append((j, i) )
print("total reduced size: " , total_reduced_size / 1024 / 1024 / 1024 , "GB" )
__magic_name__ : List[Any] = sorted(_snake_case )
_remove_dup_initializers_from_model(_snake_case , _snake_case , _snake_case )
__magic_name__ : List[str] = "optimized_" + model_file_name
__magic_name__ : Tuple = os.path.join(_snake_case , _snake_case )
onnx.save(_snake_case , _snake_case )
return new_model
| 124 | 1 |
"""simple docstring"""
import inspect
import unittest
class lowerCamelCase ( unittest.TestCase ):
'''simple docstring'''
def lowerCAmelCase_ ( self: Tuple ) -> Union[str, Any]:
try:
import diffusers # noqa: F401
except ImportError:
assert False
def lowerCAmelCase_ ( self: Dict ) -> Optional[int]:
import diffusers
from diffusers.dependency_versions_table import deps
snake_case_ :Union[str, Any] = inspect.getmembers(snake_case , inspect.isclass )
for cls_name, cls_module in all_classes:
if "dummy_" in cls_module.__module__:
for backend in cls_module._backends:
if backend == "k_diffusion":
snake_case_ :str = """k-diffusion"""
elif backend == "invisible_watermark":
snake_case_ :str = """invisible-watermark"""
assert backend in deps, f"""{backend} is not in the deps table!"""
| 310 |
"""simple docstring"""
import warnings
from typing import List, Optional, Tuple, Union
import numpy as np
import PIL
import torch
from ...models import UNetaDModel
from ...schedulers import RePaintScheduler
from ...utils import PIL_INTERPOLATION, logging, randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
__a = logging.get_logger(__name__) # pylint: disable=invalid-name
def A_ ( _lowercase ):
'''simple docstring'''
warnings.warn(
"""The preprocess method is deprecated and will be removed in a future version. Please"""
""" use VaeImageProcessor.preprocess instead""", _lowercase, )
if isinstance(_lowercase, torch.Tensor ):
return image
elif isinstance(_lowercase, PIL.Image.Image ):
snake_case_ :Tuple = [image]
if isinstance(image[0], PIL.Image.Image ):
snake_case_, snake_case_ :List[str] = image[0].size
snake_case_, snake_case_ :List[str] = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8
snake_case_ :Any = [np.array(i.resize((w, h), resample=PIL_INTERPOLATION["""lanczos"""] ) )[None, :] for i in image]
snake_case_ :Optional[Any] = np.concatenate(_lowercase, axis=0 )
snake_case_ :Optional[Any] = np.array(_lowercase ).astype(np.floataa ) / 255.0
snake_case_ :str = image.transpose(0, 3, 1, 2 )
snake_case_ :List[str] = 2.0 * image - 1.0
snake_case_ :Dict = torch.from_numpy(_lowercase )
elif isinstance(image[0], torch.Tensor ):
snake_case_ :int = torch.cat(_lowercase, dim=0 )
return image
def A_ ( _lowercase ):
'''simple docstring'''
if isinstance(_lowercase, torch.Tensor ):
return mask
elif isinstance(_lowercase, PIL.Image.Image ):
snake_case_ :Optional[Any] = [mask]
if isinstance(mask[0], PIL.Image.Image ):
snake_case_, snake_case_ :List[str] = mask[0].size
snake_case_, snake_case_ :Any = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32
snake_case_ :List[str] = [np.array(m.convert("""L""" ).resize((w, h), resample=PIL_INTERPOLATION["""nearest"""] ) )[None, :] for m in mask]
snake_case_ :Optional[Any] = np.concatenate(_lowercase, axis=0 )
snake_case_ :List[Any] = mask.astype(np.floataa ) / 255.0
snake_case_ :Dict = 0
snake_case_ :List[Any] = 1
snake_case_ :List[str] = torch.from_numpy(_lowercase )
elif isinstance(mask[0], torch.Tensor ):
snake_case_ :List[str] = torch.cat(_lowercase, dim=0 )
return mask
class lowerCamelCase ( _lowerCAmelCase ):
'''simple docstring'''
_A : UNetaDModel
_A : RePaintScheduler
def __init__( self: Optional[Any] , snake_case: Tuple , snake_case: int ) -> int:
super().__init__()
self.register_modules(unet=snake_case , scheduler=snake_case )
@torch.no_grad()
def __call__( self: Optional[int] , snake_case: Union[torch.Tensor, PIL.Image.Image] , snake_case: Union[torch.Tensor, PIL.Image.Image] , snake_case: int = 250 , snake_case: float = 0.0 , snake_case: int = 10 , snake_case: int = 10 , snake_case: Optional[Union[torch.Generator, List[torch.Generator]]] = None , snake_case: Optional[str] = "pil" , snake_case: bool = True , ) -> Union[ImagePipelineOutput, Tuple]:
snake_case_ :List[str] = image
snake_case_ :Optional[int] = _preprocess_image(snake_case )
snake_case_ :Union[str, Any] = original_image.to(device=self.device , dtype=self.unet.dtype )
snake_case_ :Tuple = _preprocess_mask(snake_case )
snake_case_ :List[str] = mask_image.to(device=self.device , dtype=self.unet.dtype )
snake_case_ :List[str] = original_image.shape[0]
# sample gaussian noise to begin the loop
if isinstance(snake_case , snake_case ) and len(snake_case ) != batch_size:
raise ValueError(
f"""You have passed a list of generators of length {len(snake_case )}, but requested an effective batch"""
f""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" )
snake_case_ :int = original_image.shape
snake_case_ :List[str] = randn_tensor(snake_case , generator=snake_case , device=self.device , dtype=self.unet.dtype )
# set step values
self.scheduler.set_timesteps(snake_case , snake_case , snake_case , self.device )
snake_case_ :Dict = eta
snake_case_ :Union[str, Any] = self.scheduler.timesteps[0] + 1
snake_case_ :str = generator[0] if isinstance(snake_case , snake_case ) else generator
for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ):
if t < t_last:
# predict the noise residual
snake_case_ :Any = self.unet(snake_case , snake_case ).sample
# compute previous image: x_t -> x_t-1
snake_case_ :Any = self.scheduler.step(snake_case , snake_case , snake_case , snake_case , snake_case , snake_case ).prev_sample
else:
# compute the reverse: x_t-1 -> x_t
snake_case_ :Optional[Any] = self.scheduler.undo_step(snake_case , snake_case , snake_case )
snake_case_ :Optional[int] = t
snake_case_ :List[str] = (image / 2 + 0.5).clamp(0 , 1 )
snake_case_ :Any = image.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
snake_case_ :Union[str, Any] = self.numpy_to_pil(snake_case )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=snake_case )
| 310 | 1 |
'''simple docstring'''
def a ( UpperCamelCase_ : int ) -> list:
snake_case__ =int(UpperCamelCase_ )
if n_element < 1:
snake_case__ =ValueError('a should be a positive number' )
raise my_error
snake_case__ =[1]
snake_case__ , snake_case__ , snake_case__ =(0, 0, 0)
snake_case__ =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__":
SCREAMING_SNAKE_CASE__ : str = input('''Enter the last number (nth term) of the Hamming Number Series: ''')
print('''Formula of Hamming Number Series => 2^i * 3^j * 5^k''')
SCREAMING_SNAKE_CASE__ : Dict = hamming(int(n))
print('''-----------------------------------------------------''')
print(f"""The list with nth numbers is: {hamming_numbers}""")
print('''-----------------------------------------------------''')
| 538 |
'''simple docstring'''
import argparse
import json
import os
from collections import OrderedDict
import numpy as np
import tensorflow as tf
import torch
def a ( UpperCamelCase_ : Any ) -> List[str]:
snake_case__ =os.path.join(args.tf_model_dir , 'parameters.json' )
snake_case__ =json.loads(open(UpperCamelCase_ ).read() )
if not params:
raise ValueError(
f"""It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file.""" )
if not args.output.endswith('.pt' ):
snake_case__ =args.output + '.pt'
snake_case__ =OrderedDict()
with tf.device('/CPU:0' ):
snake_case__ =tf.train.load_checkpoint(args.tf_model_dir )
snake_case__ =reader.get_variable_to_shape_map()
for key_name in shapes.keys():
snake_case__ =reader.get_tensor(UpperCamelCase_ ).astype(np.floataa )
if key_name.endswith('/adam_m' ) or key_name.endswith('/adam_v' ):
continue
if key_name.startswith('pasts/' ):
if key_name.startswith('pasts/mlp' ):
snake_case__ =int(key_name[9] )
elif key_name.startswith('pasts/out' ):
snake_case__ =8
snake_case__ ='model.sqout.%d.weight' % (player * 2) # enter to nn.Sequencial with Tanh, so 2 at a time
snake_case__ =vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix
snake_case__ =torch.tensor(UpperCamelCase_ )
elif key_name.startswith('model/moe' ):
snake_case__ =int(key_name[9:].split('/' )[0] )
if key_name.endswith('/switch_gating/kernel' ):
snake_case__ ='model.blocks.%d.feed_forward.mlp.router.classifier.weight' % player
snake_case__ =vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix
snake_case__ =torch.tensor(UpperCamelCase_ )
elif key_name.endswith('/softmlp/kernel' ):
snake_case__ ='model.blocks.%d.feed_forward.soft_bypass_mlp.weight' % player
snake_case__ =vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix
snake_case__ =torch.tensor(UpperCamelCase_ )
elif key_name.endswith('/wo/kernel' ) or key_name.endswith('/wi/kernel' ):
snake_case__ =key_name[-9:-7]
for i in range(16 ):
snake_case__ ='model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight' % (player, i, nlayer)
snake_case__ =(
vnp[i].transpose([1, 0] ).copy()
) # In Mesh-Tensorflow, it is one array, so it is divided
snake_case__ =torch.tensor(UpperCamelCase_ )
elif key_name.startswith('model/mlp' ):
snake_case__ =int(key_name[9:].split('/' )[0] )
if key_name.endswith('/p1/kernel' ):
snake_case__ ='model.blocks.%d.feed_forward.mlp.wi.weight' % player
snake_case__ =vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix
snake_case__ =torch.tensor(UpperCamelCase_ )
elif key_name.endswith('/p1/bias' ):
snake_case__ ='model.blocks.%d.feed_forward.mlp.wi.bias' % player
snake_case__ =vnp.copy() # same because it is one dimensional
snake_case__ =torch.tensor(UpperCamelCase_ )
elif key_name.endswith('/p2/kernel' ):
snake_case__ ='model.blocks.%d.feed_forward.mlp.wo.weight' % player
snake_case__ =vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix
snake_case__ =torch.tensor(UpperCamelCase_ )
elif key_name.endswith('/p2/bias' ):
snake_case__ ='model.blocks.%d.feed_forward.mlp.wo.bias' % player
snake_case__ =vnp.copy() # same because it is one dimensional
snake_case__ =torch.tensor(UpperCamelCase_ )
elif key_name.startswith('model/ln' ):
snake_case__ =int(key_name[8:].split('/' )[0] )
if key_name.endswith('/b' ):
snake_case__ ='model.blocks.%d.feed_forward.norm.bias' % player
snake_case__ =vnp.copy() # same because it is one dimensional
snake_case__ =torch.tensor(UpperCamelCase_ )
elif key_name.endswith('/g' ):
snake_case__ ='model.blocks.%d.feed_forward.norm.weight' % player
snake_case__ =vnp.copy() # same because it is one dimensional
snake_case__ =torch.tensor(UpperCamelCase_ )
elif key_name.startswith('model/att' ):
snake_case__ =int(key_name[9:].split('/' )[0] )
if key_name.endswith('/qkv/kernel' ):
snake_case__ =vnp.copy() # Compute same dimension as Mesh-tensorflow using einsum
snake_case__ =state[:, 0, :, :]
snake_case__ =state[:, 1, :, :]
snake_case__ =state[:, 2, :, :]
snake_case__ =(
state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]] )
.transpose([1, 0] )
.copy()
) # Mesh-Tensorflow is a diagonal matrix
snake_case__ =(
state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]] )
.transpose([1, 0] )
.copy()
) # Mesh-Tensorflow is a diagonal matrix
snake_case__ =(
state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]] )
.transpose([1, 0] )
.copy()
) # Mesh-Tensorflow is a diagonal matrix
snake_case__ ='model.blocks.%d.self_attn.self_attn.q_proj.weight' % player
snake_case__ =torch.tensor(UpperCamelCase_ )
snake_case__ ='model.blocks.%d.self_attn.self_attn.k_proj.weight' % player
snake_case__ =torch.tensor(UpperCamelCase_ )
snake_case__ ='model.blocks.%d.self_attn.self_attn.v_proj.weight' % player
snake_case__ =torch.tensor(UpperCamelCase_ )
elif key_name.endswith('/o/kernel' ):
snake_case__ ='model.blocks.%d.self_attn.self_attn.out_proj.weight' % player
snake_case__ =(
vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]] ).transpose([1, 0] ).copy()
) # Mesh-Tensorflow is a diagonal matrix
snake_case__ =torch.tensor(UpperCamelCase_ )
elif key_name.startswith('model/an' ):
snake_case__ =int(key_name[8:].split('/' )[0] )
if key_name.endswith('/b' ):
snake_case__ ='model.blocks.%d.self_attn.norm.bias' % player
snake_case__ =vnp.copy() # same because it is one dimensional
snake_case__ =torch.tensor(UpperCamelCase_ )
elif key_name.endswith('/g' ):
snake_case__ ='model.blocks.%d.self_attn.norm.weight' % player
snake_case__ =vnp.copy() # same because it is one dimensional
snake_case__ =torch.tensor(UpperCamelCase_ )
elif (
key_name.startswith('model/wte' )
or key_name.startswith('model/wpe' )
or key_name.startswith('model/ete' )
):
snake_case__ ={'wte': 'embed_tokens', 'wpe': 'position_embeddings', 'ete': 'extra_position_embeddings'}[
key_name[-3:]
]
snake_case__ ='model.%s.weight' % nlayer
snake_case__ =vnp.copy() # same in embedded
snake_case__ =torch.tensor(UpperCamelCase_ )
if key_name.startswith('model/wte' ):
snake_case__ ='lm_head.weight'
snake_case__ =vnp.copy() # same in embedded
snake_case__ =torch.tensor(UpperCamelCase_ )
elif key_name.startswith('model/wob' ):
snake_case__ ='final_logits_bias'
snake_case__ =vnp.copy() # same in embedded
snake_case__ =state.reshape((1, -1) )
snake_case__ =torch.tensor(UpperCamelCase_ )
elif key_name == "model/dense/kernel":
snake_case__ ='model.last_project.weight'
snake_case__ =vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix
snake_case__ =torch.tensor(UpperCamelCase_ )
elif key_name == "model/dense_1/bias":
snake_case__ ='model.last_project.bias'
snake_case__ =vnp.copy() # same because it is one dimensional
snake_case__ =torch.tensor(UpperCamelCase_ )
torch.save(UpperCamelCase_ , args.output )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE__ : int = argparse.ArgumentParser(
description='''model converter.''', formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument('''--tf_model_dir''', metavar='''PATH''', type=str, required=True, help='''import model''')
parser.add_argument('''--output''', metavar='''PATH''', type=str, required=True, help='''output model''')
SCREAMING_SNAKE_CASE__ : str = parser.parse_args()
convert_tf_gptsan_to_pt(args)
| 538 | 1 |
import os
__lowerCAmelCase : Dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = 0
__magic_name__ = 0
while index < len(A_ ) - 1:
__magic_name__ = SYMBOLS[numerals[index]]
__magic_name__ = SYMBOLS[numerals[index + 1]]
if current_value < next_value:
total_value -= current_value
else:
total_value += current_value
index += 1
total_value += SYMBOLS[numerals[index]]
return total_value
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = """"""
__magic_name__ = num // 1000
numerals += m_count * "M"
num %= 1000
__magic_name__ = num // 100
if c_count == 9:
numerals += "CM"
c_count -= 9
elif c_count == 4:
numerals += "CD"
c_count -= 4
if c_count >= 5:
numerals += "D"
c_count -= 5
numerals += c_count * "C"
num %= 100
__magic_name__ = num // 10
if x_count == 9:
numerals += "XC"
x_count -= 9
elif x_count == 4:
numerals += "XL"
x_count -= 4
if x_count >= 5:
numerals += "L"
x_count -= 5
numerals += x_count * "X"
num %= 10
if num == 9:
numerals += "IX"
num -= 9
elif num == 4:
numerals += "IV"
num -= 4
if num >= 5:
numerals += "V"
num -= 5
numerals += num * "I"
return numerals
def a__ ( A_ = "/p089_roman.txt" ):
'''simple docstring'''
__magic_name__ = 0
with open(os.path.dirname(A_ ) + roman_numerals_filename ) as filea:
__magic_name__ = filea.readlines()
for line in lines:
__magic_name__ = line.strip()
__magic_name__ = parse_roman_numerals(A_ )
__magic_name__ = generate_roman_numerals(A_ )
savings += len(A_ ) - len(A_ )
return savings
if __name__ == "__main__":
print(F'''{solution() = }''')
| 76 |
import functools
import operator
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCAmelCase : Optional[Any] = logging.get_logger(__name__)
__lowerCAmelCase : List[Any] = {
'asapp/sew-d-tiny-100k': 'https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json',
# See all SEW-D models at https://huggingface.co/models?filter=sew-d
}
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """sew-d"""
def __init__( self : List[str] , UpperCamelCase__ : Tuple=32 , UpperCamelCase__ : Optional[int]=768 , UpperCamelCase__ : Tuple=12 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : int=3072 , UpperCamelCase__ : Tuple=2 , UpperCamelCase__ : List[Any]=512 , UpperCamelCase__ : Any=256 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Dict=True , UpperCamelCase__ : str=("p2c", "c2p") , UpperCamelCase__ : List[Any]="layer_norm" , UpperCamelCase__ : int="gelu_python" , UpperCamelCase__ : Optional[int]=0.1 , UpperCamelCase__ : Tuple=0.1 , UpperCamelCase__ : List[Any]=0.1 , UpperCamelCase__ : int=0.0 , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : List[Any]=0.02 , UpperCamelCase__ : Optional[int]=1E-7 , UpperCamelCase__ : List[Any]=1E-5 , UpperCamelCase__ : List[str]="group" , UpperCamelCase__ : Optional[int]="gelu" , UpperCamelCase__ : Tuple=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , UpperCamelCase__ : str=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , UpperCamelCase__ : Optional[Any]=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , UpperCamelCase__ : Optional[Any]=False , UpperCamelCase__ : Optional[int]=128 , UpperCamelCase__ : Tuple=16 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Dict=0.05 , UpperCamelCase__ : str=10 , UpperCamelCase__ : Tuple=2 , UpperCamelCase__ : Dict=0.0 , UpperCamelCase__ : Dict=10 , UpperCamelCase__ : Union[str, Any]=0 , UpperCamelCase__ : List[Any]="mean" , UpperCamelCase__ : int=False , UpperCamelCase__ : Optional[int]=False , UpperCamelCase__ : Optional[int]=256 , UpperCamelCase__ : List[str]=0 , UpperCamelCase__ : Union[str, Any]=1 , UpperCamelCase__ : List[Any]=2 , **UpperCamelCase__ : str , ) -> Dict:
"""simple docstring"""
super().__init__(**UpperCamelCase__ , pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ )
__magic_name__ = hidden_size
__magic_name__ = feat_extract_norm
__magic_name__ = feat_extract_activation
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = conv_bias
__magic_name__ = num_conv_pos_embeddings
__magic_name__ = num_conv_pos_embedding_groups
__magic_name__ = len(self.conv_dim )
__magic_name__ = num_hidden_layers
__magic_name__ = intermediate_size
__magic_name__ = squeeze_factor
__magic_name__ = max_position_embeddings
__magic_name__ = position_buckets
__magic_name__ = share_att_key
__magic_name__ = relative_attention
__magic_name__ = norm_rel_ebd
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = hidden_act
__magic_name__ = num_attention_heads
__magic_name__ = hidden_dropout
__magic_name__ = attention_dropout
__magic_name__ = activation_dropout
__magic_name__ = feat_proj_dropout
__magic_name__ = final_dropout
__magic_name__ = layer_norm_eps
__magic_name__ = feature_layer_norm_eps
__magic_name__ = initializer_range
__magic_name__ = vocab_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)`,"""
F'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)'''
F'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' )
# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
__magic_name__ = apply_spec_augment
__magic_name__ = mask_time_prob
__magic_name__ = mask_time_length
__magic_name__ = mask_time_min_masks
__magic_name__ = mask_feature_prob
__magic_name__ = mask_feature_length
__magic_name__ = mask_feature_min_masks
# ctc loss
__magic_name__ = ctc_loss_reduction
__magic_name__ = ctc_zero_infinity
# sequence classification
__magic_name__ = use_weighted_layer_sum
__magic_name__ = classifier_proj_size
@property
def _lowercase ( self : Union[str, Any] ) -> str:
"""simple docstring"""
return functools.reduce(operator.mul , self.conv_stride , 1 )
| 76 | 1 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowerCAmelCase: List[str] = logging.get_logger(__name__)
lowerCAmelCase: Dict = {
'google/vivit-b-16x2-kinetics400': (
'https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json'
),
# See all Vivit models at https://huggingface.co/models?filter=vivit
}
class a__( lowerCamelCase__ ):
lowercase__ = """vivit"""
def __init__( self : List[Any] , __snake_case : int=2_24 , __snake_case : List[Any]=32 , __snake_case : Dict=[2, 16, 16] , __snake_case : int=3 , __snake_case : Optional[int]=7_68 , __snake_case : Tuple=12 , __snake_case : Dict=12 , __snake_case : int=30_72 , __snake_case : Optional[Any]="gelu_fast" , __snake_case : str=0.0 , __snake_case : Tuple=0.0 , __snake_case : Optional[Any]=0.02 , __snake_case : Optional[Any]=1e-0_6 , __snake_case : List[Any]=True , **__snake_case : Dict , ):
a : Any = hidden_size
a : Dict = num_hidden_layers
a : Optional[int] = num_attention_heads
a : Tuple = intermediate_size
a : List[Any] = hidden_act
a : List[Any] = hidden_dropout_prob
a : Union[str, Any] = attention_probs_dropout_prob
a : str = initializer_range
a : Optional[int] = layer_norm_eps
a : Optional[Any] = image_size
a : int = num_frames
a : List[str] = tubelet_size
a : Optional[Any] = num_channels
a : Dict = qkv_bias
super().__init__(**__snake_case ) | 526 |
'''simple docstring'''
from typing import Callable, Optional
from .. import Features
from ..packaged_modules.generator.generator import Generator
from .abc import AbstractDatasetInputStream
class a__( lowerCamelCase__ ):
def __init__( self : int , __snake_case : Callable , __snake_case : Optional[Features] = None , __snake_case : str = None , __snake_case : bool = False , __snake_case : bool = False , __snake_case : Optional[dict] = None , __snake_case : Optional[int] = None , **__snake_case : Optional[int] , ):
super().__init__(
features=__snake_case , cache_dir=__snake_case , keep_in_memory=__snake_case , streaming=__snake_case , num_proc=__snake_case , **__snake_case , )
a : List[Any] = Generator(
cache_dir=__snake_case , features=__snake_case , generator=__snake_case , gen_kwargs=__snake_case , **__snake_case , )
def lowercase_ ( self : Any ):
# Build iterable dataset
if self.streaming:
a : Optional[int] = self.builder.as_streaming_dataset(split='train' )
# Build regular (map-style) dataset
else:
a : List[Any] = None
a : Any = None
a : Optional[int] = None
a : List[str] = None
self.builder.download_and_prepare(
download_config=__snake_case , download_mode=__snake_case , verification_mode=__snake_case , base_path=__snake_case , num_proc=self.num_proc , )
a : Dict = self.builder.as_dataset(
split='train' , verification_mode=__snake_case , in_memory=self.keep_in_memory )
return dataset | 526 | 1 |
import argparse
import json
from pathlib import Path
import requests
import timm
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import DeiTImageProcessor, ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel
from transformers.utils import logging
logging.set_verbosity_info()
SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__)
def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Optional[int] , lowerCAmelCase: int=False ) -> Any:
_UpperCAmelCase : Any = []
for i in range(config.num_hidden_layers ):
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
rename_keys.append((F'blocks.{i}.norm1.weight', F'vit.encoder.layer.{i}.layernorm_before.weight') )
rename_keys.append((F'blocks.{i}.norm1.bias', F'vit.encoder.layer.{i}.layernorm_before.bias') )
rename_keys.append((F'blocks.{i}.attn.proj.weight', F'vit.encoder.layer.{i}.attention.output.dense.weight') )
rename_keys.append((F'blocks.{i}.attn.proj.bias', F'vit.encoder.layer.{i}.attention.output.dense.bias') )
rename_keys.append((F'blocks.{i}.norm2.weight', F'vit.encoder.layer.{i}.layernorm_after.weight') )
rename_keys.append((F'blocks.{i}.norm2.bias', F'vit.encoder.layer.{i}.layernorm_after.bias') )
rename_keys.append((F'blocks.{i}.mlp.fc1.weight', F'vit.encoder.layer.{i}.intermediate.dense.weight') )
rename_keys.append((F'blocks.{i}.mlp.fc1.bias', F'vit.encoder.layer.{i}.intermediate.dense.bias') )
rename_keys.append((F'blocks.{i}.mlp.fc2.weight', F'vit.encoder.layer.{i}.output.dense.weight') )
rename_keys.append((F'blocks.{i}.mlp.fc2.bias', F'vit.encoder.layer.{i}.output.dense.bias') )
# projection layer + position embeddings
rename_keys.extend(
[
("cls_token", "vit.embeddings.cls_token"),
("patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight"),
("patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias"),
("pos_embed", "vit.embeddings.position_embeddings"),
] )
if base_model:
# layernorm + pooler
rename_keys.extend(
[
("norm.weight", "layernorm.weight"),
("norm.bias", "layernorm.bias"),
("pre_logits.fc.weight", "pooler.dense.weight"),
("pre_logits.fc.bias", "pooler.dense.bias"),
] )
# if just the base model, we should remove "vit" from all keys that start with "vit"
_UpperCAmelCase : Dict = [(pair[0], pair[1][4:]) if pair[1].startswith("vit" ) else pair for pair in rename_keys]
else:
# layernorm + classification head
rename_keys.extend(
[
("norm.weight", "vit.layernorm.weight"),
("norm.bias", "vit.layernorm.bias"),
("head.weight", "classifier.weight"),
("head.bias", "classifier.bias"),
] )
return rename_keys
def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Tuple , lowerCAmelCase: List[str] , lowerCAmelCase: Any=False ) -> int:
for i in range(config.num_hidden_layers ):
if base_model:
_UpperCAmelCase : List[str] = ""
else:
_UpperCAmelCase : List[Any] = "vit."
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
_UpperCAmelCase : List[str] = state_dict.pop(F'blocks.{i}.attn.qkv.weight' )
_UpperCAmelCase : int = state_dict.pop(F'blocks.{i}.attn.qkv.bias' )
# next, add query, keys and values (in that order) to the state dict
_UpperCAmelCase : int = in_proj_weight[
: config.hidden_size, :
]
_UpperCAmelCase : Optional[Any] = in_proj_bias[: config.hidden_size]
_UpperCAmelCase : int = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
_UpperCAmelCase : int = in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
_UpperCAmelCase : Dict = in_proj_weight[
-config.hidden_size :, :
]
_UpperCAmelCase : Optional[Any] = in_proj_bias[-config.hidden_size :]
def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Optional[int] ) -> Optional[int]:
_UpperCAmelCase : Optional[int] = ["head.weight", "head.bias"]
for k in ignore_keys:
state_dict.pop(lowerCAmelCase , lowerCAmelCase )
def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Any , lowerCAmelCase: Optional[Any] , lowerCAmelCase: Optional[Any] ) -> Union[str, Any]:
_UpperCAmelCase : Optional[Any] = dct.pop(lowerCAmelCase )
_UpperCAmelCase : Dict = val
def __SCREAMING_SNAKE_CASE ( ) -> Dict:
_UpperCAmelCase : Tuple = "http://images.cocodataset.org/val2017/000000039769.jpg"
_UpperCAmelCase : List[str] = Image.open(requests.get(lowerCAmelCase , stream=lowerCAmelCase ).raw )
return im
@torch.no_grad()
def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Any , lowerCAmelCase: Any ) -> List[Any]:
_UpperCAmelCase : Optional[int] = ViTConfig()
_UpperCAmelCase : str = False
# dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size
if vit_name[-5:] == "in21k":
_UpperCAmelCase : Any = True
_UpperCAmelCase : Tuple = int(vit_name[-12:-10] )
_UpperCAmelCase : List[Any] = int(vit_name[-9:-6] )
else:
_UpperCAmelCase : Optional[int] = 1000
_UpperCAmelCase : Optional[int] = "huggingface/label-files"
_UpperCAmelCase : Optional[Any] = "imagenet-1k-id2label.json"
_UpperCAmelCase : List[Any] = json.load(open(hf_hub_download(lowerCAmelCase , lowerCAmelCase , repo_type="dataset" ) , "r" ) )
_UpperCAmelCase : List[Any] = {int(lowerCAmelCase ): v for k, v in idalabel.items()}
_UpperCAmelCase : Union[str, Any] = idalabel
_UpperCAmelCase : Tuple = {v: k for k, v in idalabel.items()}
_UpperCAmelCase : Tuple = int(vit_name[-6:-4] )
_UpperCAmelCase : Optional[Any] = int(vit_name[-3:] )
# size of the architecture
if "deit" in vit_name:
if vit_name[9:].startswith("tiny" ):
_UpperCAmelCase : int = 192
_UpperCAmelCase : str = 768
_UpperCAmelCase : Dict = 12
_UpperCAmelCase : int = 3
elif vit_name[9:].startswith("small" ):
_UpperCAmelCase : List[str] = 384
_UpperCAmelCase : Any = 1536
_UpperCAmelCase : Union[str, Any] = 12
_UpperCAmelCase : Optional[Any] = 6
else:
pass
else:
if vit_name[4:].startswith("small" ):
_UpperCAmelCase : List[str] = 768
_UpperCAmelCase : Union[str, Any] = 2304
_UpperCAmelCase : Optional[Any] = 8
_UpperCAmelCase : List[Any] = 8
elif vit_name[4:].startswith("base" ):
pass
elif vit_name[4:].startswith("large" ):
_UpperCAmelCase : Any = 1024
_UpperCAmelCase : Optional[int] = 4096
_UpperCAmelCase : Tuple = 24
_UpperCAmelCase : int = 16
elif vit_name[4:].startswith("huge" ):
_UpperCAmelCase : Tuple = 1280
_UpperCAmelCase : Optional[Any] = 5120
_UpperCAmelCase : List[Any] = 32
_UpperCAmelCase : Dict = 16
# load original model from timm
_UpperCAmelCase : Optional[Any] = timm.create_model(lowerCAmelCase , pretrained=lowerCAmelCase )
timm_model.eval()
# load state_dict of original model, remove and rename some keys
_UpperCAmelCase : str = timm_model.state_dict()
if base_model:
remove_classification_head_(lowerCAmelCase )
_UpperCAmelCase : str = create_rename_keys(lowerCAmelCase , lowerCAmelCase )
for src, dest in rename_keys:
rename_key(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )
read_in_q_k_v(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )
# load HuggingFace model
if vit_name[-5:] == "in21k":
_UpperCAmelCase : int = ViTModel(lowerCAmelCase ).eval()
else:
_UpperCAmelCase : Optional[Any] = ViTForImageClassification(lowerCAmelCase ).eval()
model.load_state_dict(lowerCAmelCase )
# Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor
if "deit" in vit_name:
_UpperCAmelCase : Any = DeiTImageProcessor(size=config.image_size )
else:
_UpperCAmelCase : Tuple = ViTImageProcessor(size=config.image_size )
_UpperCAmelCase : Any = image_processor(images=prepare_img() , return_tensors="pt" )
_UpperCAmelCase : Optional[int] = encoding["pixel_values"]
_UpperCAmelCase : int = model(lowerCAmelCase )
if base_model:
_UpperCAmelCase : str = timm_model.forward_features(lowerCAmelCase )
assert timm_pooled_output.shape == outputs.pooler_output.shape
assert torch.allclose(lowerCAmelCase , outputs.pooler_output , atol=1E-3 )
else:
_UpperCAmelCase : Union[str, Any] = timm_model(lowerCAmelCase )
assert timm_logits.shape == outputs.logits.shape
assert torch.allclose(lowerCAmelCase , outputs.logits , atol=1E-3 )
Path(lowerCAmelCase ).mkdir(exist_ok=lowerCAmelCase )
print(F'Saving model {vit_name} to {pytorch_dump_folder_path}' )
model.save_pretrained(lowerCAmelCase )
print(F'Saving image processor to {pytorch_dump_folder_path}' )
image_processor.save_pretrained(lowerCAmelCase )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--vit_name',
default='vit_base_patch16_224',
type=str,
help='Name of the ViT 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.'
)
SCREAMING_SNAKE_CASE_ = parser.parse_args()
convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
| 467 |
import gc
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel
from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings
from diffusers.utils import load_numpy, slow, torch_device
from diffusers.utils.testing_utils import require_torch_gpu
SCREAMING_SNAKE_CASE_ = False
class a ( unittest.TestCase ):
def _UpperCAmelCase ( self ):
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
@property
def _UpperCAmelCase ( self ):
'''simple docstring'''
return 12
@property
def _UpperCAmelCase ( self ):
'''simple docstring'''
return 12
@property
def _UpperCAmelCase ( self ):
'''simple docstring'''
return 32
@property
def _UpperCAmelCase ( self ):
'''simple docstring'''
torch.manual_seed(0 )
_UpperCAmelCase : Optional[int] = VQModel(
block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=3 , num_vq_embeddings=self.num_embed , vq_embed_dim=3 , )
return model
@property
def _UpperCAmelCase ( self ):
'''simple docstring'''
_UpperCAmelCase : List[str] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )
return tokenizer
@property
def _UpperCAmelCase ( self ):
'''simple docstring'''
torch.manual_seed(0 )
_UpperCAmelCase : int = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=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=1000 , )
return CLIPTextModel(A_ )
@property
def _UpperCAmelCase ( self ):
'''simple docstring'''
torch.manual_seed(0 )
_UpperCAmelCase : Optional[int] = 12
_UpperCAmelCase : Union[str, Any] = 12
_UpperCAmelCase : str = {
"attention_bias": True,
"cross_attention_dim": 32,
"attention_head_dim": height * width,
"num_attention_heads": 1,
"num_vector_embeds": self.num_embed,
"num_embeds_ada_norm": self.num_embeds_ada_norm,
"norm_num_groups": 32,
"sample_size": width,
"activation_fn": "geglu-approximate",
}
_UpperCAmelCase : Any = TransformeraDModel(**A_ )
return model
def _UpperCAmelCase ( self ):
'''simple docstring'''
_UpperCAmelCase : Dict = "cpu"
_UpperCAmelCase : List[str] = self.dummy_vqvae
_UpperCAmelCase : Any = self.dummy_text_encoder
_UpperCAmelCase : Optional[int] = self.dummy_tokenizer
_UpperCAmelCase : List[Any] = self.dummy_transformer
_UpperCAmelCase : Union[str, Any] = VQDiffusionScheduler(self.num_embed )
_UpperCAmelCase : Union[str, Any] = LearnedClassifierFreeSamplingEmbeddings(learnable=A_ )
_UpperCAmelCase : Optional[Any] = VQDiffusionPipeline(
vqvae=A_ , text_encoder=A_ , tokenizer=A_ , transformer=A_ , scheduler=A_ , learned_classifier_free_sampling_embeddings=A_ , )
_UpperCAmelCase : Optional[int] = pipe.to(A_ )
pipe.set_progress_bar_config(disable=A_ )
_UpperCAmelCase : Union[str, Any] = "teddy bear playing in the pool"
_UpperCAmelCase : Union[str, Any] = torch.Generator(device=A_ ).manual_seed(0 )
_UpperCAmelCase : List[Any] = pipe([prompt] , generator=A_ , num_inference_steps=2 , output_type="np" )
_UpperCAmelCase : List[Any] = output.images
_UpperCAmelCase : Dict = torch.Generator(device=A_ ).manual_seed(0 )
_UpperCAmelCase : Union[str, Any] = pipe(
[prompt] , generator=A_ , output_type="np" , return_dict=A_ , num_inference_steps=2 )[0]
_UpperCAmelCase : Optional[Any] = image[0, -3:, -3:, -1]
_UpperCAmelCase : int = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 24, 24, 3)
_UpperCAmelCase : List[str] = np.array([0.65_51, 0.61_68, 0.50_08, 0.56_76, 0.56_59, 0.42_95, 0.60_73, 0.55_99, 0.49_92] )
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 _UpperCAmelCase ( self ):
'''simple docstring'''
_UpperCAmelCase : Optional[int] = "cpu"
_UpperCAmelCase : Tuple = self.dummy_vqvae
_UpperCAmelCase : Optional[Any] = self.dummy_text_encoder
_UpperCAmelCase : List[str] = self.dummy_tokenizer
_UpperCAmelCase : List[Any] = self.dummy_transformer
_UpperCAmelCase : Dict = VQDiffusionScheduler(self.num_embed )
_UpperCAmelCase : Dict = LearnedClassifierFreeSamplingEmbeddings(
learnable=A_ , hidden_size=self.text_embedder_hidden_size , length=tokenizer.model_max_length )
_UpperCAmelCase : Optional[int] = VQDiffusionPipeline(
vqvae=A_ , text_encoder=A_ , tokenizer=A_ , transformer=A_ , scheduler=A_ , learned_classifier_free_sampling_embeddings=A_ , )
_UpperCAmelCase : Union[str, Any] = pipe.to(A_ )
pipe.set_progress_bar_config(disable=A_ )
_UpperCAmelCase : int = "teddy bear playing in the pool"
_UpperCAmelCase : Dict = torch.Generator(device=A_ ).manual_seed(0 )
_UpperCAmelCase : int = pipe([prompt] , generator=A_ , num_inference_steps=2 , output_type="np" )
_UpperCAmelCase : Union[str, Any] = output.images
_UpperCAmelCase : Optional[Any] = torch.Generator(device=A_ ).manual_seed(0 )
_UpperCAmelCase : int = pipe(
[prompt] , generator=A_ , output_type="np" , return_dict=A_ , num_inference_steps=2 )[0]
_UpperCAmelCase : Any = image[0, -3:, -3:, -1]
_UpperCAmelCase : Optional[int] = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 24, 24, 3)
_UpperCAmelCase : Union[str, Any] = np.array([0.66_93, 0.60_75, 0.49_59, 0.57_01, 0.55_83, 0.43_33, 0.61_71, 0.56_84, 0.49_88] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 2.0
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
@slow
@require_torch_gpu
class a ( unittest.TestCase ):
def _UpperCAmelCase ( self ):
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def _UpperCAmelCase ( self ):
'''simple docstring'''
_UpperCAmelCase : Optional[Any] = load_numpy(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
"/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy" )
_UpperCAmelCase : Dict = VQDiffusionPipeline.from_pretrained("microsoft/vq-diffusion-ithq" )
_UpperCAmelCase : Optional[int] = pipeline.to(A_ )
pipeline.set_progress_bar_config(disable=A_ )
# requires GPU generator for gumbel softmax
# don't use GPU generator in tests though
_UpperCAmelCase : Optional[int] = torch.Generator(device=A_ ).manual_seed(0 )
_UpperCAmelCase : Optional[Any] = pipeline(
"teddy bear playing in the pool" , num_images_per_prompt=1 , generator=A_ , output_type="np" , )
_UpperCAmelCase : str = output.images[0]
assert image.shape == (256, 256, 3)
assert np.abs(expected_image - image ).max() < 2.0
| 467 | 1 |
from __future__ import annotations
from collections.abc import Callable
from typing import Any, Generic, TypeVar
_snake_case : Union[str, Any] = TypeVar("T")
class a (Generic[T] ):
"""simple docstring"""
def __init__( self : Tuple , lowerCamelCase : list[T] , lowerCamelCase : Callable[[T, T], T] ) -> None:
__snake_case : Any | T = None
__snake_case : int = len(lowerCamelCase )
__snake_case : list[T] = [any_type for _ in range(self.N )] + arr
__snake_case : Tuple = fnc
self.build()
def __snake_case ( self : Dict ) -> None:
for p in range(self.N - 1 , 0 , -1 ):
__snake_case : List[str] = self.fn(self.st[p * 2] , self.st[p * 2 + 1] )
def __snake_case ( self : Optional[Any] , lowerCamelCase : int , lowerCamelCase : T ) -> None:
p += self.N
__snake_case : str = v
while p > 1:
__snake_case : Dict = p // 2
__snake_case : Optional[Any] = self.fn(self.st[p * 2] , self.st[p * 2 + 1] )
def __snake_case ( self : List[str] , lowerCamelCase : int , lowerCamelCase : int ) -> T | None: # noqa: E741
__snake_case , __snake_case : Optional[int] = l + self.N, r + self.N
__snake_case : T | None = None
while l <= r:
if l % 2 == 1:
__snake_case : Optional[Any] = self.st[l] if res is None else self.fn(lowerCamelCase , self.st[l] )
if r % 2 == 0:
__snake_case : int = self.st[r] if res is None else self.fn(lowerCamelCase , self.st[r] )
__snake_case , __snake_case : List[str] = (l + 1) // 2, (r - 1) // 2
return res
if __name__ == "__main__":
from functools import reduce
_snake_case : Union[str, Any] = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12]
_snake_case : Dict = {
0: 7,
1: 2,
2: 6,
3: -14,
4: 5,
5: 4,
6: 7,
7: -10,
8: 9,
9: 10,
10: 12,
11: 1,
}
_snake_case : Optional[Any] = SegmentTree(test_array, min)
_snake_case : Optional[Any] = SegmentTree(test_array, max)
_snake_case : Optional[Any] = SegmentTree(test_array, lambda a, b: a + b)
def lowerCAmelCase_ ( ):
for i in range(len(__lowerCamelCase ) ):
for j in range(__lowerCamelCase , len(__lowerCamelCase ) ):
__snake_case : Optional[int] = reduce(__lowerCamelCase , test_array[i : j + 1] )
__snake_case : List[Any] = reduce(__lowerCamelCase , test_array[i : j + 1] )
__snake_case : Union[str, Any] = reduce(lambda __lowerCamelCase , __lowerCamelCase : a + b , test_array[i : j + 1] )
assert min_range == min_segment_tree.query(__lowerCamelCase , __lowerCamelCase )
assert max_range == max_segment_tree.query(__lowerCamelCase , __lowerCamelCase )
assert sum_range == sum_segment_tree.query(__lowerCamelCase , __lowerCamelCase )
test_all_segments()
for index, value in test_updates.items():
_snake_case : List[Any] = value
min_segment_tree.update(index, value)
max_segment_tree.update(index, value)
sum_segment_tree.update(index, value)
test_all_segments()
| 81 |
import argparse
import logging
import os
import datasets
import tensorflow as tf
from transformers import AutoTokenizer
_snake_case : Union[str, Any] = logging.getLogger(__name__)
def lowerCAmelCase_ ( ):
__snake_case : int = argparse.ArgumentParser(
description="Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset." )
parser.add_argument(
"--dataset_name" , type=__lowerCamelCase , default="wikitext" , help="Name of the training. Explore datasets at: hf.co/datasets." , )
parser.add_argument(
"--dataset_config" , type=__lowerCamelCase , default="wikitext-103-raw-v1" , help="Configuration name of the dataset." )
parser.add_argument(
"--tokenizer_name_or_path" , type=__lowerCamelCase , default="sayakpaul/unigram-tokenizer-wikitext" , help="Tokenizer identifier. Can be a local filepath or a Hub identifier." , )
parser.add_argument(
"--shard_size" , type=__lowerCamelCase , default=1_0_0_0 , help="Number of entries to go in a single shard." , )
parser.add_argument("--split" , type=__lowerCamelCase , default="train" , choices=["train", "test", "validation"] )
parser.add_argument(
"--limit" , default=__lowerCamelCase , type=__lowerCamelCase , help="Limit the number of shards (used for debugging)." , )
parser.add_argument(
"--max_length" , type=__lowerCamelCase , default=5_1_2 , help="Maximum sequence length. For training on TPUs, it helps to have a maximum"
" sequence length that is a multiple of 8." , )
parser.add_argument(
"--output_dir" , default="tf-tpu" , type=__lowerCamelCase , help="Output directory where the TFRecord shards will be saved. If the"
" path is appended with `gs://` ('gs://tf-tpu', for example) then the TFRecord"
" shards will be directly saved to a Google Cloud Storage bucket." , )
__snake_case : List[str] = parser.parse_args()
return args
def lowerCAmelCase_ ( __lowerCamelCase ):
def fn(__lowerCamelCase ):
return tokenizer(examples["text"] )
return fn
def lowerCAmelCase_ ( __lowerCamelCase ):
__snake_case : Tuple = []
for i in range(len(tokenized_data["input_ids"] ) ):
__snake_case : Tuple = {
"input_ids": tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data["input_ids"][i] ) ),
"attention_mask": tf.train.Feature(
intaa_list=tf.train.IntaaList(value=tokenized_data["attention_mask"][i] ) ),
}
__snake_case : List[Any] = tf.train.Features(feature=__lowerCamelCase )
__snake_case : str = tf.train.Example(features=__lowerCamelCase )
__snake_case : List[str] = example.SerializeToString()
records.append(__lowerCamelCase )
return records
def lowerCAmelCase_ ( __lowerCamelCase ):
__snake_case : Optional[int] = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split )
if args.limit is not None:
__snake_case : Optional[Any] = min(len(__lowerCamelCase ) , args.limit )
__snake_case : Dict = dataset.select(range(__lowerCamelCase ) )
print(F'Limiting the dataset to {args.limit} entries.' )
__snake_case : Dict = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path )
# Handle output directory creation.
# For serializing into a Google Cloud Storage Bucket, one needs to first
# create a bucket.
if "gs" not in args.output_dir:
if not os.path.exists(args.output_dir ):
os.makedirs(args.output_dir )
__snake_case : Dict = os.path.join(args.output_dir , args.split )
if not os.path.exists(__lowerCamelCase ):
os.makedirs(__lowerCamelCase )
else:
__snake_case : str = os.path.join(args.output_dir , args.split )
# Tokenize the whole dataset at once.
__snake_case : Any = tokenize_function(__lowerCamelCase )
__snake_case : Optional[Any] = dataset.map(__lowerCamelCase , batched=__lowerCamelCase , num_proc=4 , remove_columns=["text"] )
# We need to concatenate all our texts together, and then split the result
# into chunks of a fixed size, which we will call block_size. To do this, we
# will use the map method again, with the option batched=True. When we use batched=True,
# the function we pass to map() will be passed multiple inputs at once, allowing us
# to group them into more or fewer examples than we had in the input.
# This allows us to create our new fixed-length samples. The advantage of this
# method is that we don't lose a whole lot of content from the dataset compared to the
# case where we simply tokenize with a pre-defined max_length.
def group_texts(__lowerCamelCase ):
# Concatenate all texts.
__snake_case : List[str] = {k: sum(examples[k] , [] ) for k in examples.keys()}
__snake_case : List[Any] = len(concatenated_examples[list(examples.keys() )[0]] )
# We drop the small remainder, though you could add padding instead if the model supports it
# In this, as in all things, we advise you to follow your heart 🫀
__snake_case : Any = (total_length // args.max_length) * args.max_length
# Split by chunks of max_len.
__snake_case : int = {
k: [t[i : i + args.max_length] for i in range(0 , __lowerCamelCase , args.max_length )]
for k, t in concatenated_examples.items()
}
return result
__snake_case : Any = dataset_tokenized.map(__lowerCamelCase , batched=__lowerCamelCase , batch_size=1_0_0_0 , num_proc=4 )
__snake_case : Optional[Any] = 0
__snake_case : Optional[Any] = 0
for shard in range(0 , len(__lowerCamelCase ) , args.shard_size ):
__snake_case : List[str] = grouped_dataset[shard : shard + args.shard_size]
__snake_case : Any = len(dataset_snapshot["input_ids"] )
__snake_case : List[Any] = os.path.join(__lowerCamelCase , F'dataset-{shard_count}-{records_containing}.tfrecord' )
__snake_case : Optional[Any] = get_serialized_examples(__lowerCamelCase )
with tf.io.TFRecordWriter(__lowerCamelCase ) as out_file:
for i in range(len(__lowerCamelCase ) ):
__snake_case : Union[str, Any] = serialized_examples[i]
out_file.write(__lowerCamelCase )
print("Wrote file {} containing {} records".format(__lowerCamelCase , __lowerCamelCase ) )
shard_count += 1
total_records += records_containing
with open(F'split-{args.split}-records-count.txt' , "w" ) as f:
print(F'Total {args.split} records: {total_records}' , file=__lowerCamelCase )
if __name__ == "__main__":
_snake_case : List[Any] = parse_args()
main(args)
| 81 | 1 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
_lowerCamelCase : Dict = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase : List[str] = [
'SEW_PRETRAINED_MODEL_ARCHIVE_LIST',
'SEWForCTC',
'SEWForSequenceClassification',
'SEWModel',
'SEWPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_sew import (
SEW_PRETRAINED_MODEL_ARCHIVE_LIST,
SEWForCTC,
SEWForSequenceClassification,
SEWModel,
SEWPreTrainedModel,
)
else:
import sys
_lowerCamelCase : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 361 |
"""simple docstring"""
import argparse
from argparse import Namespace
import torch
from torch import nn
from transformers import XGLMConfig, XGLMForCausalLM
def lowercase_ ( _UpperCAmelCase ):
"""simple docstring"""
A_ : Optional[Any] = [
'''decoder.version''',
'''decoder.output_projection.weight''',
'''_float_tensor''',
'''decoder.embed_positions._float_tensor''',
]
for k in ignore_keys:
state_dict.pop(_UpperCAmelCase , _UpperCAmelCase )
def lowercase_ ( _UpperCAmelCase ):
"""simple docstring"""
A_ , A_ : List[Any] = emb.weight.shape
A_ : List[Any] = nn.Linear(_UpperCAmelCase , _UpperCAmelCase , bias=_UpperCAmelCase )
A_ : Any = emb.weight.data
return lin_layer
def lowercase_ ( _UpperCAmelCase ):
"""simple docstring"""
A_ : int = torch.load(_UpperCAmelCase , map_location='''cpu''' )
A_ : Any = Namespace(**checkpoint['''cfg''']['''model'''] )
A_ : List[str] = checkpoint['''model''']
remove_ignore_keys_(_UpperCAmelCase )
A_ : Union[str, Any] = state_dict['''decoder.embed_tokens.weight'''].shape[0]
A_ : List[str] = {key.replace('''decoder''' , '''model''' ): val for key, val in state_dict.items()}
A_ : int = XGLMConfig(
vocab_size=_UpperCAmelCase , max_position_embeddings=args.max_target_positions , num_layers=args.decoder_layers , attention_heads=args.decoder_attention_heads , ffn_dim=args.decoder_ffn_embed_dim , d_model=args.decoder_embed_dim , layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='''gelu''' , scale_embedding=not args.no_scale_embedding , tie_word_embeddings=args.share_decoder_input_output_embed , )
A_ : Any = XGLMForCausalLM(_UpperCAmelCase )
A_ : int = model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase )
print(_UpperCAmelCase )
A_ : int = make_linear_from_emb(model.model.embed_tokens )
return model
if __name__ == "__main__":
_lowerCamelCase : Any = argparse.ArgumentParser()
# Required parameters
parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.')
parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
_lowerCamelCase : int = parser.parse_args()
_lowerCamelCase : Optional[Any] = convert_fairseq_xglm_checkpoint_from_disk(args.fairseq_path)
model.save_pretrained(args.pytorch_dump_folder_path)
| 361 | 1 |
'''simple docstring'''
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
UpperCamelCase__ : str = {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 _a (nn.Module):
"""simple docstring"""
def __init__( self , A__ ) -> Optional[Any]:
super().__init__()
_SCREAMING_SNAKE_CASE = torchvision.models.resnetaaa(pretrained=A__ )
_SCREAMING_SNAKE_CASE = list(model.children() )[:-2]
_SCREAMING_SNAKE_CASE = nn.Sequential(*A__ )
_SCREAMING_SNAKE_CASE = nn.AdaptiveAvgPoolad(POOLING_BREAKDOWN[args.num_image_embeds] )
def UpperCamelCase ( self , A__ ) -> Tuple:
# Bx3x224x224 -> Bx2048x7x7 -> Bx2048xN -> BxNx2048
_SCREAMING_SNAKE_CASE = self.pool(self.model(A__ ) )
_SCREAMING_SNAKE_CASE = torch.flatten(A__ , start_dim=2 )
_SCREAMING_SNAKE_CASE = out.transpose(1 , 2 ).contiguous()
return out # BxNx2048
class _a (_lowerCamelCase):
"""simple docstring"""
def __init__( self , A__ , A__ , A__ , A__ , A__ ) -> Dict:
_SCREAMING_SNAKE_CASE = [json.loads(A__ ) for l in open(A__ )]
_SCREAMING_SNAKE_CASE = os.path.dirname(A__ )
_SCREAMING_SNAKE_CASE = tokenizer
_SCREAMING_SNAKE_CASE = labels
_SCREAMING_SNAKE_CASE = len(A__ )
_SCREAMING_SNAKE_CASE = max_seq_length
_SCREAMING_SNAKE_CASE = transforms
def __len__( self ) -> Optional[int]:
return len(self.data )
def __getitem__( self , A__ ) -> int:
_SCREAMING_SNAKE_CASE = torch.LongTensor(self.tokenizer.encode(self.data[index]["""text"""] , add_special_tokens=A__ ) )
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = sentence[0], sentence[1:-1], sentence[-1]
_SCREAMING_SNAKE_CASE = sentence[: self.max_seq_length]
_SCREAMING_SNAKE_CASE = torch.zeros(self.n_classes )
_SCREAMING_SNAKE_CASE = 1
_SCREAMING_SNAKE_CASE = Image.open(os.path.join(self.data_dir , self.data[index]["""img"""] ) ).convert("""RGB""" )
_SCREAMING_SNAKE_CASE = self.transforms(A__ )
return {
"image_start_token": start_token,
"image_end_token": end_token,
"sentence": sentence,
"image": image,
"label": label,
}
def UpperCamelCase ( self ) -> str:
_SCREAMING_SNAKE_CASE = Counter()
for row in self.data:
label_freqs.update(row["""label"""] )
return label_freqs
def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE_ ) -> Tuple:
"""simple docstring"""
_SCREAMING_SNAKE_CASE = [len(row["""sentence"""] ) for row in batch]
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = len(SCREAMING_SNAKE_CASE_ ), max(SCREAMING_SNAKE_CASE_ )
_SCREAMING_SNAKE_CASE = torch.zeros(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , dtype=torch.long )
_SCREAMING_SNAKE_CASE = 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_ ) ):
_SCREAMING_SNAKE_CASE = input_row["""sentence"""]
_SCREAMING_SNAKE_CASE = 1
_SCREAMING_SNAKE_CASE = torch.stack([row["""image"""] for row in batch] )
_SCREAMING_SNAKE_CASE = torch.stack([row["""label"""] for row in batch] )
_SCREAMING_SNAKE_CASE = torch.stack([row["""image_start_token"""] for row in batch] )
_SCREAMING_SNAKE_CASE = 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_ ( ) -> List[Any]:
"""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_ ( ) -> Tuple:
"""simple docstring"""
return transforms.Compose(
[
transforms.Resize(2_56 ),
transforms.CenterCrop(2_24 ),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.4677_7044, 0.4453_1429, 0.4066_1017] , std=[0.1222_1994, 0.1214_5835, 0.1438_0469] , ),
] )
| 591 |
'''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 _a :
"""simple docstring"""
def __init__( self , A__ , A__=2 , A__=32 , A__=16 , A__=3 , A__=True , A__=True , A__=32 , A__=4 , A__=[0, 1, 2, 3] , A__=4 , A__=37 , A__="gelu" , A__=0.1 , A__=0.1 , A__=0.02 , A__=3 , A__=[1, 3_84, 24, 24] , A__=True , A__=None , ) -> int:
_SCREAMING_SNAKE_CASE = parent
_SCREAMING_SNAKE_CASE = batch_size
_SCREAMING_SNAKE_CASE = image_size
_SCREAMING_SNAKE_CASE = patch_size
_SCREAMING_SNAKE_CASE = num_channels
_SCREAMING_SNAKE_CASE = is_training
_SCREAMING_SNAKE_CASE = use_labels
_SCREAMING_SNAKE_CASE = hidden_size
_SCREAMING_SNAKE_CASE = num_hidden_layers
_SCREAMING_SNAKE_CASE = backbone_out_indices
_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 = initializer_range
_SCREAMING_SNAKE_CASE = num_labels
_SCREAMING_SNAKE_CASE = backbone_featmap_shape
_SCREAMING_SNAKE_CASE = scope
_SCREAMING_SNAKE_CASE = is_hybrid
# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
_SCREAMING_SNAKE_CASE = (image_size // patch_size) ** 2
_SCREAMING_SNAKE_CASE = num_patches + 1
def UpperCamelCase ( self ) -> Optional[Any]:
_SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
_SCREAMING_SNAKE_CASE = None
if self.use_labels:
_SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels )
_SCREAMING_SNAKE_CASE = self.get_config()
return config, pixel_values, labels
def UpperCamelCase ( self ) -> List[str]:
_SCREAMING_SNAKE_CASE = {
"""global_padding""": """same""",
"""layer_type""": """bottleneck""",
"""depths""": [3, 4, 9],
"""out_features""": ["""stage1""", """stage2""", """stage3"""],
"""embedding_dynamic_padding""": True,
"""hidden_sizes""": [96, 1_92, 3_84, 7_68],
"""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 UpperCamelCase ( self , A__ , A__ , A__ ) -> Tuple:
_SCREAMING_SNAKE_CASE = DPTModel(config=A__ )
model.to(A__ )
model.eval()
_SCREAMING_SNAKE_CASE = model(A__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def UpperCamelCase ( self , A__ , A__ , A__ ) -> List[str]:
_SCREAMING_SNAKE_CASE = self.num_labels
_SCREAMING_SNAKE_CASE = DPTForDepthEstimation(A__ )
model.to(A__ )
model.eval()
_SCREAMING_SNAKE_CASE = model(A__ )
self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) )
def UpperCamelCase ( self , A__ , A__ , A__ ) -> Optional[Any]:
_SCREAMING_SNAKE_CASE = self.num_labels
_SCREAMING_SNAKE_CASE = DPTForSemanticSegmentation(A__ )
model.to(A__ )
model.eval()
_SCREAMING_SNAKE_CASE = model(A__ , labels=A__ )
self.parent.assertEqual(
result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) )
def UpperCamelCase ( self ) -> int:
_SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs()
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = config_and_inputs
_SCREAMING_SNAKE_CASE = {"""pixel_values""": pixel_values}
return config, inputs_dict
@require_torch
class _a (_lowerCamelCase , _lowerCamelCase , unittest.TestCase):
"""simple docstring"""
SCREAMING_SNAKE_CASE = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
SCREAMING_SNAKE_CASE = (
{
'depth-estimation': DPTForDepthEstimation,
'feature-extraction': DPTModel,
'image-segmentation': DPTForSemanticSegmentation,
}
if is_torch_available()
else {}
)
SCREAMING_SNAKE_CASE = False
SCREAMING_SNAKE_CASE = False
SCREAMING_SNAKE_CASE = False
def UpperCamelCase ( self ) -> List[str]:
_SCREAMING_SNAKE_CASE = DPTModelTester(self )
_SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=A__ , has_text_modality=A__ , hidden_size=37 )
def UpperCamelCase ( self ) -> str:
self.config_tester.run_common_tests()
@unittest.skip(reason="""DPT does not use inputs_embeds""" )
def UpperCamelCase ( self ) -> List[str]:
pass
def UpperCamelCase ( self ) -> Dict:
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_SCREAMING_SNAKE_CASE = model_class(A__ )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
_SCREAMING_SNAKE_CASE = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(A__ , nn.Linear ) )
def UpperCamelCase ( self ) -> Tuple:
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_SCREAMING_SNAKE_CASE = model_class(A__ )
_SCREAMING_SNAKE_CASE = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_SCREAMING_SNAKE_CASE = [*signature.parameters.keys()]
_SCREAMING_SNAKE_CASE = ["""pixel_values"""]
self.assertListEqual(arg_names[:1] , A__ )
def UpperCamelCase ( self ) -> int:
_SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*A__ )
def UpperCamelCase ( self ) -> str:
_SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_depth_estimation(*A__ )
def UpperCamelCase ( self ) -> List[Any]:
_SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_semantic_segmentation(*A__ )
def UpperCamelCase ( self ) -> Union[str, Any]:
for model_class in self.all_model_classes:
if model_class.__name__ == "DPTForDepthEstimation":
continue
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common()
_SCREAMING_SNAKE_CASE = True
if model_class in get_values(A__ ):
continue
_SCREAMING_SNAKE_CASE = model_class(A__ )
model.to(A__ )
model.train()
_SCREAMING_SNAKE_CASE = self._prepare_for_class(A__ , A__ , return_labels=A__ )
_SCREAMING_SNAKE_CASE = model(**A__ ).loss
loss.backward()
def UpperCamelCase ( self ) -> Union[str, Any]:
for model_class in self.all_model_classes:
if model_class.__name__ == "DPTForDepthEstimation":
continue
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common()
_SCREAMING_SNAKE_CASE = False
_SCREAMING_SNAKE_CASE = True
if model_class in get_values(A__ ) or not model_class.supports_gradient_checkpointing:
continue
_SCREAMING_SNAKE_CASE = model_class(A__ )
model.to(A__ )
model.gradient_checkpointing_enable()
model.train()
_SCREAMING_SNAKE_CASE = self._prepare_for_class(A__ , A__ , return_labels=A__ )
_SCREAMING_SNAKE_CASE = model(**A__ ).loss
loss.backward()
def UpperCamelCase ( self ) -> Any:
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common()
_SCREAMING_SNAKE_CASE = _config_zero_init(A__ )
for model_class in self.all_model_classes:
_SCREAMING_SNAKE_CASE = model_class(config=A__ )
# Skip the check for the backbone
_SCREAMING_SNAKE_CASE = []
for name, module in model.named_modules():
if module.__class__.__name__ == "DPTViTHybridEmbeddings":
_SCREAMING_SNAKE_CASE = [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 UpperCamelCase ( self ) -> Any:
pass
@slow
def UpperCamelCase ( self ) -> List[Any]:
for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
_SCREAMING_SNAKE_CASE = DPTModel.from_pretrained(A__ )
self.assertIsNotNone(A__ )
def UpperCamelCase ( self ) -> List[Any]:
# We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common()
_SCREAMING_SNAKE_CASE = """add"""
with self.assertRaises(A__ ):
_SCREAMING_SNAKE_CASE = DPTForDepthEstimation(A__ )
def lowerCAmelCase_ ( ) -> Tuple:
"""simple docstring"""
_SCREAMING_SNAKE_CASE = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
return image
@require_torch
@require_vision
@slow
class _a (unittest.TestCase):
"""simple docstring"""
def UpperCamelCase ( self ) -> Tuple:
_SCREAMING_SNAKE_CASE = DPTImageProcessor.from_pretrained("""Intel/dpt-hybrid-midas""" )
_SCREAMING_SNAKE_CASE = DPTForDepthEstimation.from_pretrained("""Intel/dpt-hybrid-midas""" ).to(A__ )
_SCREAMING_SNAKE_CASE = prepare_img()
_SCREAMING_SNAKE_CASE = image_processor(images=A__ , return_tensors="""pt""" ).to(A__ )
# forward pass
with torch.no_grad():
_SCREAMING_SNAKE_CASE = model(**A__ )
_SCREAMING_SNAKE_CASE = outputs.predicted_depth
# verify the predicted depth
_SCREAMING_SNAKE_CASE = torch.Size((1, 3_84, 3_84) )
self.assertEqual(predicted_depth.shape , A__ )
_SCREAMING_SNAKE_CASE = torch.tensor(
[[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]] ).to(A__ )
self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 1_00 , A__ , atol=1E-4 ) )
| 591 | 1 |
import gc
import tempfile
import unittest
import numpy as np
import torch
from diffusers import VersatileDiffusionTextToImagePipeline
from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device
__a : Optional[int] = False
class A ( unittest.TestCase ):
pass
@nightly
@require_torch_gpu
class A ( unittest.TestCase ):
def lowercase__ ( self : List[str] ) -> Dict:
"""simple docstring"""
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def lowercase__ ( self : List[str] ) -> str:
"""simple docstring"""
UpperCamelCase_ = VersatileDiffusionTextToImagePipeline.from_pretrained('shi-labs/versatile-diffusion' )
# remove text_unet
pipe.remove_unused_weights()
pipe.to(__UpperCAmelCase )
pipe.set_progress_bar_config(disable=__UpperCAmelCase )
UpperCamelCase_ = 'A painting of a squirrel eating a burger '
UpperCamelCase_ = torch.manual_seed(0 )
UpperCamelCase_ = pipe(
prompt=__UpperCAmelCase , generator=__UpperCAmelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='numpy' ).images
with tempfile.TemporaryDirectory() as tmpdirname:
pipe.save_pretrained(__UpperCAmelCase )
UpperCamelCase_ = VersatileDiffusionTextToImagePipeline.from_pretrained(__UpperCAmelCase )
pipe.to(__UpperCAmelCase )
pipe.set_progress_bar_config(disable=__UpperCAmelCase )
UpperCamelCase_ = generator.manual_seed(0 )
UpperCamelCase_ = pipe(
prompt=__UpperCAmelCase , generator=__UpperCAmelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='numpy' ).images
assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass"
def lowercase__ ( self : Optional[int] ) -> List[Any]:
"""simple docstring"""
UpperCamelCase_ = VersatileDiffusionTextToImagePipeline.from_pretrained(
'shi-labs/versatile-diffusion' , torch_dtype=torch.floataa )
pipe.to(__UpperCAmelCase )
pipe.set_progress_bar_config(disable=__UpperCAmelCase )
UpperCamelCase_ = 'A painting of a squirrel eating a burger '
UpperCamelCase_ = torch.manual_seed(0 )
UpperCamelCase_ = pipe(
prompt=__UpperCAmelCase , generator=__UpperCAmelCase , guidance_scale=7.5 , num_inference_steps=50 , output_type='numpy' ).images
UpperCamelCase_ = image[0, 253:256, 253:256, -1]
assert image.shape == (1, 512, 512, 3)
UpperCamelCase_ = np.array([0.3_367, 0.3_169, 0.2_656, 0.3_870, 0.4_790, 0.3_796, 0.4_009, 0.4_878, 0.4_778] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
| 559 |
import math
import torch
from torch import nn
from ..configuration_utils import ConfigMixin, register_to_config
from .attention_processor import Attention
from .embeddings import get_timestep_embedding
from .modeling_utils import ModelMixin
class A ( lowerCamelCase_ , lowerCamelCase_ ):
@register_to_config
def __init__( self : Optional[int] , __UpperCAmelCase : int = 128 , __UpperCAmelCase : int = 256 , __UpperCAmelCase : float = 2_000.0 , __UpperCAmelCase : int = 768 , __UpperCAmelCase : int = 12 , __UpperCAmelCase : int = 12 , __UpperCAmelCase : int = 64 , __UpperCAmelCase : int = 2048 , __UpperCAmelCase : float = 0.1 , ) -> List[str]:
"""simple docstring"""
super().__init__()
UpperCamelCase_ = nn.Sequential(
nn.Linear(__UpperCAmelCase , d_model * 4 , bias=__UpperCAmelCase ) , nn.SiLU() , nn.Linear(d_model * 4 , d_model * 4 , bias=__UpperCAmelCase ) , nn.SiLU() , )
UpperCamelCase_ = nn.Embedding(__UpperCAmelCase , __UpperCAmelCase )
UpperCamelCase_ = False
UpperCamelCase_ = nn.Linear(__UpperCAmelCase , __UpperCAmelCase , bias=__UpperCAmelCase )
UpperCamelCase_ = nn.Dropout(p=__UpperCAmelCase )
UpperCamelCase_ = nn.ModuleList()
for lyr_num in range(__UpperCAmelCase ):
# FiLM conditional T5 decoder
UpperCamelCase_ = DecoderLayer(d_model=__UpperCAmelCase , d_kv=__UpperCAmelCase , num_heads=__UpperCAmelCase , d_ff=__UpperCAmelCase , dropout_rate=__UpperCAmelCase )
self.decoders.append(__UpperCAmelCase )
UpperCamelCase_ = TaLayerNorm(__UpperCAmelCase )
UpperCamelCase_ = nn.Dropout(p=__UpperCAmelCase )
UpperCamelCase_ = nn.Linear(__UpperCAmelCase , __UpperCAmelCase , bias=__UpperCAmelCase )
def lowercase__ ( self : str , __UpperCAmelCase : Tuple , __UpperCAmelCase : int ) -> Any:
"""simple docstring"""
UpperCamelCase_ = torch.mul(query_input.unsqueeze(-1 ) , key_input.unsqueeze(-2 ) )
return mask.unsqueeze(-3 )
def lowercase__ ( self : List[Any] , __UpperCAmelCase : Dict , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Any ) -> int:
"""simple docstring"""
UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = decoder_input_tokens.shape
assert decoder_noise_time.shape == (batch,)
# decoder_noise_time is in [0, 1), so rescale to expected timing range.
UpperCamelCase_ = get_timestep_embedding(
decoder_noise_time * self.config.max_decoder_noise_time , embedding_dim=self.config.d_model , max_period=self.config.max_decoder_noise_time , ).to(dtype=self.dtype )
UpperCamelCase_ = self.conditioning_emb(__UpperCAmelCase ).unsqueeze(1 )
assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4)
UpperCamelCase_ = decoder_input_tokens.shape[1]
# If we want to use relative positions for audio context, we can just offset
# this sequence by the length of encodings_and_masks.
UpperCamelCase_ = torch.broadcast_to(
torch.arange(__UpperCAmelCase , device=decoder_input_tokens.device ) , (batch, seq_length) , )
UpperCamelCase_ = self.position_encoding(__UpperCAmelCase )
UpperCamelCase_ = self.continuous_inputs_projection(__UpperCAmelCase )
inputs += position_encodings
UpperCamelCase_ = self.dropout(__UpperCAmelCase )
# decoder: No padding present.
UpperCamelCase_ = torch.ones(
decoder_input_tokens.shape[:2] , device=decoder_input_tokens.device , dtype=inputs.dtype )
# Translate encoding masks to encoder-decoder masks.
UpperCamelCase_ = [(x, self.encoder_decoder_mask(__UpperCAmelCase , __UpperCAmelCase )) for x, y in encodings_and_masks]
# cross attend style: concat encodings
UpperCamelCase_ = torch.cat([x[0] for x in encodings_and_encdec_masks] , dim=1 )
UpperCamelCase_ = torch.cat([x[1] for x in encodings_and_encdec_masks] , dim=-1 )
for lyr in self.decoders:
UpperCamelCase_ = lyr(
__UpperCAmelCase , conditioning_emb=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , )[0]
UpperCamelCase_ = self.decoder_norm(__UpperCAmelCase )
UpperCamelCase_ = self.post_dropout(__UpperCAmelCase )
UpperCamelCase_ = self.spec_out(__UpperCAmelCase )
return spec_out
class A ( nn.Module ):
def __init__( self : List[str] , __UpperCAmelCase : int , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : int , __UpperCAmelCase : int , __UpperCAmelCase : str=1E-6 ) -> List[Any]:
"""simple docstring"""
super().__init__()
UpperCamelCase_ = nn.ModuleList()
# cond self attention: layer 0
self.layer.append(
TaLayerSelfAttentionCond(d_model=__UpperCAmelCase , d_kv=__UpperCAmelCase , num_heads=__UpperCAmelCase , dropout_rate=__UpperCAmelCase ) )
# cross attention: layer 1
self.layer.append(
TaLayerCrossAttention(
d_model=__UpperCAmelCase , d_kv=__UpperCAmelCase , num_heads=__UpperCAmelCase , dropout_rate=__UpperCAmelCase , layer_norm_epsilon=__UpperCAmelCase , ) )
# Film Cond MLP + dropout: last layer
self.layer.append(
TaLayerFFCond(d_model=__UpperCAmelCase , d_ff=__UpperCAmelCase , dropout_rate=__UpperCAmelCase , layer_norm_epsilon=__UpperCAmelCase ) )
def lowercase__ ( self : Optional[int] , __UpperCAmelCase : int , __UpperCAmelCase : Union[str, Any]=None , __UpperCAmelCase : str=None , __UpperCAmelCase : int=None , __UpperCAmelCase : int=None , __UpperCAmelCase : str=None , ) -> Tuple:
"""simple docstring"""
UpperCamelCase_ = self.layer[0](
__UpperCAmelCase , conditioning_emb=__UpperCAmelCase , attention_mask=__UpperCAmelCase , )
if encoder_hidden_states is not None:
UpperCamelCase_ = torch.where(encoder_attention_mask > 0 , 0 , -1E1_0 ).to(
encoder_hidden_states.dtype )
UpperCamelCase_ = self.layer[1](
__UpperCAmelCase , key_value_states=__UpperCAmelCase , attention_mask=__UpperCAmelCase , )
# Apply Film Conditional Feed Forward layer
UpperCamelCase_ = self.layer[-1](__UpperCAmelCase , __UpperCAmelCase )
return (hidden_states,)
class A ( nn.Module ):
def __init__( self : Union[str, Any] , __UpperCAmelCase : int , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : str ) -> str:
"""simple docstring"""
super().__init__()
UpperCamelCase_ = TaLayerNorm(__UpperCAmelCase )
UpperCamelCase_ = TaFiLMLayer(in_features=d_model * 4 , out_features=__UpperCAmelCase )
UpperCamelCase_ = Attention(query_dim=__UpperCAmelCase , heads=__UpperCAmelCase , dim_head=__UpperCAmelCase , out_bias=__UpperCAmelCase , scale_qk=__UpperCAmelCase )
UpperCamelCase_ = nn.Dropout(__UpperCAmelCase )
def lowercase__ ( self : Union[str, Any] , __UpperCAmelCase : Any , __UpperCAmelCase : List[str]=None , __UpperCAmelCase : List[Any]=None , ) -> Optional[int]:
"""simple docstring"""
UpperCamelCase_ = self.layer_norm(__UpperCAmelCase )
if conditioning_emb is not None:
UpperCamelCase_ = self.FiLMLayer(__UpperCAmelCase , __UpperCAmelCase )
# Self-attention block
UpperCamelCase_ = self.attention(__UpperCAmelCase )
UpperCamelCase_ = hidden_states + self.dropout(__UpperCAmelCase )
return hidden_states
class A ( nn.Module ):
def __init__( self : Any , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : str ) -> Any:
"""simple docstring"""
super().__init__()
UpperCamelCase_ = Attention(query_dim=__UpperCAmelCase , heads=__UpperCAmelCase , dim_head=__UpperCAmelCase , out_bias=__UpperCAmelCase , scale_qk=__UpperCAmelCase )
UpperCamelCase_ = TaLayerNorm(__UpperCAmelCase , eps=__UpperCAmelCase )
UpperCamelCase_ = nn.Dropout(__UpperCAmelCase )
def lowercase__ ( self : Optional[int] , __UpperCAmelCase : str , __UpperCAmelCase : List[str]=None , __UpperCAmelCase : Tuple=None , ) -> str:
"""simple docstring"""
UpperCamelCase_ = self.layer_norm(__UpperCAmelCase )
UpperCamelCase_ = self.attention(
__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , attention_mask=attention_mask.squeeze(1 ) , )
UpperCamelCase_ = hidden_states + self.dropout(__UpperCAmelCase )
return layer_output
class A ( nn.Module ):
def __init__( self : Dict , __UpperCAmelCase : Tuple , __UpperCAmelCase : Any , __UpperCAmelCase : Any , __UpperCAmelCase : List[Any] ) -> List[Any]:
"""simple docstring"""
super().__init__()
UpperCamelCase_ = TaDenseGatedActDense(d_model=__UpperCAmelCase , d_ff=__UpperCAmelCase , dropout_rate=__UpperCAmelCase )
UpperCamelCase_ = TaFiLMLayer(in_features=d_model * 4 , out_features=__UpperCAmelCase )
UpperCamelCase_ = TaLayerNorm(__UpperCAmelCase , eps=__UpperCAmelCase )
UpperCamelCase_ = nn.Dropout(__UpperCAmelCase )
def lowercase__ ( self : Optional[int] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : List[str]=None ) -> str:
"""simple docstring"""
UpperCamelCase_ = self.layer_norm(__UpperCAmelCase )
if conditioning_emb is not None:
UpperCamelCase_ = self.film(__UpperCAmelCase , __UpperCAmelCase )
UpperCamelCase_ = self.DenseReluDense(__UpperCAmelCase )
UpperCamelCase_ = hidden_states + self.dropout(__UpperCAmelCase )
return hidden_states
class A ( nn.Module ):
def __init__( self : Optional[int] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : List[Any] ) -> Tuple:
"""simple docstring"""
super().__init__()
UpperCamelCase_ = nn.Linear(__UpperCAmelCase , __UpperCAmelCase , bias=__UpperCAmelCase )
UpperCamelCase_ = nn.Linear(__UpperCAmelCase , __UpperCAmelCase , bias=__UpperCAmelCase )
UpperCamelCase_ = nn.Linear(__UpperCAmelCase , __UpperCAmelCase , bias=__UpperCAmelCase )
UpperCamelCase_ = nn.Dropout(__UpperCAmelCase )
UpperCamelCase_ = NewGELUActivation()
def lowercase__ ( self : List[str] , __UpperCAmelCase : List[Any] ) -> Any:
"""simple docstring"""
UpperCamelCase_ = self.act(self.wi_a(__UpperCAmelCase ) )
UpperCamelCase_ = self.wi_a(__UpperCAmelCase )
UpperCamelCase_ = hidden_gelu * hidden_linear
UpperCamelCase_ = self.dropout(__UpperCAmelCase )
UpperCamelCase_ = self.wo(__UpperCAmelCase )
return hidden_states
class A ( nn.Module ):
def __init__( self : Dict , __UpperCAmelCase : Dict , __UpperCAmelCase : Any=1E-6 ) -> str:
"""simple docstring"""
super().__init__()
UpperCamelCase_ = nn.Parameter(torch.ones(__UpperCAmelCase ) )
UpperCamelCase_ = eps
def lowercase__ ( self : Any , __UpperCAmelCase : Optional[Any] ) -> int:
"""simple docstring"""
UpperCamelCase_ = hidden_states.to(torch.floataa ).pow(2 ).mean(-1 , keepdim=__UpperCAmelCase )
UpperCamelCase_ = hidden_states * torch.rsqrt(variance + self.variance_epsilon )
# convert into half-precision if necessary
if self.weight.dtype in [torch.floataa, torch.bfloataa]:
UpperCamelCase_ = hidden_states.to(self.weight.dtype )
return self.weight * hidden_states
class A ( nn.Module ):
def lowercase__ ( self : List[Any] , __UpperCAmelCase : torch.Tensor ) -> torch.Tensor:
"""simple docstring"""
return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi ) * (input + 0.044_715 * torch.pow(__UpperCAmelCase , 3.0 )) ))
class A ( nn.Module ):
def __init__( self : Optional[int] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Tuple ) -> Any:
"""simple docstring"""
super().__init__()
UpperCamelCase_ = nn.Linear(__UpperCAmelCase , out_features * 2 , bias=__UpperCAmelCase )
def lowercase__ ( self : List[Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Any ) -> Optional[int]:
"""simple docstring"""
UpperCamelCase_ = self.scale_bias(__UpperCAmelCase )
UpperCamelCase_ , UpperCamelCase_ = torch.chunk(__UpperCAmelCase , 2 , -1 )
UpperCamelCase_ = x * (1 + scale) + shift
return x
| 559 | 1 |
import argparse
import gc
import json
import os
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
from accelerate.utils.deepspeed import DummyOptim, DummyScheduler
lowerCAmelCase__: str = 16
lowerCAmelCase__: Dict = 32
def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ) -> Optional[int]:
return int(x / 2**20 )
class snake_case_ :
def __enter__( self ):
gc.collect()
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero
SCREAMING_SNAKE_CASE_ : Tuple = torch.cuda.memory_allocated()
return self
def __exit__( self , *__lowerCAmelCase ):
gc.collect()
torch.cuda.empty_cache()
SCREAMING_SNAKE_CASE_ : Tuple = torch.cuda.memory_allocated()
SCREAMING_SNAKE_CASE_ : Dict = torch.cuda.max_memory_allocated()
SCREAMING_SNAKE_CASE_ : Optional[int] = bamb(self.end - self.begin )
SCREAMING_SNAKE_CASE_ : Dict = bamb(self.peak - self.begin )
# print(f"delta used/peak {self.used:4d}/{self.peaked:4d}")
def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 16 , SCREAMING_SNAKE_CASE = "bert-base-cased" , SCREAMING_SNAKE_CASE = 320 , SCREAMING_SNAKE_CASE = 160 , ) -> List[str]:
SCREAMING_SNAKE_CASE_ : Tuple = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ : Any = load_dataset(
'glue' , 'mrpc' , split={'train': f'train[:{n_train}]', 'validation': f'validation[:{n_val}]'} )
def tokenize_function(SCREAMING_SNAKE_CASE ):
# max_length=None => use the model max length (it's actually the default)
SCREAMING_SNAKE_CASE_ : List[str] = 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
SCREAMING_SNAKE_CASE_ : int = datasets.map(
SCREAMING_SNAKE_CASE , batched=SCREAMING_SNAKE_CASE , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=SCREAMING_SNAKE_CASE )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
SCREAMING_SNAKE_CASE_ : str = tokenized_datasets.rename_column('label' , 'labels' )
def collate_fn(SCREAMING_SNAKE_CASE ):
# 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(SCREAMING_SNAKE_CASE , padding='max_length' , max_length=128 , return_tensors='pt' )
return tokenizer.pad(SCREAMING_SNAKE_CASE , padding='longest' , return_tensors='pt' )
# Instantiate dataloaders.
SCREAMING_SNAKE_CASE_ : List[Any] = DataLoader(
tokenized_datasets['train'] , shuffle=SCREAMING_SNAKE_CASE , collate_fn=SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ : Tuple = DataLoader(
tokenized_datasets['validation'] , shuffle=SCREAMING_SNAKE_CASE , collate_fn=SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE )
return train_dataloader, eval_dataloader
def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any:
# Initialize accelerator
SCREAMING_SNAKE_CASE_ : Optional[int] = Accelerator()
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
SCREAMING_SNAKE_CASE_ : Optional[Any] = config['lr']
SCREAMING_SNAKE_CASE_ : Optional[int] = int(config['num_epochs'] )
SCREAMING_SNAKE_CASE_ : Optional[Any] = int(config['seed'] )
SCREAMING_SNAKE_CASE_ : Dict = int(config['batch_size'] )
SCREAMING_SNAKE_CASE_ : Union[str, Any] = args.model_name_or_path
set_seed(SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = get_dataloaders(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , args.n_train , args.n_val )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE , return_dict=SCREAMING_SNAKE_CASE )
# Instantiate optimizer
SCREAMING_SNAKE_CASE_ : Any = (
AdamW
if accelerator.state.deepspeed_plugin is None
or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config
else DummyOptim
)
SCREAMING_SNAKE_CASE_ : Union[str, Any] = optimizer_cls(params=model.parameters() , lr=SCREAMING_SNAKE_CASE )
if accelerator.state.deepspeed_plugin is not None:
SCREAMING_SNAKE_CASE_ : Optional[int] = accelerator.state.deepspeed_plugin.deepspeed_config[
'gradient_accumulation_steps'
]
else:
SCREAMING_SNAKE_CASE_ : Optional[int] = 1
SCREAMING_SNAKE_CASE_ : int = (len(SCREAMING_SNAKE_CASE ) * num_epochs) // gradient_accumulation_steps
# Instantiate scheduler
if (
accelerator.state.deepspeed_plugin is None
or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
):
SCREAMING_SNAKE_CASE_ : Tuple = get_linear_schedule_with_warmup(
optimizer=SCREAMING_SNAKE_CASE , num_warmup_steps=0 , num_training_steps=SCREAMING_SNAKE_CASE , )
else:
SCREAMING_SNAKE_CASE_ : List[Any] = DummyScheduler(SCREAMING_SNAKE_CASE , total_num_steps=SCREAMING_SNAKE_CASE , warmup_num_steps=0 )
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = accelerator.prepare(
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
# We need to keep track of how many total steps we have iterated over
SCREAMING_SNAKE_CASE_ : str = 0
# We also need to keep track of the stating epoch so files are named properly
SCREAMING_SNAKE_CASE_ : int = 0
# Now we train the model
SCREAMING_SNAKE_CASE_ : str = {}
for epoch in range(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
with TorchTracemalloc() as tracemalloc:
model.train()
for step, batch in enumerate(SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(**SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ : List[str] = outputs.loss
SCREAMING_SNAKE_CASE_ : Tuple = loss / gradient_accumulation_steps
accelerator.backward(SCREAMING_SNAKE_CASE )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
overall_step += 1
# Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage
accelerator.print('Memory before entering the train : {}'.format(bamb(tracemalloc.begin ) ) )
accelerator.print('Memory consumed at the end of the train (end-begin): {}'.format(tracemalloc.used ) )
accelerator.print('Peak Memory consumed during the train (max-begin): {}'.format(tracemalloc.peaked ) )
accelerator.print(
'Total Peak Memory consumed during the train (max): {}'.format(
tracemalloc.peaked + bamb(tracemalloc.begin ) ) )
SCREAMING_SNAKE_CASE_ : str = tracemalloc.peaked + bamb(tracemalloc.begin )
if args.peak_memory_upper_bound is not None:
assert (
train_total_peak_memory[f'epoch-{epoch}'] <= args.peak_memory_upper_bound
), "Peak memory usage exceeded the upper bound"
accelerator.wait_for_everyone()
if accelerator.is_main_process:
with open(os.path.join(args.output_dir , 'peak_memory_utilization.json' ) , 'w' ) as f:
json.dump(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
def __SCREAMING_SNAKE_CASE ( ) -> Optional[Any]:
SCREAMING_SNAKE_CASE_ : Tuple = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' )
parser.add_argument(
'--model_name_or_path' , type=SCREAMING_SNAKE_CASE , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=SCREAMING_SNAKE_CASE , )
parser.add_argument(
'--output_dir' , type=SCREAMING_SNAKE_CASE , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , )
parser.add_argument(
'--peak_memory_upper_bound' , type=SCREAMING_SNAKE_CASE , default=SCREAMING_SNAKE_CASE , help='The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value.' , )
parser.add_argument(
'--n_train' , type=SCREAMING_SNAKE_CASE , default=320 , help='Number of training examples to use.' , )
parser.add_argument(
'--n_val' , type=SCREAMING_SNAKE_CASE , default=160 , help='Number of validation examples to use.' , )
parser.add_argument(
'--num_epochs' , type=SCREAMING_SNAKE_CASE , default=1 , help='Number of train epochs.' , )
SCREAMING_SNAKE_CASE_ : List[Any] = parser.parse_args()
SCREAMING_SNAKE_CASE_ : List[Any] = {'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16}
training_function(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
main()
| 345 |
import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401
from coval.conll import reader, util
from coval.eval import evaluator
import datasets
lowerCAmelCase__: int = datasets.logging.get_logger(__name__)
lowerCAmelCase__: Optional[int] = "\\n@InProceedings{moosavi2019minimum,\n author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube},\n title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection},\n year = {2019},\n booktitle = {Proceedings of the 57th Annual Meeting of\n the Association for Computational Linguistics (Volume 1: Long Papers)},\n publisher = {Association for Computational Linguistics},\n address = {Florence, Italy},\n}\n\n@inproceedings{10.3115/1072399.1072405,\nauthor = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette},\ntitle = {A Model-Theoretic Coreference Scoring Scheme},\nyear = {1995},\nisbn = {1558604022},\npublisher = {Association for Computational Linguistics},\naddress = {USA},\nurl = {https://doi.org/10.3115/1072399.1072405},\ndoi = {10.3115/1072399.1072405},\nbooktitle = {Proceedings of the 6th Conference on Message Understanding},\npages = {45–52},\nnumpages = {8},\nlocation = {Columbia, Maryland},\nseries = {MUC6 ’95}\n}\n\n@INPROCEEDINGS{Bagga98algorithmsfor,\n author = {Amit Bagga and Breck Baldwin},\n title = {Algorithms for Scoring Coreference Chains},\n booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference},\n year = {1998},\n pages = {563--566}\n}\n\n@INPROCEEDINGS{Luo05oncoreference,\n author = {Xiaoqiang Luo},\n title = {On coreference resolution performance metrics},\n booktitle = {In Proc. of HLT/EMNLP},\n year = {2005},\n pages = {25--32},\n publisher = {URL}\n}\n\n@inproceedings{moosavi-strube-2016-coreference,\n title = \"Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric\",\n author = \"Moosavi, Nafise Sadat and\n Strube, Michael\",\n booktitle = \"Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)\",\n month = aug,\n year = \"2016\",\n address = \"Berlin, Germany\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/P16-1060\",\n doi = \"10.18653/v1/P16-1060\",\n pages = \"632--642\",\n}\n\n"
lowerCAmelCase__: Any = "\\nCoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which\nimplements of the common evaluation metrics including MUC [Vilain et al, 1995],\nB-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005],\nLEA [Moosavi and Strube, 2016] and the averaged CoNLL score\n(the average of the F1 values of MUC, B-cubed and CEAFe)\n[Denis and Baldridge, 2009a; Pradhan et al., 2011].\n\nThis wrapper of CoVal currently only work with CoNLL line format:\nThe CoNLL format has one word per line with all the annotation for this word in column separated by spaces:\nColumn Type Description\n1 Document ID This is a variation on the document filename\n2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc.\n3 Word number\n4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release.\n5 Part-of-Speech\n6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the \"([pos] [word])\" string (or leaf) and concatenating the items in the rows of that column.\n7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a \"-\"\n8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7.\n9 Word sense This is the word sense of the word in Column 3.\n10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data.\n11 Named Entities These columns identifies the spans representing various named entities.\n12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7.\nN Coreference Coreference chain information encoded in a parenthesis structure.\nMore informations on the format can be found here (section \"*_conll File Format\"): http://www.conll.cemantix.org/2012/data.html\n\nDetails on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md\n\nCoVal code was written by @ns-moosavi.\nSome parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py\nThe test suite is taken from https://github.com/conll/reference-coreference-scorers/\nMention evaluation and the test suite are added by @andreasvc.\nParsing CoNLL files is developed by Leo Born.\n"
lowerCAmelCase__: Tuple = "\nCalculates coreference evaluation metrics.\nArgs:\n predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format.\n Each prediction is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format.\n Each reference is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n keep_singletons: After extracting all mentions of key or system files,\n mentions whose corresponding coreference chain is of size one,\n are considered as singletons. The default evaluation mode will include\n singletons in evaluations if they are included in the key or the system files.\n By setting 'keep_singletons=False', all singletons in the key and system files\n will be excluded from the evaluation.\n NP_only: Most of the recent coreference resolvers only resolve NP mentions and\n leave out the resolution of VPs. By setting the 'NP_only' option, the scorer will only evaluate the resolution of NPs.\n min_span: By setting 'min_span', the scorer reports the results based on automatically detected minimum spans.\n Minimum spans are determined using the MINA algorithm.\n\nReturns:\n 'mentions': mentions\n 'muc': MUC metric [Vilain et al, 1995]\n 'bcub': B-cubed [Bagga and Baldwin, 1998]\n 'ceafe': CEAFe [Luo et al., 2005]\n 'lea': LEA [Moosavi and Strube, 2016]\n 'conll_score': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe)\n\nExamples:\n\n >>> coval = datasets.load_metric('coval')\n >>> words = ['bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -',\n ... 'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)',\n ... 'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)',\n ... 'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -',\n ... 'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -',\n ... 'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -']\n >>> references = [words]\n >>> predictions = [words]\n >>> results = coval.compute(predictions=predictions, references=references)\n >>> print(results) # doctest:+ELLIPSIS\n {'mentions/recall': 1.0,[...] 'conll_score': 100.0}\n"
def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE="dummy_doc" ) -> Tuple:
SCREAMING_SNAKE_CASE_ : Dict = {doc: key_lines}
SCREAMING_SNAKE_CASE_ : Dict = {doc: sys_lines}
SCREAMING_SNAKE_CASE_ : List[str] = {}
SCREAMING_SNAKE_CASE_ : int = 0
SCREAMING_SNAKE_CASE_ : int = 0
SCREAMING_SNAKE_CASE_ : Optional[Any] = 0
SCREAMING_SNAKE_CASE_ : Tuple = 0
SCREAMING_SNAKE_CASE_ : Tuple = 0
SCREAMING_SNAKE_CASE_ : Optional[Any] = 0
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = reader.get_doc_mentions(SCREAMING_SNAKE_CASE , key_doc_lines[doc] , SCREAMING_SNAKE_CASE )
key_singletons_num += singletons_num
if NP_only or min_span:
SCREAMING_SNAKE_CASE_ : List[str] = reader.set_annotated_parse_trees(SCREAMING_SNAKE_CASE , key_doc_lines[doc] , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = reader.get_doc_mentions(SCREAMING_SNAKE_CASE , sys_doc_lines[doc] , SCREAMING_SNAKE_CASE )
sys_singletons_num += singletons_num
if NP_only or min_span:
SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.set_annotated_parse_trees(SCREAMING_SNAKE_CASE , key_doc_lines[doc] , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
if remove_nested:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = reader.remove_nested_coref_mentions(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
key_nested_coref_num += nested_mentions
key_removed_nested_clusters += removed_clusters
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = reader.remove_nested_coref_mentions(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
sys_nested_coref_num += nested_mentions
sys_removed_nested_clusters += removed_clusters
SCREAMING_SNAKE_CASE_ : Optional[int] = reader.get_mention_assignments(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ : List[str] = reader.get_mention_assignments(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ : Optional[Any] = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster)
if remove_nested:
logger.info(
'Number of removed nested coreferring mentions in the key '
f'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' )
logger.info(
'Number of resulting singleton clusters in the key '
f'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' )
if not keep_singletons:
logger.info(
f'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system '
'files, respectively' )
return doc_coref_infos
def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]:
SCREAMING_SNAKE_CASE_ : Optional[Any] = get_coref_infos(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ : Dict = {}
SCREAMING_SNAKE_CASE_ : int = 0
SCREAMING_SNAKE_CASE_ : List[str] = 0
for name, metric in metrics:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = evaluator.evaluate_documents(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , beta=1 )
if name in ["muc", "bcub", "ceafe"]:
conll += fa
conll_subparts_num += 1
output_scores.update({f'{name}/recall': recall, f'{name}/precision': precision, f'{name}/f1': fa} )
logger.info(
name.ljust(10 ) , f'Recall: {recall * 100:.2f}' , f' Precision: {precision * 100:.2f}' , f' F1: {fa * 100:.2f}' , )
if conll_subparts_num == 3:
SCREAMING_SNAKE_CASE_ : Dict = (conll / 3) * 100
logger.info(f'CoNLL score: {conll:.2f}' )
output_scores.update({'conll_score': conll} )
return output_scores
def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ) -> int:
SCREAMING_SNAKE_CASE_ : Dict = False
for line in key_lines:
if not line.startswith('#' ):
if len(line.split() ) > 6:
SCREAMING_SNAKE_CASE_ : Dict = line.split()[5]
if not parse_col == "-":
SCREAMING_SNAKE_CASE_ : int = True
break
else:
break
return has_gold_parse
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class snake_case_ ( datasets.Metric ):
def __A ( self ):
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'predictions': datasets.Sequence(datasets.Value('string' ) ),
'references': datasets.Sequence(datasets.Value('string' ) ),
} ) , codebase_urls=['https://github.com/ns-moosavi/coval'] , reference_urls=[
'https://github.com/ns-moosavi/coval',
'https://www.aclweb.org/anthology/P16-1060',
'http://www.conll.cemantix.org/2012/data.html',
] , )
def __A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=True , __lowerCAmelCase=False , __lowerCAmelCase=False , __lowerCAmelCase=False ):
SCREAMING_SNAKE_CASE_ : Any = [
('mentions', evaluator.mentions),
('muc', evaluator.muc),
('bcub', evaluator.b_cubed),
('ceafe', evaluator.ceafe),
('lea', evaluator.lea),
]
if min_span:
SCREAMING_SNAKE_CASE_ : Optional[int] = util.check_gold_parse_annotation(__lowerCAmelCase )
if not has_gold_parse:
raise NotImplementedError('References should have gold parse annotation to use \'min_span\'.' )
# util.parse_key_file(key_file)
# key_file = key_file + ".parsed"
SCREAMING_SNAKE_CASE_ : Optional[Any] = evaluate(
key_lines=__lowerCAmelCase , sys_lines=__lowerCAmelCase , metrics=__lowerCAmelCase , NP_only=__lowerCAmelCase , remove_nested=__lowerCAmelCase , keep_singletons=__lowerCAmelCase , min_span=__lowerCAmelCase , )
return score
| 345 | 1 |
"""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,
) | 700 |
"""simple docstring"""
from abc import ABC, abstractmethod
from argparse import ArgumentParser
class _SCREAMING_SNAKE_CASE ( __UpperCAmelCase ):
"""simple docstring"""
@staticmethod
@abstractmethod
def UpperCAmelCase__( lowerCamelCase__ ) -> Optional[Any]:
raise NotImplementedError()
@abstractmethod
def UpperCAmelCase__( self ) -> Dict:
raise NotImplementedError() | 128 | 0 |
from collections.abc import Sequence
from queue import Queue
class _SCREAMING_SNAKE_CASE :
def __init__( self , lowercase , lowercase , lowercase , lowercase=None , lowercase=None ) -> List[str]:
lowerCamelCase_ = start
lowerCamelCase_ = end
lowerCamelCase_ = val
lowerCamelCase_ = (start + end) // 2
lowerCamelCase_ = left
lowerCamelCase_ = right
def __repr__( self ) -> List[Any]:
return f'SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})'
class _SCREAMING_SNAKE_CASE :
def __init__( self , lowercase , lowercase ) -> Tuple:
lowerCamelCase_ = collection
lowerCamelCase_ = function
if self.collection:
lowerCamelCase_ = self._build_tree(0 , len(_SCREAMING_SNAKE_CASE ) - 1 )
def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase ) -> Optional[Any]:
self._update_tree(self.root , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase ) -> int:
return self._query_range(self.root , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase ) -> int:
if start == end:
return SegmentTreeNode(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.collection[start] )
lowerCamelCase_ = (start + end) // 2
lowerCamelCase_ = self._build_tree(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
lowerCamelCase_ = self._build_tree(mid + 1 , _SCREAMING_SNAKE_CASE )
return SegmentTreeNode(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.fn(left.val , right.val ) , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase , lowercase ) -> List[str]:
if node.start == i and node.end == i:
lowerCamelCase_ = val
return
if i <= node.mid:
self._update_tree(node.left , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
else:
self._update_tree(node.right , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
lowerCamelCase_ = self.fn(node.left.val , node.right.val )
def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase , lowercase ) -> Union[str, Any]:
if node.start == i and node.end == j:
return node.val
if i <= node.mid:
if j <= node.mid:
# range in left child tree
return self._query_range(node.left , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
else:
# range in left child tree and right child tree
return self.fn(
self._query_range(node.left , _SCREAMING_SNAKE_CASE , node.mid ) , self._query_range(node.right , node.mid + 1 , _SCREAMING_SNAKE_CASE ) , )
else:
# range in right child tree
return self._query_range(node.right , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
def SCREAMING_SNAKE_CASE_( self ) -> Optional[int]:
if self.root is not None:
lowerCamelCase_ = Queue()
queue.put(self.root )
while not queue.empty():
lowerCamelCase_ = queue.get()
yield node
if node.left is not None:
queue.put(node.left )
if node.right is not None:
queue.put(node.right )
if __name__ == "__main__":
import operator
for fn in [operator.add, max, min]:
print('''*''' * 5_0)
__A =SegmentTree([2, 1, 5, 3, 4], fn)
for node in arr.traverse():
print(node)
print()
arr.update(1, 5)
for node in arr.traverse():
print(node)
print()
print(arr.query_range(3, 4)) # 7
print(arr.query_range(2, 2)) # 5
print(arr.query_range(1, 3)) # 13
print()
| 463 |
import torch
from torch import nn
class A__ ( nn.Module ):
'''simple docstring'''
def __init__( self : List[str] , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[int]=1 , _SCREAMING_SNAKE_CASE : List[str]=False ):
"""simple docstring"""
super().__init__()
UpperCamelCase = n_token
UpperCamelCase = d_embed
UpperCamelCase = d_proj
UpperCamelCase = cutoffs + [n_token]
UpperCamelCase = [0] + self.cutoffs
UpperCamelCase = div_val
UpperCamelCase = self.cutoffs[0]
UpperCamelCase = len(self.cutoffs ) - 1
UpperCamelCase = self.shortlist_size + self.n_clusters
if self.n_clusters > 0:
UpperCamelCase = nn.Parameter(torch.zeros(self.n_clusters , self.d_embed ) )
UpperCamelCase = nn.Parameter(torch.zeros(self.n_clusters ) )
UpperCamelCase = nn.ModuleList()
UpperCamelCase = nn.ParameterList()
if div_val == 1:
for i in range(len(self.cutoffs ) ):
if d_proj != d_embed:
self.out_projs.append(nn.Parameter(torch.FloatTensor(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) )
else:
self.out_projs.append(_SCREAMING_SNAKE_CASE )
self.out_layers.append(nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) )
else:
for i in range(len(self.cutoffs ) ):
UpperCamelCase , UpperCamelCase = self.cutoff_ends[i], self.cutoff_ends[i + 1]
UpperCamelCase = d_embed // (div_val**i)
self.out_projs.append(nn.Parameter(torch.FloatTensor(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) )
self.out_layers.append(nn.Linear(_SCREAMING_SNAKE_CASE , r_idx - l_idx ) )
UpperCamelCase = keep_order
def _SCREAMING_SNAKE_CASE ( self : Dict , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Dict ):
"""simple docstring"""
if proj is None:
UpperCamelCase = nn.functional.linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , bias=_SCREAMING_SNAKE_CASE )
else:
# if CUDA_MAJOR <= 9 and CUDA_MINOR <= 1:
UpperCamelCase = nn.functional.linear(_SCREAMING_SNAKE_CASE , proj.t().contiguous() )
UpperCamelCase = nn.functional.linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , bias=_SCREAMING_SNAKE_CASE )
# else:
# logit = torch.einsum('bd,de,ev->bv', (hidden, proj, weight.t()))
# if bias is not None:
# logit = logit + bias
return logit
def _SCREAMING_SNAKE_CASE ( self : List[Any] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[Any]=None , _SCREAMING_SNAKE_CASE : Dict=False ):
"""simple docstring"""
if labels is not None:
# Shift so that tokens < n predict n
UpperCamelCase = hidden[..., :-1, :].contiguous()
UpperCamelCase = labels[..., 1:].contiguous()
UpperCamelCase = hidden.view(-1 , hidden.size(-1 ) )
UpperCamelCase = labels.view(-1 )
if hidden.size(0 ) != labels.size(0 ):
raise RuntimeError('Input and labels should have the same size in the batch dimension.' )
else:
UpperCamelCase = hidden.view(-1 , hidden.size(-1 ) )
if self.n_clusters == 0:
UpperCamelCase = self._compute_logit(_SCREAMING_SNAKE_CASE , self.out_layers[0].weight , self.out_layers[0].bias , self.out_projs[0] )
if labels is not None:
UpperCamelCase = labels != -100
UpperCamelCase = torch.zeros_like(_SCREAMING_SNAKE_CASE , dtype=hidden.dtype , device=hidden.device )
UpperCamelCase = (
-nn.functional.log_softmax(_SCREAMING_SNAKE_CASE , dim=-1 )[mask].gather(1 , labels[mask].unsqueeze(1 ) ).squeeze(1 )
)
else:
UpperCamelCase = nn.functional.log_softmax(_SCREAMING_SNAKE_CASE , dim=-1 )
else:
# construct weights and biases
UpperCamelCase , UpperCamelCase = [], []
for i in range(len(self.cutoffs ) ):
if self.div_val == 1:
UpperCamelCase , UpperCamelCase = self.cutoff_ends[i], self.cutoff_ends[i + 1]
UpperCamelCase = self.out_layers[0].weight[l_idx:r_idx]
UpperCamelCase = self.out_layers[0].bias[l_idx:r_idx]
else:
UpperCamelCase = self.out_layers[i].weight
UpperCamelCase = self.out_layers[i].bias
if i == 0:
UpperCamelCase = torch.cat([weight_i, self.cluster_weight] , dim=0 )
UpperCamelCase = torch.cat([bias_i, self.cluster_bias] , dim=0 )
weights.append(_SCREAMING_SNAKE_CASE )
biases.append(_SCREAMING_SNAKE_CASE )
UpperCamelCase , UpperCamelCase , UpperCamelCase = weights[0], biases[0], self.out_projs[0]
UpperCamelCase = self._compute_logit(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
UpperCamelCase = nn.functional.log_softmax(_SCREAMING_SNAKE_CASE , dim=1 )
if labels is None:
UpperCamelCase = hidden.new_empty((head_logit.size(0 ), self.n_token) )
else:
UpperCamelCase = torch.zeros_like(_SCREAMING_SNAKE_CASE , dtype=hidden.dtype , device=hidden.device )
UpperCamelCase = 0
UpperCamelCase = [0] + self.cutoffs
for i in range(len(_SCREAMING_SNAKE_CASE ) - 1 ):
UpperCamelCase , UpperCamelCase = cutoff_values[i], cutoff_values[i + 1]
if labels is not None:
UpperCamelCase = (labels >= l_idx) & (labels < r_idx)
UpperCamelCase = mask_i.nonzero().squeeze()
if indices_i.numel() == 0:
continue
UpperCamelCase = labels.index_select(0 , _SCREAMING_SNAKE_CASE ) - l_idx
UpperCamelCase = head_logprob.index_select(0 , _SCREAMING_SNAKE_CASE )
UpperCamelCase = hidden.index_select(0 , _SCREAMING_SNAKE_CASE )
else:
UpperCamelCase = hidden
if i == 0:
if labels is not None:
UpperCamelCase = head_logprob_i.gather(1 , target_i[:, None] ).squeeze(1 )
else:
UpperCamelCase = head_logprob[:, : self.cutoffs[0]]
else:
UpperCamelCase , UpperCamelCase , UpperCamelCase = weights[i], biases[i], self.out_projs[i]
UpperCamelCase = self._compute_logit(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
UpperCamelCase = nn.functional.log_softmax(_SCREAMING_SNAKE_CASE , dim=1 )
UpperCamelCase = self.cutoffs[0] + i - 1 # No probability for the head cluster
if labels is not None:
UpperCamelCase = head_logprob_i[:, cluster_prob_idx] + tail_logprob_i.gather(
1 , target_i[:, None] ).squeeze(1 )
else:
UpperCamelCase = head_logprob[:, cluster_prob_idx, None] + tail_logprob_i
UpperCamelCase = logprob_i
if labels is not None:
if (hasattr(self , 'keep_order' ) and self.keep_order) or keep_order:
out.index_copy_(0 , _SCREAMING_SNAKE_CASE , -logprob_i )
else:
out[offset : offset + logprob_i.size(0 )].copy_(-logprob_i )
offset += logprob_i.size(0 )
return out
def _SCREAMING_SNAKE_CASE ( self : int , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
if self.n_clusters == 0:
UpperCamelCase = self._compute_logit(_SCREAMING_SNAKE_CASE , self.out_layers[0].weight , self.out_layers[0].bias , self.out_projs[0] )
return nn.functional.log_softmax(_SCREAMING_SNAKE_CASE , dim=-1 )
else:
# construct weights and biases
UpperCamelCase , UpperCamelCase = [], []
for i in range(len(self.cutoffs ) ):
if self.div_val == 1:
UpperCamelCase , UpperCamelCase = self.cutoff_ends[i], self.cutoff_ends[i + 1]
UpperCamelCase = self.out_layers[0].weight[l_idx:r_idx]
UpperCamelCase = self.out_layers[0].bias[l_idx:r_idx]
else:
UpperCamelCase = self.out_layers[i].weight
UpperCamelCase = self.out_layers[i].bias
if i == 0:
UpperCamelCase = torch.cat([weight_i, self.cluster_weight] , dim=0 )
UpperCamelCase = torch.cat([bias_i, self.cluster_bias] , dim=0 )
weights.append(_SCREAMING_SNAKE_CASE )
biases.append(_SCREAMING_SNAKE_CASE )
UpperCamelCase , UpperCamelCase , UpperCamelCase = weights[0], biases[0], self.out_projs[0]
UpperCamelCase = self._compute_logit(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
UpperCamelCase = hidden.new_empty((head_logit.size(0 ), self.n_token) )
UpperCamelCase = nn.functional.log_softmax(_SCREAMING_SNAKE_CASE , dim=1 )
UpperCamelCase = [0] + self.cutoffs
for i in range(len(_SCREAMING_SNAKE_CASE ) - 1 ):
UpperCamelCase , UpperCamelCase = cutoff_values[i], cutoff_values[i + 1]
if i == 0:
UpperCamelCase = head_logprob[:, : self.cutoffs[0]]
else:
UpperCamelCase , UpperCamelCase , UpperCamelCase = weights[i], biases[i], self.out_projs[i]
UpperCamelCase = self._compute_logit(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
UpperCamelCase = nn.functional.log_softmax(_SCREAMING_SNAKE_CASE , dim=1 )
UpperCamelCase = head_logprob[:, -i] + tail_logprob_i
UpperCamelCase = logprob_i
return out
| 280 | 0 |
'''simple docstring'''
import re
import tempfile
from pathlib import Path
import pytest
import yaml
from datasets.utils.readme import ReadMe
# @pytest.fixture
# def example_yaml_structure():
_UpperCAmelCase : List[str] = yaml.safe_load(
"""\
name: \"\"
allow_empty: false
allow_empty_text: true
subsections:
- name: \"Dataset Card for X\" # First-level markdown heading
allow_empty: false
allow_empty_text: true
subsections:
- name: \"Table of Contents\"
allow_empty: false
allow_empty_text: false
subsections: null
- name: \"Dataset Description\"
allow_empty: false
allow_empty_text: false
subsections:
- name: \"Dataset Summary\"
allow_empty: false
allow_empty_text: false
subsections: null
- name: \"Supported Tasks and Leaderboards\"
allow_empty: true
allow_empty_text: true
subsections: null
- name: Languages
allow_empty: false
allow_empty_text: true
subsections: null
"""
)
_UpperCAmelCase : Tuple = {
"""name""": """root""",
"""text""": """""",
"""is_empty_text""": True,
"""subsections""": [
{
"""name""": """Dataset Card for My Dataset""",
"""text""": """""",
"""is_empty_text""": True,
"""subsections""": [
{"""name""": """Table of Contents""", """text""": """Some text here.""", """is_empty_text""": False, """subsections""": []},
{
"""name""": """Dataset Description""",
"""text""": """Some text here.""",
"""is_empty_text""": False,
"""subsections""": [
{
"""name""": """Dataset Summary""",
"""text""": """Some text here.""",
"""is_empty_text""": False,
"""subsections""": [],
},
{
"""name""": """Supported Tasks and Leaderboards""",
"""text""": """""",
"""is_empty_text""": True,
"""subsections""": [],
},
{"""name""": """Languages""", """text""": """Language Text""", """is_empty_text""": False, """subsections""": []},
],
},
],
}
],
}
_UpperCAmelCase : Dict = """\
---
language:
- zh
- en
---
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""
_UpperCAmelCase : List[str] = """\
---
language:
- zh
- en
---
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
#### Extra Ignored Subsection
### Supported Tasks and Leaderboards
### Languages
Language Text
"""
_UpperCAmelCase : str = {
"""name""": """root""",
"""text""": """""",
"""is_empty_text""": True,
"""subsections""": [
{
"""name""": """Dataset Card for My Dataset""",
"""text""": """""",
"""is_empty_text""": True,
"""subsections""": [
{"""name""": """Table of Contents""", """text""": """Some text here.""", """is_empty_text""": False, """subsections""": []},
{
"""name""": """Dataset Description""",
"""text""": """Some text here.""",
"""is_empty_text""": False,
"""subsections""": [
{
"""name""": """Dataset Summary""",
"""text""": """Some text here.""",
"""is_empty_text""": False,
"""subsections""": [
{
"""name""": """Extra Ignored Subsection""",
"""text""": """""",
"""is_empty_text""": True,
"""subsections""": [],
}
],
},
{
"""name""": """Supported Tasks and Leaderboards""",
"""text""": """""",
"""is_empty_text""": True,
"""subsections""": [],
},
{"""name""": """Languages""", """text""": """Language Text""", """is_empty_text""": False, """subsections""": []},
],
},
],
}
],
}
_UpperCAmelCase : List[Any] = """\
---
---
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""
_UpperCAmelCase : Any = (
"""The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README."""
)
_UpperCAmelCase : Dict = """\
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""
_UpperCAmelCase : int = (
"""The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README."""
)
_UpperCAmelCase : List[str] = """\
---
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""
_UpperCAmelCase : int = """The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README."""
_UpperCAmelCase : Union[str, Any] = """\
---
language:
- zh
- en
---
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
### Supported Tasks and Leaderboards
### Languages
Language Text
"""
_UpperCAmelCase : Any = """The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored)."""
_UpperCAmelCase : List[str] = """\
---
language:
- zh
- en
---
# Dataset Card for My Dataset
"""
_UpperCAmelCase : Dict = """The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found 'None'."""
_UpperCAmelCase : int = """\
---
language:
- zh
- en
---
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Languages
Language Text
"""
_UpperCAmelCase : Dict = """The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`."""
_UpperCAmelCase : Union[str, Any] = """\
---
language:
- zh
- en
---
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
"""
_UpperCAmelCase : List[Any] = """The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty."""
_UpperCAmelCase : Optional[Any] = """\
---
language:
- zh
- en
---
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""
_UpperCAmelCase : List[Any] = """The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README."""
_UpperCAmelCase : str = """\
---
language:
- zh
- en
---
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
# Dataset Card My Dataset
"""
_UpperCAmelCase : List[str] = """The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README."""
_UpperCAmelCase : str = """\
---
language:
- zh
- en
---
# Dataset Card My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""
_UpperCAmelCase : int = """The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README."""
_UpperCAmelCase : List[str] = """"""
_UpperCAmelCase : Dict = """The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README."""
_UpperCAmelCase : Tuple = """\
---
language:
- zh
- en
---
# Dataset Card for My Dataset
# Dataset Card for My Dataset
## Table of Contents
Some text here.
## Dataset Description
Some text here.
### Dataset Summary
Some text here.
### Supported Tasks and Leaderboards
### Languages
Language Text
"""
_UpperCAmelCase : str = """The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections."""
@pytest.mark.parametrize(
'''readme_md, expected_dict''', [
(README_CORRECT, CORRECT_DICT),
(README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL),
], )
def __magic_name__( lowerCamelCase, lowerCamelCase ):
assert ReadMe.from_string(lowerCamelCase, lowerCamelCase ).to_dict() == expected_dict
@pytest.mark.parametrize(
'''readme_md, expected_error''', [
(README_NO_YAML, EXPECTED_ERROR_README_NO_YAML),
(README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML),
(README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML),
(README_EMPTY, EXPECTED_ERROR_README_EMPTY),
(README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION),
(README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL),
(README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION),
(README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT),
(README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL),
(README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL),
(README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT),
], )
def __magic_name__( lowerCamelCase, lowerCamelCase ):
with pytest.raises(lowerCamelCase, match=re.escape(expected_error.format(path='''root''' ) ) ):
__lowerCAmelCase = ReadMe.from_string(lowerCamelCase, lowerCamelCase )
readme.validate()
@pytest.mark.parametrize(
'''readme_md, expected_error''', [
(README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1),
], )
def __magic_name__( lowerCamelCase, lowerCamelCase ):
with pytest.raises(lowerCamelCase, match=re.escape(expected_error.format(path='''root''' ) ) ):
ReadMe.from_string(lowerCamelCase, lowerCamelCase )
@pytest.mark.parametrize(
'''readme_md,''', [
(README_MULTIPLE_SAME_HEADING_1),
], )
def __magic_name__( lowerCamelCase ):
ReadMe.from_string(lowerCamelCase, lowerCamelCase, suppress_parsing_errors=lowerCamelCase )
@pytest.mark.parametrize(
'''readme_md, expected_dict''', [
(README_CORRECT, CORRECT_DICT),
(README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL),
], )
def __magic_name__( lowerCamelCase, lowerCamelCase ):
with tempfile.TemporaryDirectory() as tmp_dir:
__lowerCAmelCase = Path(lowerCamelCase ) / '''README.md'''
with open(lowerCamelCase, '''w+''' ) as readme_file:
readme_file.write(lowerCamelCase )
__lowerCAmelCase = ReadMe.from_readme(lowerCamelCase, lowerCamelCase ).to_dict()
assert out["name"] == path
assert out["text"] == ""
assert out["is_empty_text"]
assert out["subsections"] == expected_dict["subsections"]
@pytest.mark.parametrize(
'''readme_md, expected_error''', [
(README_NO_YAML, EXPECTED_ERROR_README_NO_YAML),
(README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML),
(README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML),
(README_EMPTY, EXPECTED_ERROR_README_EMPTY),
(README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION),
(README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL),
(README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION),
(README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT),
(README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL),
(README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL),
(README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT),
], )
def __magic_name__( lowerCamelCase, lowerCamelCase ):
with tempfile.TemporaryDirectory() as tmp_dir:
__lowerCAmelCase = Path(lowerCamelCase ) / '''README.md'''
with open(lowerCamelCase, '''w+''' ) as readme_file:
readme_file.write(lowerCamelCase )
__lowerCAmelCase = expected_error.format(path=lowerCamelCase )
with pytest.raises(lowerCamelCase, match=re.escape(lowerCamelCase ) ):
__lowerCAmelCase = ReadMe.from_readme(lowerCamelCase, lowerCamelCase )
readme.validate()
@pytest.mark.parametrize(
'''readme_md, expected_error''', [
(README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1),
], )
def __magic_name__( lowerCamelCase, lowerCamelCase ):
with tempfile.TemporaryDirectory() as tmp_dir:
__lowerCAmelCase = Path(lowerCamelCase ) / '''README.md'''
with open(lowerCamelCase, '''w+''' ) as readme_file:
readme_file.write(lowerCamelCase )
__lowerCAmelCase = expected_error.format(path=lowerCamelCase )
with pytest.raises(lowerCamelCase, match=re.escape(lowerCamelCase ) ):
ReadMe.from_readme(lowerCamelCase, lowerCamelCase )
@pytest.mark.parametrize(
'''readme_md,''', [
(README_MULTIPLE_SAME_HEADING_1),
], )
def __magic_name__( lowerCamelCase ):
with tempfile.TemporaryDirectory() as tmp_dir:
__lowerCAmelCase = Path(lowerCamelCase ) / '''README.md'''
with open(lowerCamelCase, '''w+''' ) as readme_file:
readme_file.write(lowerCamelCase )
ReadMe.from_readme(lowerCamelCase, lowerCamelCase, suppress_parsing_errors=lowerCamelCase )
| 710 |
'''simple docstring'''
import argparse
import json
from collections import OrderedDict
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import (
ConditionalDetrConfig,
ConditionalDetrForObjectDetection,
ConditionalDetrForSegmentation,
ConditionalDetrImageProcessor,
)
from transformers.utils import logging
logging.set_verbosity_info()
_UpperCAmelCase : Optional[int] = logging.get_logger(__name__)
# here we list all keys to be renamed (original name on the left, our name on the right)
_UpperCAmelCase : Any = []
for i in range(6):
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
rename_keys.append(
(f"""transformer.encoder.layers.{i}.self_attn.out_proj.weight""", f"""encoder.layers.{i}.self_attn.out_proj.weight""")
)
rename_keys.append(
(f"""transformer.encoder.layers.{i}.self_attn.out_proj.bias""", f"""encoder.layers.{i}.self_attn.out_proj.bias""")
)
rename_keys.append((f"""transformer.encoder.layers.{i}.linear1.weight""", f"""encoder.layers.{i}.fc1.weight"""))
rename_keys.append((f"""transformer.encoder.layers.{i}.linear1.bias""", f"""encoder.layers.{i}.fc1.bias"""))
rename_keys.append((f"""transformer.encoder.layers.{i}.linear2.weight""", f"""encoder.layers.{i}.fc2.weight"""))
rename_keys.append((f"""transformer.encoder.layers.{i}.linear2.bias""", f"""encoder.layers.{i}.fc2.bias"""))
rename_keys.append(
(f"""transformer.encoder.layers.{i}.norm1.weight""", f"""encoder.layers.{i}.self_attn_layer_norm.weight""")
)
rename_keys.append((f"""transformer.encoder.layers.{i}.norm1.bias""", f"""encoder.layers.{i}.self_attn_layer_norm.bias"""))
rename_keys.append((f"""transformer.encoder.layers.{i}.norm2.weight""", f"""encoder.layers.{i}.final_layer_norm.weight"""))
rename_keys.append((f"""transformer.encoder.layers.{i}.norm2.bias""", f"""encoder.layers.{i}.final_layer_norm.bias"""))
# decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms
rename_keys.append(
(f"""transformer.decoder.layers.{i}.self_attn.out_proj.weight""", f"""decoder.layers.{i}.self_attn.out_proj.weight""")
)
rename_keys.append(
(f"""transformer.decoder.layers.{i}.self_attn.out_proj.bias""", f"""decoder.layers.{i}.self_attn.out_proj.bias""")
)
rename_keys.append(
(
f"""transformer.decoder.layers.{i}.cross_attn.out_proj.weight""",
f"""decoder.layers.{i}.encoder_attn.out_proj.weight""",
)
)
rename_keys.append(
(
f"""transformer.decoder.layers.{i}.cross_attn.out_proj.bias""",
f"""decoder.layers.{i}.encoder_attn.out_proj.bias""",
)
)
rename_keys.append((f"""transformer.decoder.layers.{i}.linear1.weight""", f"""decoder.layers.{i}.fc1.weight"""))
rename_keys.append((f"""transformer.decoder.layers.{i}.linear1.bias""", f"""decoder.layers.{i}.fc1.bias"""))
rename_keys.append((f"""transformer.decoder.layers.{i}.linear2.weight""", f"""decoder.layers.{i}.fc2.weight"""))
rename_keys.append((f"""transformer.decoder.layers.{i}.linear2.bias""", f"""decoder.layers.{i}.fc2.bias"""))
rename_keys.append(
(f"""transformer.decoder.layers.{i}.norm1.weight""", f"""decoder.layers.{i}.self_attn_layer_norm.weight""")
)
rename_keys.append((f"""transformer.decoder.layers.{i}.norm1.bias""", f"""decoder.layers.{i}.self_attn_layer_norm.bias"""))
rename_keys.append(
(f"""transformer.decoder.layers.{i}.norm2.weight""", f"""decoder.layers.{i}.encoder_attn_layer_norm.weight""")
)
rename_keys.append(
(f"""transformer.decoder.layers.{i}.norm2.bias""", f"""decoder.layers.{i}.encoder_attn_layer_norm.bias""")
)
rename_keys.append((f"""transformer.decoder.layers.{i}.norm3.weight""", f"""decoder.layers.{i}.final_layer_norm.weight"""))
rename_keys.append((f"""transformer.decoder.layers.{i}.norm3.bias""", f"""decoder.layers.{i}.final_layer_norm.bias"""))
# q, k, v projections in self/cross-attention in decoder for conditional DETR
rename_keys.append(
(f"""transformer.decoder.layers.{i}.sa_qcontent_proj.weight""", f"""decoder.layers.{i}.sa_qcontent_proj.weight""")
)
rename_keys.append(
(f"""transformer.decoder.layers.{i}.sa_kcontent_proj.weight""", f"""decoder.layers.{i}.sa_kcontent_proj.weight""")
)
rename_keys.append(
(f"""transformer.decoder.layers.{i}.sa_qpos_proj.weight""", f"""decoder.layers.{i}.sa_qpos_proj.weight""")
)
rename_keys.append(
(f"""transformer.decoder.layers.{i}.sa_kpos_proj.weight""", f"""decoder.layers.{i}.sa_kpos_proj.weight""")
)
rename_keys.append((f"""transformer.decoder.layers.{i}.sa_v_proj.weight""", f"""decoder.layers.{i}.sa_v_proj.weight"""))
rename_keys.append(
(f"""transformer.decoder.layers.{i}.ca_qcontent_proj.weight""", f"""decoder.layers.{i}.ca_qcontent_proj.weight""")
)
# rename_keys.append((f"transformer.decoder.layers.{i}.ca_qpos_proj.weight", f"decoder.layers.{i}.ca_qpos_proj.weight"))
rename_keys.append(
(f"""transformer.decoder.layers.{i}.ca_kcontent_proj.weight""", f"""decoder.layers.{i}.ca_kcontent_proj.weight""")
)
rename_keys.append(
(f"""transformer.decoder.layers.{i}.ca_kpos_proj.weight""", f"""decoder.layers.{i}.ca_kpos_proj.weight""")
)
rename_keys.append((f"""transformer.decoder.layers.{i}.ca_v_proj.weight""", f"""decoder.layers.{i}.ca_v_proj.weight"""))
rename_keys.append(
(f"""transformer.decoder.layers.{i}.ca_qpos_sine_proj.weight""", f"""decoder.layers.{i}.ca_qpos_sine_proj.weight""")
)
rename_keys.append(
(f"""transformer.decoder.layers.{i}.sa_qcontent_proj.bias""", f"""decoder.layers.{i}.sa_qcontent_proj.bias""")
)
rename_keys.append(
(f"""transformer.decoder.layers.{i}.sa_kcontent_proj.bias""", f"""decoder.layers.{i}.sa_kcontent_proj.bias""")
)
rename_keys.append((f"""transformer.decoder.layers.{i}.sa_qpos_proj.bias""", f"""decoder.layers.{i}.sa_qpos_proj.bias"""))
rename_keys.append((f"""transformer.decoder.layers.{i}.sa_kpos_proj.bias""", f"""decoder.layers.{i}.sa_kpos_proj.bias"""))
rename_keys.append((f"""transformer.decoder.layers.{i}.sa_v_proj.bias""", f"""decoder.layers.{i}.sa_v_proj.bias"""))
rename_keys.append(
(f"""transformer.decoder.layers.{i}.ca_qcontent_proj.bias""", f"""decoder.layers.{i}.ca_qcontent_proj.bias""")
)
# rename_keys.append((f"transformer.decoder.layers.{i}.ca_qpos_proj.bias", f"decoder.layers.{i}.ca_qpos_proj.bias"))
rename_keys.append(
(f"""transformer.decoder.layers.{i}.ca_kcontent_proj.bias""", f"""decoder.layers.{i}.ca_kcontent_proj.bias""")
)
rename_keys.append((f"""transformer.decoder.layers.{i}.ca_kpos_proj.bias""", f"""decoder.layers.{i}.ca_kpos_proj.bias"""))
rename_keys.append((f"""transformer.decoder.layers.{i}.ca_v_proj.bias""", f"""decoder.layers.{i}.ca_v_proj.bias"""))
rename_keys.append(
(f"""transformer.decoder.layers.{i}.ca_qpos_sine_proj.bias""", f"""decoder.layers.{i}.ca_qpos_sine_proj.bias""")
)
# convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads
# for conditional DETR, also convert reference point head and query scale MLP
rename_keys.extend(
[
("""input_proj.weight""", """input_projection.weight"""),
("""input_proj.bias""", """input_projection.bias"""),
("""query_embed.weight""", """query_position_embeddings.weight"""),
("""transformer.decoder.norm.weight""", """decoder.layernorm.weight"""),
("""transformer.decoder.norm.bias""", """decoder.layernorm.bias"""),
("""class_embed.weight""", """class_labels_classifier.weight"""),
("""class_embed.bias""", """class_labels_classifier.bias"""),
("""bbox_embed.layers.0.weight""", """bbox_predictor.layers.0.weight"""),
("""bbox_embed.layers.0.bias""", """bbox_predictor.layers.0.bias"""),
("""bbox_embed.layers.1.weight""", """bbox_predictor.layers.1.weight"""),
("""bbox_embed.layers.1.bias""", """bbox_predictor.layers.1.bias"""),
("""bbox_embed.layers.2.weight""", """bbox_predictor.layers.2.weight"""),
("""bbox_embed.layers.2.bias""", """bbox_predictor.layers.2.bias"""),
("""transformer.decoder.ref_point_head.layers.0.weight""", """decoder.ref_point_head.layers.0.weight"""),
("""transformer.decoder.ref_point_head.layers.0.bias""", """decoder.ref_point_head.layers.0.bias"""),
("""transformer.decoder.ref_point_head.layers.1.weight""", """decoder.ref_point_head.layers.1.weight"""),
("""transformer.decoder.ref_point_head.layers.1.bias""", """decoder.ref_point_head.layers.1.bias"""),
("""transformer.decoder.query_scale.layers.0.weight""", """decoder.query_scale.layers.0.weight"""),
("""transformer.decoder.query_scale.layers.0.bias""", """decoder.query_scale.layers.0.bias"""),
("""transformer.decoder.query_scale.layers.1.weight""", """decoder.query_scale.layers.1.weight"""),
("""transformer.decoder.query_scale.layers.1.bias""", """decoder.query_scale.layers.1.bias"""),
("""transformer.decoder.layers.0.ca_qpos_proj.weight""", """decoder.layers.0.ca_qpos_proj.weight"""),
("""transformer.decoder.layers.0.ca_qpos_proj.bias""", """decoder.layers.0.ca_qpos_proj.bias"""),
]
)
def __magic_name__( lowerCamelCase, lowerCamelCase, lowerCamelCase):
__lowerCAmelCase = state_dict.pop(lowerCamelCase)
__lowerCAmelCase = val
def __magic_name__( lowerCamelCase):
__lowerCAmelCase = OrderedDict()
for key, value in state_dict.items():
if "backbone.0.body" in key:
__lowerCAmelCase = key.replace('''backbone.0.body''', '''backbone.conv_encoder.model''')
__lowerCAmelCase = value
else:
__lowerCAmelCase = value
return new_state_dict
def __magic_name__( lowerCamelCase, lowerCamelCase=False):
__lowerCAmelCase = ''''''
if is_panoptic:
__lowerCAmelCase = '''conditional_detr.'''
# first: transformer encoder
for i in range(6):
# read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias)
__lowerCAmelCase = state_dict.pop(F"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight""")
__lowerCAmelCase = state_dict.pop(F"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias""")
# next, add query, keys and values (in that order) to the state dict
__lowerCAmelCase = in_proj_weight[:2_5_6, :]
__lowerCAmelCase = in_proj_bias[:2_5_6]
__lowerCAmelCase = in_proj_weight[2_5_6:5_1_2, :]
__lowerCAmelCase = in_proj_bias[2_5_6:5_1_2]
__lowerCAmelCase = in_proj_weight[-2_5_6:, :]
__lowerCAmelCase = in_proj_bias[-2_5_6:]
def __magic_name__( ):
__lowerCAmelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg'''
__lowerCAmelCase = Image.open(requests.get(lowerCamelCase, stream=lowerCamelCase).raw)
return im
@torch.no_grad()
def __magic_name__( lowerCamelCase, lowerCamelCase):
__lowerCAmelCase = ConditionalDetrConfig()
# set backbone and dilation attributes
if "resnet101" in model_name:
__lowerCAmelCase = '''resnet101'''
if "dc5" in model_name:
__lowerCAmelCase = True
__lowerCAmelCase = '''panoptic''' in model_name
if is_panoptic:
__lowerCAmelCase = 2_5_0
else:
__lowerCAmelCase = 9_1
__lowerCAmelCase = '''huggingface/label-files'''
__lowerCAmelCase = '''coco-detection-id2label.json'''
__lowerCAmelCase = json.load(open(hf_hub_download(lowerCamelCase, lowerCamelCase, repo_type='''dataset'''), '''r'''))
__lowerCAmelCase = {int(lowerCamelCase): v for k, v in idalabel.items()}
__lowerCAmelCase = idalabel
__lowerCAmelCase = {v: k for k, v in idalabel.items()}
# load image processor
__lowerCAmelCase = '''coco_panoptic''' if is_panoptic else '''coco_detection'''
__lowerCAmelCase = ConditionalDetrImageProcessor(format=lowerCamelCase)
# prepare image
__lowerCAmelCase = prepare_img()
__lowerCAmelCase = image_processor(images=lowerCamelCase, return_tensors='''pt''')
__lowerCAmelCase = encoding['''pixel_values''']
logger.info(F"""Converting model {model_name}...""")
# load original model from torch hub
__lowerCAmelCase = torch.hub.load('''DeppMeng/ConditionalDETR''', lowerCamelCase, pretrained=lowerCamelCase).eval()
__lowerCAmelCase = conditional_detr.state_dict()
# rename keys
for src, dest in rename_keys:
if is_panoptic:
__lowerCAmelCase = '''conditional_detr.''' + src
rename_key(lowerCamelCase, lowerCamelCase, lowerCamelCase)
__lowerCAmelCase = rename_backbone_keys(lowerCamelCase)
# query, key and value matrices need special treatment
read_in_q_k_v(lowerCamelCase, is_panoptic=lowerCamelCase)
# important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them
__lowerCAmelCase = '''conditional_detr.model.''' if is_panoptic else '''model.'''
for key in state_dict.copy().keys():
if is_panoptic:
if (
key.startswith('''conditional_detr''')
and not key.startswith('''class_labels_classifier''')
and not key.startswith('''bbox_predictor''')
):
__lowerCAmelCase = state_dict.pop(lowerCamelCase)
__lowerCAmelCase = val
elif "class_labels_classifier" in key or "bbox_predictor" in key:
__lowerCAmelCase = state_dict.pop(lowerCamelCase)
__lowerCAmelCase = val
elif key.startswith('''bbox_attention''') or key.startswith('''mask_head'''):
continue
else:
__lowerCAmelCase = state_dict.pop(lowerCamelCase)
__lowerCAmelCase = val
else:
if not key.startswith('''class_labels_classifier''') and not key.startswith('''bbox_predictor'''):
__lowerCAmelCase = state_dict.pop(lowerCamelCase)
__lowerCAmelCase = val
# finally, create HuggingFace model and load state dict
__lowerCAmelCase = ConditionalDetrForSegmentation(lowerCamelCase) if is_panoptic else ConditionalDetrForObjectDetection(lowerCamelCase)
model.load_state_dict(lowerCamelCase)
model.eval()
model.push_to_hub(repo_id=lowerCamelCase, organization='''DepuMeng''', commit_message='''Add model''')
# verify our conversion
__lowerCAmelCase = conditional_detr(lowerCamelCase)
__lowerCAmelCase = model(lowerCamelCase)
assert torch.allclose(outputs.logits, original_outputs['''pred_logits'''], atol=1E-4)
assert torch.allclose(outputs.pred_boxes, original_outputs['''pred_boxes'''], atol=1E-4)
if is_panoptic:
assert torch.allclose(outputs.pred_masks, original_outputs['''pred_masks'''], atol=1E-4)
# Save model and image processor
logger.info(F"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""")
Path(lowerCamelCase).mkdir(exist_ok=lowerCamelCase)
model.save_pretrained(lowerCamelCase)
image_processor.save_pretrained(lowerCamelCase)
if __name__ == "__main__":
_UpperCAmelCase : str = argparse.ArgumentParser()
parser.add_argument(
"""--model_name""",
default="""conditional_detr_resnet50""",
type=str,
help="""Name of the CONDITIONAL_DETR model you'd like to convert.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the folder to output PyTorch model."""
)
_UpperCAmelCase : Any = parser.parse_args()
convert_conditional_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path)
| 474 | 0 |
from __future__ import annotations
def A__ ( SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : int ) -> Optional[int]:
"""simple docstring"""
if len(SCREAMING_SNAKE_CASE_ ) == 0:
return False
_UpperCAmelCase = len(SCREAMING_SNAKE_CASE_ ) // 2
if a_list[midpoint] == item:
return True
if item < a_list[midpoint]:
return binary_search(a_list[:midpoint] , SCREAMING_SNAKE_CASE_ )
else:
return binary_search(a_list[midpoint + 1 :] , SCREAMING_SNAKE_CASE_ )
if __name__ == "__main__":
UpperCAmelCase_ = input("Enter numbers separated by comma:\n").strip()
UpperCAmelCase_ = [int(item.strip()) for item in user_input.split(",")]
UpperCAmelCase_ = int(input("Enter the number to be found in the list:\n").strip())
UpperCAmelCase_ = '''''' if binary_search(sequence, target) else '''not '''
print(f'''{target} was {not_str}found in {sequence}''') | 32 |
'''simple docstring'''
import gc
import random
import unittest
import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
enable_full_determinism()
class __lowerCamelCase ( unittest.TestCase ):
"""simple docstring"""
def A ( self : Union[str, Any]):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
@property
def A ( self : str):
_A : str = 1
_A : int = 3
_A : int = (32, 32)
_A : Any = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0)).to(SCREAMING_SNAKE_CASE)
return image
@property
def A ( self : Optional[Any]):
torch.manual_seed(0)
_A : List[str] = UNetaDConditionModel(
block_out_channels=(32, 32, 64) , layers_per_block=2 , sample_size=32 , in_channels=7 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=8 , use_linear_projection=SCREAMING_SNAKE_CASE , only_cross_attention=(True, True, False) , num_class_embeds=100 , )
return model
@property
def A ( self : List[str]):
torch.manual_seed(0)
_A : Optional[int] = AutoencoderKL(
block_out_channels=[32, 32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , )
return model
@property
def A ( self : Dict):
torch.manual_seed(0)
_A : Optional[Any] = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , )
return CLIPTextModel(SCREAMING_SNAKE_CASE)
def A ( self : int):
_A : str = 'cpu' # ensure determinism for the device-dependent torch.Generator
_A : List[Any] = self.dummy_cond_unet_upscale
_A : Tuple = DDPMScheduler()
_A : str = DDIMScheduler(prediction_type='v_prediction')
_A : List[str] = self.dummy_vae
_A : List[Any] = self.dummy_text_encoder
_A : Optional[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip')
_A : Tuple = self.dummy_image.cpu().permute(0 , 2 , 3 , 1)[0]
_A : Any = Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE)).convert('RGB').resize((64, 64))
# make sure here that pndm scheduler skips prk
_A : Optional[int] = StableDiffusionUpscalePipeline(
unet=SCREAMING_SNAKE_CASE , low_res_scheduler=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE , vae=SCREAMING_SNAKE_CASE , text_encoder=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , max_noise_level=350 , )
_A : Any = sd_pipe.to(SCREAMING_SNAKE_CASE)
sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE)
_A : List[str] = 'A painting of a squirrel eating a burger'
_A : str = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(0)
_A : int = sd_pipe(
[prompt] , image=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type='np' , )
_A : str = output.images
_A : str = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(0)
_A : Optional[int] = sd_pipe(
[prompt] , image=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type='np' , return_dict=SCREAMING_SNAKE_CASE , )[0]
_A : Any = image[0, -3:, -3:, -1]
_A : Optional[Any] = image_from_tuple[0, -3:, -3:, -1]
_A : str = low_res_image.size[0] * 4
assert image.shape == (1, expected_height_width, expected_height_width, 3)
_A : Union[str, Any] = np.array([0.3113, 0.3910, 0.4272, 0.4859, 0.5061, 0.4652, 0.5362, 0.5715, 0.5661])
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):
_A : str = 'cpu' # ensure determinism for the device-dependent torch.Generator
_A : Dict = self.dummy_cond_unet_upscale
_A : Optional[int] = DDPMScheduler()
_A : Dict = DDIMScheduler(prediction_type='v_prediction')
_A : int = self.dummy_vae
_A : Dict = self.dummy_text_encoder
_A : Union[str, Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip')
_A : List[str] = self.dummy_image.cpu().permute(0 , 2 , 3 , 1)[0]
_A : Union[str, Any] = Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE)).convert('RGB').resize((64, 64))
# make sure here that pndm scheduler skips prk
_A : str = StableDiffusionUpscalePipeline(
unet=SCREAMING_SNAKE_CASE , low_res_scheduler=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE , vae=SCREAMING_SNAKE_CASE , text_encoder=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , max_noise_level=350 , )
_A : List[str] = sd_pipe.to(SCREAMING_SNAKE_CASE)
sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE)
_A : Any = 'A painting of a squirrel eating a burger'
_A : Any = sd_pipe(
2 * [prompt] , image=2 * [low_res_image] , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type='np' , )
_A : str = output.images
assert image.shape[0] == 2
_A : List[str] = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(0)
_A : int = sd_pipe(
[prompt] , image=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , num_images_per_prompt=2 , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type='np' , )
_A : List[str] = output.images
assert image.shape[0] == 2
@unittest.skipIf(torch_device != 'cuda' , 'This test requires a GPU')
def A ( self : Tuple):
_A : Dict = self.dummy_cond_unet_upscale
_A : Tuple = DDPMScheduler()
_A : int = DDIMScheduler(prediction_type='v_prediction')
_A : Union[str, Any] = self.dummy_vae
_A : List[str] = self.dummy_text_encoder
_A : int = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip')
_A : Optional[int] = self.dummy_image.cpu().permute(0 , 2 , 3 , 1)[0]
_A : Optional[Any] = Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE)).convert('RGB').resize((64, 64))
# put models in fp16, except vae as it overflows in fp16
_A : int = unet.half()
_A : List[Any] = text_encoder.half()
# make sure here that pndm scheduler skips prk
_A : Any = StableDiffusionUpscalePipeline(
unet=SCREAMING_SNAKE_CASE , low_res_scheduler=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE , vae=SCREAMING_SNAKE_CASE , text_encoder=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , max_noise_level=350 , )
_A : Dict = sd_pipe.to(SCREAMING_SNAKE_CASE)
sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE)
_A : str = 'A painting of a squirrel eating a burger'
_A : str = torch.manual_seed(0)
_A : Optional[int] = sd_pipe(
[prompt] , image=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type='np' , ).images
_A : List[Any] = low_res_image.size[0] * 4
assert image.shape == (1, expected_height_width, expected_height_width, 3)
@slow
@require_torch_gpu
class __lowerCamelCase ( unittest.TestCase ):
"""simple docstring"""
def A ( self : str):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def A ( self : Any):
_A : Tuple = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/sd2-upscale/low_res_cat.png')
_A : Dict = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale'
'/upsampled_cat.npy')
_A : Optional[int] = 'stabilityai/stable-diffusion-x4-upscaler'
_A : int = StableDiffusionUpscalePipeline.from_pretrained(SCREAMING_SNAKE_CASE)
pipe.to(SCREAMING_SNAKE_CASE)
pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE)
pipe.enable_attention_slicing()
_A : List[Any] = 'a cat sitting on a park bench'
_A : str = torch.manual_seed(0)
_A : Any = pipe(
prompt=SCREAMING_SNAKE_CASE , image=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , output_type='np' , )
_A : Tuple = output.images[0]
assert image.shape == (512, 512, 3)
assert np.abs(expected_image - image).max() < 1e-3
def A ( self : List[Any]):
_A : List[Any] = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/sd2-upscale/low_res_cat.png')
_A : int = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale'
'/upsampled_cat_fp16.npy')
_A : Optional[int] = 'stabilityai/stable-diffusion-x4-upscaler'
_A : Any = StableDiffusionUpscalePipeline.from_pretrained(
SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , )
pipe.to(SCREAMING_SNAKE_CASE)
pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE)
pipe.enable_attention_slicing()
_A : Any = 'a cat sitting on a park bench'
_A : Optional[Any] = torch.manual_seed(0)
_A : Any = pipe(
prompt=SCREAMING_SNAKE_CASE , image=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , output_type='np' , )
_A : List[Any] = output.images[0]
assert image.shape == (512, 512, 3)
assert np.abs(expected_image - image).max() < 5e-1
def A ( self : int):
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated()
torch.cuda.reset_peak_memory_stats()
_A : Dict = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/sd2-upscale/low_res_cat.png')
_A : Any = 'stabilityai/stable-diffusion-x4-upscaler'
_A : Any = StableDiffusionUpscalePipeline.from_pretrained(
SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , )
pipe.to(SCREAMING_SNAKE_CASE)
pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE)
pipe.enable_attention_slicing(1)
pipe.enable_sequential_cpu_offload()
_A : Tuple = 'a cat sitting on a park bench'
_A : int = torch.manual_seed(0)
_A : int = pipe(
prompt=SCREAMING_SNAKE_CASE , image=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , num_inference_steps=5 , output_type='np' , )
_A : Dict = torch.cuda.max_memory_allocated()
# make sure that less than 2.9 GB is allocated
assert mem_bytes < 2.9 * 10**9
| 128 | 0 |
"""simple docstring"""
import math
import time
from transformers import Trainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics
if is_torch_tpu_available(check_device=False):
import torch_xla.core.xla_model as xm
import torch_xla.debug.metrics as met
class snake_case ( __lowercase ):
def __init__(self , *SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = eval_examples
SCREAMING_SNAKE_CASE_ = post_process_function
def _lowercase (self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_ = "eval" ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = self.eval_dataset if eval_dataset is None else eval_dataset
SCREAMING_SNAKE_CASE_ = self.get_eval_dataloader(SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = self.eval_examples if eval_examples is None else eval_examples
# Temporarily disable metric computation, we will do it in the loop here.
SCREAMING_SNAKE_CASE_ = self.compute_metrics
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
SCREAMING_SNAKE_CASE_ = time.time()
try:
SCREAMING_SNAKE_CASE_ = eval_loop(
SCREAMING_SNAKE_CASE_ , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=SCREAMING_SNAKE_CASE_ , metric_key_prefix=SCREAMING_SNAKE_CASE_ , )
finally:
SCREAMING_SNAKE_CASE_ = compute_metrics
SCREAMING_SNAKE_CASE_ = self.args.eval_batch_size * self.args.world_size
if f'{metric_key_prefix}_jit_compilation_time' in output.metrics:
start_time += output.metrics[f'{metric_key_prefix}_jit_compilation_time']
output.metrics.update(
speed_metrics(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) )
if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
# Only the main node write the results by default
SCREAMING_SNAKE_CASE_ = self.post_process_function(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , output.predictions )
SCREAMING_SNAKE_CASE_ = self.compute_metrics(SCREAMING_SNAKE_CASE_ )
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys() ):
if not key.startswith(f'{metric_key_prefix}_' ):
SCREAMING_SNAKE_CASE_ = metrics.pop(SCREAMING_SNAKE_CASE_ )
metrics.update(output.metrics )
else:
SCREAMING_SNAKE_CASE_ = output.metrics
if self.args.should_log:
# Only the main node log the results by default
self.log(SCREAMING_SNAKE_CASE_ )
if self.args.tpu_metrics_debug or self.args.debug:
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report() )
SCREAMING_SNAKE_CASE_ = self.callback_handler.on_evaluate(self.args , self.state , self.control , SCREAMING_SNAKE_CASE_ )
return metrics
def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_ = "test" ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = self.get_test_dataloader(SCREAMING_SNAKE_CASE_ )
# Temporarily disable metric computation, we will do it in the loop here.
SCREAMING_SNAKE_CASE_ = self.compute_metrics
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
SCREAMING_SNAKE_CASE_ = time.time()
try:
SCREAMING_SNAKE_CASE_ = eval_loop(
SCREAMING_SNAKE_CASE_ , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=SCREAMING_SNAKE_CASE_ , metric_key_prefix=SCREAMING_SNAKE_CASE_ , )
finally:
SCREAMING_SNAKE_CASE_ = compute_metrics
SCREAMING_SNAKE_CASE_ = self.args.eval_batch_size * self.args.world_size
if f'{metric_key_prefix}_jit_compilation_time' in output.metrics:
start_time += output.metrics[f'{metric_key_prefix}_jit_compilation_time']
output.metrics.update(
speed_metrics(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) )
if self.post_process_function is None or self.compute_metrics is None:
return output
SCREAMING_SNAKE_CASE_ = self.post_process_function(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , output.predictions , '''predict''' )
SCREAMING_SNAKE_CASE_ = self.compute_metrics(SCREAMING_SNAKE_CASE_ )
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys() ):
if not key.startswith(f'{metric_key_prefix}_' ):
SCREAMING_SNAKE_CASE_ = metrics.pop(SCREAMING_SNAKE_CASE_ )
metrics.update(output.metrics )
return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=SCREAMING_SNAKE_CASE_ ) | 628 |
"""simple docstring"""
import inspect
import logging
import os
import random
import shutil
import tempfile
import unittest
import pytest
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
from accelerate import Accelerator
from accelerate.test_utils import execute_subprocess_async, require_cuda
from accelerate.utils import ProjectConfiguration, set_seed
lowerCAmelCase__ = logging.getLogger(__name__)
def _lowerCamelCase ( __a=2, __a=3, __a=16, __a = 10, __a = 2 ):
def get_dataset(__a ):
SCREAMING_SNAKE_CASE_ = torch.randn(batch_size * n_batches, 1 )
return TensorDataset(__a, a * x + b + 0.1 * torch.randn(batch_size * n_batches, 1 ) )
SCREAMING_SNAKE_CASE_ = get_dataset(__a )
SCREAMING_SNAKE_CASE_ = get_dataset(__a )
SCREAMING_SNAKE_CASE_ = DataLoader(__a, shuffle=__a, batch_size=__a, num_workers=4 )
SCREAMING_SNAKE_CASE_ = DataLoader(__a, shuffle=__a, batch_size=__a, num_workers=4 )
return (train_dataloader, valid_dataloader)
def _lowerCamelCase ( __a, __a, __a, __a, __a, __a=None ):
SCREAMING_SNAKE_CASE_ = []
for epoch in range(__a ):
# Train quickly
model.train()
for batch in dataloader:
SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = batch
SCREAMING_SNAKE_CASE_ = model(__a )
SCREAMING_SNAKE_CASE_ = torch.nn.functional.mse_loss(__a, __a )
accelerator.backward(__a )
optimizer.step()
optimizer.zero_grad()
rands.append(random.random() ) # Introduce some randomness
if scheduler is not None:
scheduler.step()
return rands
class snake_case ( nn.Module ):
def __init__(self ):
"""simple docstring"""
super().__init__()
SCREAMING_SNAKE_CASE_ = nn.Parameter(torch.randn(1 ) )
SCREAMING_SNAKE_CASE_ = nn.Parameter(torch.randn(1 ) )
def _lowercase (self , SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
return x * self.a + self.b
class snake_case ( unittest.TestCase ):
def _lowercase (self ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmpdir:
set_seed(42 )
SCREAMING_SNAKE_CASE_ = DummyModel()
SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 )
SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders()
SCREAMING_SNAKE_CASE_ = ProjectConfiguration(total_limit=1 , project_dir=SCREAMING_SNAKE_CASE_ , automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ )
# Train baseline
SCREAMING_SNAKE_CASE_ = Accelerator(project_config=SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Save initial
accelerator.save_state()
# Save second state
accelerator.save_state()
self.assertEqual(len(os.listdir(accelerator.project_dir ) ) , 1 )
def _lowercase (self ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmpdir:
set_seed(42 )
SCREAMING_SNAKE_CASE_ = DummyModel()
SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 )
SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders()
# Train baseline
SCREAMING_SNAKE_CASE_ = Accelerator()
SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Save initial
SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , '''initial''' )
accelerator.save_state(SCREAMING_SNAKE_CASE_ )
((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item()
SCREAMING_SNAKE_CASE_ = optimizer.state_dict()
SCREAMING_SNAKE_CASE_ = train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item()
SCREAMING_SNAKE_CASE_ = optimizer.state_dict()
# Train partially
set_seed(42 )
SCREAMING_SNAKE_CASE_ = DummyModel()
SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 )
SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders()
SCREAMING_SNAKE_CASE_ = Accelerator()
SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
accelerator.load_state(SCREAMING_SNAKE_CASE_ )
((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item()
SCREAMING_SNAKE_CASE_ = optimizer.state_dict()
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = train(2 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Save everything
SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoint''' )
accelerator.save_state(SCREAMING_SNAKE_CASE_ )
# Load everything back in and make sure all states work
accelerator.load_state(SCREAMING_SNAKE_CASE_ )
test_rands += train(1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item()
SCREAMING_SNAKE_CASE_ = optimizer.state_dict()
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
def _lowercase (self ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmpdir:
set_seed(42 )
SCREAMING_SNAKE_CASE_ = DummyModel()
SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 )
SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders()
SCREAMING_SNAKE_CASE_ = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ )
# Train baseline
SCREAMING_SNAKE_CASE_ = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Save initial
accelerator.save_state()
((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item()
SCREAMING_SNAKE_CASE_ = optimizer.state_dict()
SCREAMING_SNAKE_CASE_ = train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item()
SCREAMING_SNAKE_CASE_ = optimizer.state_dict()
# Train partially
set_seed(42 )
SCREAMING_SNAKE_CASE_ = DummyModel()
SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 )
SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders()
SCREAMING_SNAKE_CASE_ = ProjectConfiguration(iteration=1 , automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) )
((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item()
SCREAMING_SNAKE_CASE_ = optimizer.state_dict()
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = train(2 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Save everything
accelerator.save_state()
# Load everything back in and make sure all states work
accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_1''' ) )
test_rands += train(1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item()
SCREAMING_SNAKE_CASE_ = optimizer.state_dict()
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
def _lowercase (self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = torch.tensor([1, 2, 3] )
SCREAMING_SNAKE_CASE_ = torch.tensor([2, 3, 4] )
SCREAMING_SNAKE_CASE_ = DummyModel()
SCREAMING_SNAKE_CASE_ = torch.optim.Adam(net.parameters() )
SCREAMING_SNAKE_CASE_ = Accelerator()
with self.assertRaises(SCREAMING_SNAKE_CASE_ ) as ve:
accelerator.register_for_checkpointing(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = str(ve.exception )
self.assertTrue('''Item at index 0''' in message )
self.assertTrue('''Item at index 1''' in message )
self.assertFalse('''Item at index 2''' in message )
self.assertFalse('''Item at index 3''' in message )
def _lowercase (self ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmpdir:
set_seed(42 )
SCREAMING_SNAKE_CASE_ = DummyModel()
SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 )
SCREAMING_SNAKE_CASE_ = torch.optim.lr_scheduler.StepLR(SCREAMING_SNAKE_CASE_ , step_size=1 , gamma=0.99 )
SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders()
SCREAMING_SNAKE_CASE_ = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ )
# Train baseline
SCREAMING_SNAKE_CASE_ = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Save initial
accelerator.save_state()
SCREAMING_SNAKE_CASE_ = scheduler.state_dict()
train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertNotEqual(SCREAMING_SNAKE_CASE_ , scheduler.state_dict() )
# Load everything back in and make sure all states work
accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) )
self.assertEqual(SCREAMING_SNAKE_CASE_ , scheduler.state_dict() )
def _lowercase (self ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmpdir:
set_seed(42 )
SCREAMING_SNAKE_CASE_ = DummyModel()
SCREAMING_SNAKE_CASE_ = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ , total_limit=2 )
# Train baseline
SCREAMING_SNAKE_CASE_ = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE_ = accelerator.prepare(SCREAMING_SNAKE_CASE_ )
# Save 3 states:
for _ in range(11 ):
accelerator.save_state()
self.assertTrue(not os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) ) )
self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_9''' ) ) )
self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_10''' ) ) )
@require_cuda
def _lowercase (self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = ['''torchrun''', f'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__ )]
execute_subprocess_async(SCREAMING_SNAKE_CASE_ , env=os.environ.copy() )
if __name__ == "__main__":
lowerCAmelCase__ = '/tmp/accelerate/state_checkpointing'
lowerCAmelCase__ = DummyModel()
lowerCAmelCase__ = torch.optim.Adam(params=model.parameters(), lr=1e-3)
lowerCAmelCase__ = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
lowerCAmelCase__, lowerCAmelCase__ = dummy_dataloaders()
lowerCAmelCase__ = ProjectConfiguration(automatic_checkpoint_naming=True)
# Train baseline
lowerCAmelCase__ = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision='no')
if accelerator.process_index == 0:
if os.path.exists(savedir):
shutil.rmtree(savedir)
os.makedirs(savedir)
lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__ = accelerator.prepare(
model, optimizer, train_dataloader, valid_dataloader, scheduler
)
lowerCAmelCase__, lowerCAmelCase__ = accelerator.prepare(model, optimizer)
train(3, model, train_dataloader, optimizer, accelerator, scheduler)
# Check that the intial optimizer is loaded on the GPU
for group in optimizer.param_groups:
lowerCAmelCase__ = group['params'][0].device
break
assert param_device.type == accelerator.device.type
lowerCAmelCase__ = model.cpu()
accelerator.wait_for_everyone()
accelerator.save_state()
accelerator.wait_for_everyone()
# Check CPU state
accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='cpu')
for group in optimizer.param_groups:
lowerCAmelCase__ = group['params'][0].device
break
assert (
param_device.type == torch.device('cpu').type
), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}"
# Check device state
model.to(accelerator.device)
accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='on_device')
for group in optimizer.param_groups:
lowerCAmelCase__ = group['params'][0].device
break
assert (
param_device.type == accelerator.device.type
), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}"
# Check error
with pytest.raises(TypeError, match='Unsupported optimizer map location passed'):
accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='invalid')
accelerator.wait_for_everyone()
if accelerator.process_index == 0:
shutil.rmtree(savedir)
accelerator.wait_for_everyone() | 628 | 1 |
"""simple docstring"""
_lowercase = {'''a''': ['''c''', '''b'''], '''b''': ['''d''', '''e'''], '''c''': [], '''d''': [], '''e''': []}
_lowercase = ['''a''', '''b''', '''c''', '''d''', '''e''']
def _snake_case ( snake_case__ : Dict , snake_case__ : str , snake_case__ : Optional[Any] ):
A = start
# add current to visited
visited.append(snake_case__ )
A = edges[current]
for neighbor in neighbors:
# if neighbor not in visited, visit
if neighbor not in visited:
A = topological_sort(snake_case__ , snake_case__ , snake_case__ )
# if all neighbors visited add current to sort
sort.append(snake_case__ )
# if all vertices haven't been visited select a new one to visit
if len(snake_case__ ) != len(snake_case__ ):
for vertice in vertices:
if vertice not in visited:
A = topological_sort(snake_case__ , snake_case__ , snake_case__ )
# return sort
return sort
if __name__ == "__main__":
_lowercase = topological_sort('''a''', [], [])
print(sort) | 91 |
"""simple docstring"""
import inspect
import os
import unittest
from pathlib import Path
import torch
import accelerate
from accelerate.test_utils import execute_subprocess_async
from accelerate.test_utils.testing import run_command
class _lowercase ( unittest.TestCase ):
_lowerCamelCase = inspect.getfile(accelerate.test_utils )
_lowerCamelCase = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] )
_lowerCamelCase = ['''accelerate''', '''launch''']
_lowerCamelCase = Path.home() / '''.cache/huggingface/accelerate'''
_lowerCamelCase = '''default_config.yaml'''
_lowerCamelCase = config_folder / config_file
_lowerCamelCase = config_folder / '''_default_config.yaml'''
_lowerCamelCase = Path('''tests/test_configs''' )
@classmethod
def lowerCAmelCase__ ( cls ):
if cls.config_path.is_file():
cls.config_path.rename(cls.changed_path )
@classmethod
def lowerCAmelCase__ ( cls ):
if cls.changed_path.is_file():
cls.changed_path.rename(cls.config_path )
def lowerCAmelCase__ ( self ):
__magic_name__ = self.base_cmd
if torch.cuda.is_available() and (torch.cuda.device_count() > 1):
cmd += ["--multi_gpu"]
execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy() )
def lowerCAmelCase__ ( self ):
for config in sorted(self.test_config_path.glob('''**/*.yaml''' ) ):
with self.subTest(config_file=UpperCamelCase_ ):
execute_subprocess_async(
self.base_cmd + ['''--config_file''', str(UpperCamelCase_ ), self.test_file_path] , env=os.environ.copy() )
def lowerCAmelCase__ ( self ):
execute_subprocess_async(['''accelerate''', '''test'''] , env=os.environ.copy() )
class _lowercase ( unittest.TestCase ):
_lowerCamelCase = '''test-tpu'''
_lowerCamelCase = '''us-central1-a'''
_lowerCamelCase = '''ls'''
_lowerCamelCase = ['''accelerate''', '''tpu-config''']
_lowerCamelCase = '''cd /usr/share'''
_lowerCamelCase = '''tests/test_samples/test_command_file.sh'''
_lowerCamelCase = '''Running gcloud compute tpus tpu-vm ssh'''
def lowerCAmelCase__ ( self ):
__magic_name__ = run_command(
self.cmd
+ ['''--command''', self.command, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug'''] , return_stdout=UpperCamelCase_ , )
self.assertIn(
f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , UpperCamelCase_ , )
def lowerCAmelCase__ ( self ):
__magic_name__ = run_command(
self.cmd
+ [
'''--config_file''',
'''tests/test_configs/0_12_0.yaml''',
'''--command''',
self.command,
'''--tpu_zone''',
self.tpu_zone,
'''--tpu_name''',
self.tpu_name,
'''--debug''',
] , return_stdout=UpperCamelCase_ , )
self.assertIn(
f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , UpperCamelCase_ , )
def lowerCAmelCase__ ( self ):
__magic_name__ = run_command(
self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--debug'''] , return_stdout=UpperCamelCase_ )
self.assertIn(
f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , UpperCamelCase_ , )
def lowerCAmelCase__ ( self ):
__magic_name__ = run_command(
self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command''', self.command, '''--debug'''] , return_stdout=UpperCamelCase_ , )
self.assertIn(
f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , UpperCamelCase_ , )
def lowerCAmelCase__ ( self ):
__magic_name__ = run_command(
self.cmd
+ [
'''--config_file''',
'''tests/test_configs/latest.yaml''',
'''--command''',
self.command,
'''--command''',
'''echo "Hello World"''',
'''--debug''',
] , return_stdout=UpperCamelCase_ , )
self.assertIn(
f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo "Hello World" --worker all''' , UpperCamelCase_ , )
def lowerCAmelCase__ ( self ):
__magic_name__ = run_command(
self.cmd
+ ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command_file''', self.command_file, '''--debug'''] , return_stdout=UpperCamelCase_ , )
self.assertIn(
f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , UpperCamelCase_ , )
def lowerCAmelCase__ ( self ):
__magic_name__ = run_command(
self.cmd
+ [
'''--config_file''',
'''tests/test_configs/0_12_0.yaml''',
'''--command_file''',
self.command_file,
'''--tpu_zone''',
self.tpu_zone,
'''--tpu_name''',
self.tpu_name,
'''--debug''',
] , return_stdout=UpperCamelCase_ , )
self.assertIn(
f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , UpperCamelCase_ , )
def lowerCAmelCase__ ( self ):
__magic_name__ = run_command(
self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--install_accelerate''', '''--debug'''] , return_stdout=UpperCamelCase_ , )
self.assertIn(
f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo "hello world"; echo "this is a second command" --worker all''' , UpperCamelCase_ , )
def lowerCAmelCase__ ( self ):
__magic_name__ = run_command(
self.cmd
+ [
'''--config_file''',
'''tests/test_configs/latest.yaml''',
'''--install_accelerate''',
'''--accelerate_version''',
'''12.0.0''',
'''--debug''',
] , return_stdout=UpperCamelCase_ , )
self.assertIn(
f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo "hello world"; echo "this is a second command" --worker all''' , UpperCamelCase_ , )
| 490 | 0 |
import argparse
import re
from flax.traverse_util import flatten_dict, unflatten_dict
from tax import checkpoints
from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration
from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model
from transformers.utils import logging
logging.set_verbosity_info()
# should not include what is already done by the `from_pt` argument
lowerCamelCase : List[str] = {
'/attention/': '/0/SelfAttention/',
'/self_attention/': '/0/SelfAttention/',
'/encoder_decoder_attention/': '/1/EncDecAttention/',
'value': 'v',
'query': 'q',
'key': 'k',
'out': 'o',
'pre_self_attention_layer_norm': '0/layer_norm',
'pre_cross_attention_layer_norm': '1/layer_norm',
'pre_attention_layer_norm': '0/layer_norm', # previously 1, but seems wrong
'token_embedder': 'shared',
'encoder_norm': 'final_layer_norm',
'decoder_norm': 'final_layer_norm',
'relpos_bias/rel_embedding': 'block/0/layer/0/SelfAttention/relative_attention_bias/weight',
'router/router_weights/w/': 'router/classifier/',
'roer/roer_weights/w/': 'router/classifier/',
'logits_dense': 'lm_head',
}
def SCREAMING_SNAKE_CASE__ ( lowercase ) -> Any:
# 1. in HF T5, we have block.{x}.layer.{y}. which corresponds to layer.{x} in
# the original model
snake_case : List[Any] = list(s_dict.keys() )
for key in keys:
snake_case : int = R""".*/layers_(\d+)"""
snake_case : Optional[int] = key
if re.match(lowercase ,lowercase ):
snake_case : Optional[Any] = re.sub(R"""layers_(\d+)""" ,R"""block/\1/layer""" ,lowercase )
snake_case : int = R"""(encoder|decoder)\/"""
if re.match(lowercase ,lowercase ):
snake_case : Tuple = re.match(lowercase ,lowercase ).groups()
if groups[0] == "encoder":
snake_case : List[str] = re.sub(R"""/mlp/""" ,R"""/1/mlp/""" ,lowercase )
snake_case : Optional[int] = re.sub(R"""/pre_mlp_layer_norm/""" ,R"""/1/layer_norm/""" ,lowercase )
elif groups[0] == "decoder":
snake_case : List[str] = re.sub(R"""/mlp/""" ,R"""/2/mlp/""" ,lowercase )
snake_case : List[Any] = re.sub(R"""/pre_mlp_layer_norm/""" ,R"""/2/layer_norm/""" ,lowercase )
# 2. Convert other classic mappings
for old_key, temp_key in MOE_LAYER_NAME_MAPPING.items():
if old_key in new_key:
snake_case : Optional[int] = new_key.replace(lowercase ,lowercase )
print(f"""{key} -> {new_key}""" )
snake_case : str = s_dict.pop(lowercase )
if "encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict:
snake_case : List[str] = s_dict[
"""encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight"""
].T
if "decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict:
snake_case : Any = s_dict[
"""decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight"""
].T
# 3. Take extra care of the EXPERTS layer
for key in list(s_dict.keys() ):
if "expert" in key:
snake_case : Tuple = s_dict[key].shape[0]
snake_case : str = s_dict[key]
for idx in range(lowercase ):
snake_case : List[str] = expert_weihts[idx]
print(f"""{key} -> {key.replace("expert/" ,"nested fstring" )}""" )
s_dict.pop(lowercase )
return s_dict
lowerCamelCase : str = {
'NUM_ENCODER_LAYERS': 'num_layers',
'NUM_DECODER_LAYERS': 'num_decoder_layers',
'NUM_HEADS': 'num_heads',
'HEAD_DIM': 'd_kv',
'EMBED_DIM': 'd_model',
'MLP_DIM': 'd_ff',
'NUM_SELECTED_EXPERTS': 'num_selected_experts',
'NUM_ENCODER_SPARSE_LAYERS': 'num_sparse_encoder_layers',
'NUM_DECODER_SPARSE_LAYERS': 'num_sparse_decoder_layers',
'dense.MlpBlock.activations': 'feed_forward_proj',
}
def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ) -> Optional[int]:
# Convert a google style config to the hugging face fromat
import regex as re
with open(lowercase ,"""r""" ) as f:
snake_case : List[str] = f.read()
snake_case : List[Any] = re.findall(R"""(.*) = ([0-9.]*)""" ,lowercase )
snake_case : Optional[int] = {}
for param, value in regex_match:
if param in GIN_TO_CONFIG_MAPPING and value != "":
snake_case : int = float(lowercase ) if """.""" in value else int(lowercase )
snake_case : Tuple = re.findall(R"""(.*activations) = \(\'(.*)\',\)""" ,lowercase )[0]
snake_case : int = str(activation[1] )
snake_case : int = num_experts
snake_case : Union[str, Any] = SwitchTransformersConfig(**lowercase )
return config
def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ,lowercase=None ,lowercase="./" ,lowercase=8 ) -> List[str]:
# Initialise PyTorch model
print(f"""Loading flax weights from : {flax_checkpoint_path}""" )
snake_case : Tuple = checkpoints.load_tax_checkpoint(lowercase )
if gin_file is not None:
snake_case : Union[str, Any] = convert_gin_to_config(lowercase ,lowercase )
else:
snake_case : Dict = SwitchTransformersConfig.from_pretrained(lowercase )
snake_case : Tuple = SwitchTransformersForConditionalGeneration(lowercase )
snake_case : Optional[int] = flax_params["""target"""]
snake_case : Dict = flatten_dict(lowercase ,sep="""/""" )
snake_case : int = rename_keys(lowercase )
snake_case : Dict = unflatten_dict(lowercase ,sep="""/""" )
# Load the flax params in the PT model
load_flax_weights_in_pytorch_model(lowercase ,lowercase )
print(f"""Save PyTorch model to {pytorch_dump_path}""" )
pt_model.save_pretrained(lowercase )
if __name__ == "__main__":
lowerCamelCase : Union[str, Any] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--switch_t5x_checkpoint_path',
default=None,
type=str,
required=True,
help=(
'The config json file corresponding to the pre-trained SwitchTransformers model. \nThis specifies the'
' model architecture. If not provided, a `gin_file` has to be provided.'
),
)
parser.add_argument(
'--gin_file',
default=None,
type=str,
required=False,
help='Path to the gin config file. If not provided, a `config_file` has to be passed ',
)
parser.add_argument(
'--config_name', default=None, type=str, required=False, help='Config name of SwitchTransformers model.'
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output pytorch model.'
)
parser.add_argument('--num_experts', default=8, type=int, required=False, help='Number of experts')
lowerCamelCase : str = parser.parse_args()
convert_flax_checkpoint_to_pytorch(
args.switch_tax_checkpoint_path,
args.config_name,
args.gin_file,
args.pytorch_dump_folder_path,
args.num_experts,
)
| 684 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowerCamelCase : Any = logging.get_logger(__name__)
lowerCamelCase : Optional[int] = {
'abeja/gpt-neox-japanese-2.7b': 'https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json',
}
class __lowercase (UpperCamelCase__ ):
"""simple docstring"""
_snake_case = """gpt_neox_japanese"""
def __init__( self , A=3_2_0_0_0 , A=2_5_6_0 , A=3_2 , A=3_2 , A=4 , A="gelu" , A=1.00 , A=1_0_0_0_0 , A=2_0_4_8 , A=0.02 , A=1e-5 , A=True , A=3_1_9_9_6 , A=3_1_9_9_9 , A=0.1 , A=0.0 , **A , ) -> str:
super().__init__(bos_token_id=A , eos_token_id=A , **A )
snake_case : Optional[Any] = vocab_size
snake_case : Optional[Any] = max_position_embeddings
snake_case : Union[str, Any] = hidden_size
snake_case : Union[str, Any] = num_hidden_layers
snake_case : Optional[int] = num_attention_heads
snake_case : Optional[int] = intermediate_multiple_size
snake_case : int = hidden_act
snake_case : str = rotary_pct
snake_case : Optional[Any] = rotary_emb_base
snake_case : Any = initializer_range
snake_case : Any = layer_norm_eps
snake_case : Optional[Any] = use_cache
snake_case : Tuple = attention_dropout
snake_case : Tuple = hidden_dropout
| 684 | 1 |
import copy
import os
from typing import Union
from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING
UpperCAmelCase__ = logging.get_logger(__name__)
UpperCAmelCase__ = {
"salesforce/blip2-opt-2.7b": "https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json",
}
class lowercase_ ( lowercase ):
'''simple docstring'''
__snake_case = '''blip_2_vision_model'''
def __init__( self : Union[str, Any] , __UpperCAmelCase : Optional[Any]=1_408 , __UpperCAmelCase : Optional[Any]=6_144 , __UpperCAmelCase : int=39 , __UpperCAmelCase : List[str]=16 , __UpperCAmelCase : Optional[int]=224 , __UpperCAmelCase : Union[str, Any]=14 , __UpperCAmelCase : Optional[int]="gelu" , __UpperCAmelCase : Optional[int]=0.00001 , __UpperCAmelCase : List[str]=0.0 , __UpperCAmelCase : str=1e-1_0 , __UpperCAmelCase : List[str]=True , **__UpperCAmelCase : List[str] , ) ->Tuple:
"""simple docstring"""
super().__init__(**__UpperCAmelCase )
a = hidden_size
a = intermediate_size
a = num_hidden_layers
a = num_attention_heads
a = patch_size
a = image_size
a = initializer_range
a = attention_dropout
a = layer_norm_eps
a = hidden_act
a = qkv_bias
@classmethod
def __lowerCAmelCase ( cls : Union[str, Any] , __UpperCAmelCase : Union[str, os.PathLike] , **__UpperCAmelCase : Tuple ) ->"PretrainedConfig":
"""simple docstring"""
cls._set_token_in_kwargs(__UpperCAmelCase )
a , a = cls.get_config_dict(__UpperCAmelCase , **__UpperCAmelCase )
# get the vision config dict if we are loading from Blip2Config
if config_dict.get('''model_type''' ) == "blip-2":
a = 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(__UpperCAmelCase , **__UpperCAmelCase )
class lowercase_ ( lowercase ):
'''simple docstring'''
__snake_case = '''blip_2_qformer'''
def __init__( self : Any , __UpperCAmelCase : Dict=30_522 , __UpperCAmelCase : Union[str, Any]=768 , __UpperCAmelCase : Any=12 , __UpperCAmelCase : Dict=12 , __UpperCAmelCase : Union[str, Any]=3_072 , __UpperCAmelCase : Optional[int]="gelu" , __UpperCAmelCase : Optional[int]=0.1 , __UpperCAmelCase : str=0.1 , __UpperCAmelCase : Optional[Any]=512 , __UpperCAmelCase : str=0.02 , __UpperCAmelCase : Tuple=1e-1_2 , __UpperCAmelCase : List[str]=0 , __UpperCAmelCase : List[str]="absolute" , __UpperCAmelCase : Optional[int]=2 , __UpperCAmelCase : List[Any]=1_408 , **__UpperCAmelCase : Dict , ) ->str:
"""simple docstring"""
super().__init__(pad_token_id=__UpperCAmelCase , **__UpperCAmelCase )
a = vocab_size
a = hidden_size
a = num_hidden_layers
a = num_attention_heads
a = hidden_act
a = intermediate_size
a = hidden_dropout_prob
a = attention_probs_dropout_prob
a = max_position_embeddings
a = initializer_range
a = layer_norm_eps
a = position_embedding_type
a = cross_attention_frequency
a = encoder_hidden_size
@classmethod
def __lowerCAmelCase ( cls : Any , __UpperCAmelCase : Union[str, os.PathLike] , **__UpperCAmelCase : Optional[Any] ) ->"PretrainedConfig":
"""simple docstring"""
cls._set_token_in_kwargs(__UpperCAmelCase )
a , a = cls.get_config_dict(__UpperCAmelCase , **__UpperCAmelCase )
# get the qformer config dict if we are loading from Blip2Config
if config_dict.get('''model_type''' ) == "blip-2":
a = config_dict['''qformer_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(__UpperCAmelCase , **__UpperCAmelCase )
class lowercase_ ( lowercase ):
'''simple docstring'''
__snake_case = '''blip-2'''
__snake_case = True
def __init__( self : Dict , __UpperCAmelCase : Optional[Any]=None , __UpperCAmelCase : List[str]=None , __UpperCAmelCase : str=None , __UpperCAmelCase : Union[str, Any]=32 , **__UpperCAmelCase : List[Any] ) ->List[Any]:
"""simple docstring"""
super().__init__(**__UpperCAmelCase )
if vision_config is None:
a = {}
logger.info('''vision_config is None. initializing the Blip2VisionConfig with default values.''' )
if qformer_config is None:
a = {}
logger.info('''qformer_config is None. Initializing the Blip2QFormerConfig with default values.''' )
if text_config is None:
a = {}
logger.info('''text_config is None. Initializing the text config with default values (`OPTConfig`).''' )
a = BlipaVisionConfig(**__UpperCAmelCase )
a = BlipaQFormerConfig(**__UpperCAmelCase )
a = text_config['''model_type'''] if '''model_type''' in text_config else '''opt'''
a = CONFIG_MAPPING[text_model_type](**__UpperCAmelCase )
a = self.text_config.tie_word_embeddings
a = self.text_config.is_encoder_decoder
a = num_query_tokens
a = self.vision_config.hidden_size
a = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
a = 1.0
a = 0.02
@classmethod
def __lowerCAmelCase ( cls : Optional[Any] , __UpperCAmelCase : BlipaVisionConfig , __UpperCAmelCase : BlipaQFormerConfig , __UpperCAmelCase : PretrainedConfig , **__UpperCAmelCase : Optional[Any] , ) ->Any:
"""simple docstring"""
return cls(
vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **__UpperCAmelCase , )
def __lowerCAmelCase ( self : Any ) ->Dict:
"""simple docstring"""
a = copy.deepcopy(self.__dict__ )
a = self.vision_config.to_dict()
a = self.qformer_config.to_dict()
a = self.text_config.to_dict()
a = self.__class__.model_type
return output
| 117 |
def _a ( a :list ) -> list:
if len(a ) < 2:
return collection
def circle_sort_util(a :list , a :int , a :int ) -> bool:
a = False
if low == high:
return swapped
a = low
a = high
while left < right:
if collection[left] > collection[right]:
a , a = (
collection[right],
collection[left],
)
a = True
left += 1
right -= 1
if left == right and collection[left] > collection[right + 1]:
a , a = (
collection[right + 1],
collection[left],
)
a = True
a = low + int((high - low) / 2 )
a = circle_sort_util(a , a , a )
a = circle_sort_util(a , mid + 1 , a )
return swapped or left_swap or right_swap
a = True
while is_not_sorted is True:
a = circle_sort_util(a , 0 , len(a ) - 1 )
return collection
if __name__ == "__main__":
UpperCAmelCase__ = input("Enter numbers separated by a comma:\n").strip()
UpperCAmelCase__ = [int(item) for item in user_input.split(",")]
print(circle_sort(unsorted))
| 117 | 1 |
'''simple docstring'''
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 _lowerCAmelCase ( A__ ):
"""simple docstring"""
snake_case_ = ["image_processor", "tokenizer"]
snake_case_ = "LayoutLMv3ImageProcessor"
snake_case_ = ("LayoutLMv3Tokenizer", "LayoutLMv3TokenizerFast")
def __init__( self : Optional[int] , __snake_case : Optional[Any]=None , __snake_case : Optional[int]=None , **__snake_case : Optional[int] )-> Optional[Any]:
snake_case = 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 , )
snake_case = kwargs.pop("""feature_extractor""" )
snake_case = 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 : str , __snake_case : Dict , __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:
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
snake_case = 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 ):
snake_case = [text] # add batch dimension (as the image processor always adds a batch dimension)
snake_case = features["""words"""]
snake_case = 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
snake_case = features.pop("""pixel_values""" )
if return_overflowing_tokens is True:
snake_case = self.get_overflowing_images(__snake_case , encoded_inputs["""overflow_to_sample_mapping"""] )
snake_case = images
return encoded_inputs
def lowerCAmelCase ( self : str , __snake_case : Union[str, Any] , __snake_case : Optional[int] )-> str:
snake_case = []
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 lowerCAmelCase ( self : List[str] , *__snake_case : Optional[int] , **__snake_case : List[Any] )-> List[Any]:
return self.tokenizer.batch_decode(*__snake_case , **__snake_case )
def lowerCAmelCase ( self : List[Any] , *__snake_case : Optional[int] , **__snake_case : Tuple )-> Dict:
return self.tokenizer.decode(*__snake_case , **__snake_case )
@property
def lowerCAmelCase ( self : List[Any] )-> Dict:
return ["input_ids", "bbox", "attention_mask", "pixel_values"]
@property
def lowerCAmelCase ( self : int )-> Tuple:
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 lowerCAmelCase ( self : Union[str, Any] )-> Optional[int]:
warnings.warn(
"""`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , __snake_case , )
return self.image_processor
| 706 |
'''simple docstring'''
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 _lowerCAmelCase ( A__ ):
"""simple docstring"""
snake_case_ = ["image_processor", "tokenizer"]
snake_case_ = "LayoutLMv3ImageProcessor"
snake_case_ = ("LayoutLMv3Tokenizer", "LayoutLMv3TokenizerFast")
def __init__( self : str , __snake_case : int=None , __snake_case : List[Any]=None , **__snake_case : Optional[Any] )-> List[Any]:
snake_case = 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 , )
snake_case = kwargs.pop("""feature_extractor""" )
snake_case = 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 : Any , __snake_case : int , __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 : List[Any] , )-> BatchEncoding:
# verify input
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
snake_case = 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 ):
snake_case = [text] # add batch dimension (as the image processor always adds a batch dimension)
snake_case = features["""words"""]
snake_case = 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
snake_case = features.pop("""pixel_values""" )
if return_overflowing_tokens is True:
snake_case = self.get_overflowing_images(__snake_case , encoded_inputs["""overflow_to_sample_mapping"""] )
snake_case = images
return encoded_inputs
def lowerCAmelCase ( self : Any , __snake_case : int , __snake_case : Tuple )-> List[Any]:
# in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
snake_case = []
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 lowerCAmelCase ( self : Optional[int] , *__snake_case : Optional[int] , **__snake_case : Optional[Any] )-> Tuple:
return self.tokenizer.batch_decode(*__snake_case , **__snake_case )
def lowerCAmelCase ( self : str , *__snake_case : Any , **__snake_case : Optional[Any] )-> List[str]:
return self.tokenizer.decode(*__snake_case , **__snake_case )
@property
def lowerCAmelCase ( self : Union[str, Any] )-> Tuple:
return ["input_ids", "bbox", "attention_mask", "pixel_values"]
@property
def lowerCAmelCase ( self : Any )-> Any:
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 lowerCAmelCase ( self : int )-> Optional[Any]:
warnings.warn(
"""`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , __snake_case , )
return self.image_processor
| 517 | 0 |
"""simple docstring"""
import copy
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto.configuration_auto import CONFIG_MAPPING
_A = logging.get_logger(__name__)
class lowerCamelCase ( lowerCAmelCase__ ):
'''simple docstring'''
SCREAMING_SNAKE_CASE = 'upernet'
def __init__(self , _lowerCamelCase=None , _lowerCamelCase=512 , _lowerCamelCase=0.02 , _lowerCamelCase=[1, 2, 3, 6] , _lowerCamelCase=True , _lowerCamelCase=0.4 , _lowerCamelCase=384 , _lowerCamelCase=256 , _lowerCamelCase=1 , _lowerCamelCase=False , _lowerCamelCase=255 , **_lowerCamelCase , ):
"""simple docstring"""
super().__init__(**_lowerCamelCase )
if backbone_config is None:
logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" )
UpperCAmelCase__ : Tuple = CONFIG_MAPPING["""resnet"""](out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] )
elif isinstance(_lowerCamelCase , _lowerCamelCase ):
UpperCAmelCase__ : Any = backbone_config.get("""model_type""" )
UpperCAmelCase__ : Union[str, Any] = CONFIG_MAPPING[backbone_model_type]
UpperCAmelCase__ : List[Any] = config_class.from_dict(_lowerCamelCase )
UpperCAmelCase__ : Union[str, Any] = backbone_config
UpperCAmelCase__ : List[Any] = hidden_size
UpperCAmelCase__ : Optional[Any] = initializer_range
UpperCAmelCase__ : List[str] = pool_scales
UpperCAmelCase__ : List[Any] = use_auxiliary_head
UpperCAmelCase__ : Tuple = auxiliary_loss_weight
UpperCAmelCase__ : Dict = auxiliary_in_channels
UpperCAmelCase__ : Union[str, Any] = auxiliary_channels
UpperCAmelCase__ : Optional[Any] = auxiliary_num_convs
UpperCAmelCase__ : List[Any] = auxiliary_concat_input
UpperCAmelCase__ : Any = loss_ignore_index
def _a (self ):
"""simple docstring"""
UpperCAmelCase__ : List[Any] = copy.deepcopy(self.__dict__ )
UpperCAmelCase__ : Optional[int] = self.backbone_config.to_dict()
UpperCAmelCase__ : Optional[int] = self.__class__.model_type
return output
| 182 |
'''simple docstring'''
import argparse
import logging
import os
from datetime import datetime
import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, RandomSampler, TensorDataset
from tqdm import tqdm
from transformers import GPTaLMHeadModel
lowercase_ = logging.getLogger(__name__)
def lowerCAmelCase (__A , __A):
"""simple docstring"""
if os.path.exists(__A):
if os.path.exists(os.path.join(__A , '''config.json''')) and os.path.isfile(
os.path.join(__A , '''config.json''')):
os.remove(os.path.join(__A , '''config.json'''))
if os.path.exists(os.path.join(__A , '''pytorch_model.bin''')) and os.path.isfile(
os.path.join(__A , '''pytorch_model.bin''')):
os.remove(os.path.join(__A , '''pytorch_model.bin'''))
else:
os.makedirs(__A)
model.save_pretrained(__A)
def lowerCAmelCase (__A , __A=False):
"""simple docstring"""
_a = 2
if unlogit:
_a = torch.pow(__A , __A)
_a = p * torch.log(__A)
_a = 0
return -plogp.sum(dim=-1)
def lowerCAmelCase (__A):
"""simple docstring"""
logger.info('''lv, h >\t''' + '''\t'''.join(F'''{x + 1}''' for x in range(len(__A))))
for row in range(len(__A)):
if tensor.dtype != torch.long:
logger.info(F'''layer {row + 1}:\t''' + '''\t'''.join(F'''{x:.5f}''' for x in tensor[row].cpu().data))
else:
logger.info(F'''layer {row + 1}:\t''' + '''\t'''.join(F'''{x:d}''' for x in tensor[row].cpu().data))
def lowerCAmelCase (__A , __A , __A , __A=True , __A=True , __A=None , __A=False):
"""simple docstring"""
_a , _a = model.config.num_hidden_layers, model.config.num_attention_heads
_a = torch.zeros(__A , __A).to(args.device)
_a = torch.zeros(__A , __A).to(args.device)
if head_mask is None:
_a = torch.ones(__A , __A).to(args.device)
head_mask.requires_grad_(requires_grad=__A)
# If actually pruned attention multi-head, set head mask to None to avoid shape mismatch
if actually_pruned:
_a = None
_a = 0.0
_a = 0.0
for step, inputs in enumerate(tqdm(__A , desc='''Iteration''' , disable=args.local_rank not in [-1, 0])):
_a = tuple(t.to(args.device) for t in inputs)
((_a) , ) = inputs
# Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
_a = model(__A , labels=__A , head_mask=__A)
# (loss), lm_logits, presents, (all hidden_states), (attentions)
_a , _a , _a = (
outputs[0],
outputs[1],
outputs[-1],
) # Loss and logits are the first, attention the last
loss.backward() # Backpropagate to populate the gradients in the head mask
total_loss += loss.detach().cpu().numpy()
if compute_entropy:
for layer, attn in enumerate(__A):
_a = entropy(attn.detach() , __A)
attn_entropy[layer] += masked_entropy.sum(-1).sum(0).sum(0).detach()
if compute_importance:
head_importance += head_mask.grad.abs().detach()
tot_tokens += torch.ones_like(__A).float().detach().sum().data
# Normalize
attn_entropy /= tot_tokens
head_importance /= tot_tokens
# Layerwise importance normalization
if not args.dont_normalize_importance_by_layer:
_a = 2
_a = torch.pow(torch.pow(__A , __A).sum(-1) , 1 / exponent)
head_importance /= norm_by_layer.unsqueeze(-1) + 1e-20
if not args.dont_normalize_global_importance:
_a = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())
# Print matrices
if compute_entropy:
logger.info('''Attention entropies''')
print_ad_tensor(__A)
if compute_importance:
logger.info('''Head importance scores''')
print_ad_tensor(__A)
logger.info('''Head ranked by importance scores''')
_a = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device)
_a = torch.arange(
head_importance.numel() , device=args.device)
_a = head_ranks.view_as(__A)
print_ad_tensor(__A)
return attn_entropy, head_importance, total_loss
def lowerCAmelCase (__A , __A , __A):
"""simple docstring"""
_a , _a , _a = compute_heads_importance(__A , __A , __A , compute_entropy=__A)
_a = 1 / loss # instead of downsteam score use the LM loss
logger.info('''Pruning: original score: %f, threshold: %f''' , __A , original_score * args.masking_threshold)
_a = torch.ones_like(__A)
_a = max(1 , int(new_head_mask.numel() * args.masking_amount))
_a = original_score
while current_score >= original_score * args.masking_threshold:
_a = new_head_mask.clone().detach() # save current head mask
# heads from least important to most - keep only not-masked heads
_a = float('''Inf''')
_a = head_importance.view(-1).sort()[1]
if len(__A) <= num_to_mask:
print('''BREAK BY num_to_mask''')
break
# mask heads
_a = current_heads_to_mask[:num_to_mask]
logger.info('''Heads to mask: %s''' , str(current_heads_to_mask.tolist()))
_a = new_head_mask.view(-1)
_a = 0.0
_a = new_head_mask.view_as(__A)
_a = new_head_mask.clone().detach()
print_ad_tensor(__A)
# Compute metric and head importance again
_a , _a , _a = compute_heads_importance(
__A , __A , __A , compute_entropy=__A , head_mask=__A)
_a = 1 / loss
logger.info(
'''Masking: current score: %f, remaining heads %d (%.1f percents)''' , __A , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 100 , )
logger.info('''Final head mask''')
print_ad_tensor(__A)
np.save(os.path.join(args.output_dir , '''head_mask.npy''') , head_mask.detach().cpu().numpy())
return head_mask
def lowerCAmelCase (__A , __A , __A , __A):
"""simple docstring"""
_a = datetime.now()
_a , _a , _a = compute_heads_importance(
__A , __A , __A , compute_entropy=__A , compute_importance=__A , head_mask=__A)
_a = 1 / loss
_a = datetime.now() - before_time
_a = sum(p.numel() for p in model.parameters())
_a = {
layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(__A))
}
for k, v in heads_to_prune.items():
if isinstance(__A , __A):
_a = [
v,
]
assert sum(len(__A) for h in heads_to_prune.values()) == (1 - head_mask.long()).sum().item()
model.prune_heads(__A)
_a = sum(p.numel() for p in model.parameters())
_a = datetime.now()
_a , _a , _a = compute_heads_importance(
__A , __A , __A , compute_entropy=__A , compute_importance=__A , head_mask=__A , actually_pruned=__A , )
_a = 1 / loss
_a = datetime.now() - before_time
logger.info(
'''Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)''' , __A , __A , pruned_num_params / original_num_params * 100 , )
logger.info('''Pruning: score with masking: %f score with pruning: %f''' , __A , __A)
logger.info('''Pruning: speed ratio (original timing / new timing): %f percents''' , original_time / new_time * 100)
save_model(__A , args.output_dir)
def lowerCAmelCase ():
"""simple docstring"""
_a = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--data_dir''' , default=__A , type=__A , required=__A , help='''The input data dir. Should contain the .tsv files (or other data files) for the task.''' , )
parser.add_argument(
'''--model_name_or_path''' , default=__A , type=__A , required=__A , help='''Path to pretrained model or model identifier from huggingface.co/models''' , )
parser.add_argument(
'''--output_dir''' , default=__A , type=__A , required=__A , help='''The output directory where the model predictions and checkpoints will be written.''' , )
# Other parameters
parser.add_argument(
'''--config_name''' , default='''''' , type=__A , help='''Pretrained config name or path if not the same as model_name_or_path''' , )
parser.add_argument(
'''--tokenizer_name''' , default='''''' , type=__A , help='''Pretrained tokenizer name or path if not the same as model_name_or_path''' , )
parser.add_argument(
'''--cache_dir''' , default=__A , type=__A , help='''Where do you want to store the pre-trained models downloaded from s3''' , )
parser.add_argument(
'''--data_subset''' , type=__A , default=-1 , help='''If > 0: limit the data to a subset of data_subset instances.''')
parser.add_argument(
'''--overwrite_output_dir''' , action='''store_true''' , help='''Whether to overwrite data in output directory''')
parser.add_argument(
'''--overwrite_cache''' , action='''store_true''' , help='''Overwrite the cached training and evaluation sets''')
parser.add_argument(
'''--dont_normalize_importance_by_layer''' , action='''store_true''' , help='''Don\'t normalize importance score by layers''')
parser.add_argument(
'''--dont_normalize_global_importance''' , action='''store_true''' , help='''Don\'t normalize all importance scores between 0 and 1''' , )
parser.add_argument(
'''--try_masking''' , action='''store_true''' , help='''Whether to try to mask head until a threshold of accuracy.''')
parser.add_argument(
'''--masking_threshold''' , default=0.9 , type=__A , help='''masking threshold in term of metrics (stop masking when metric < threshold * original metric value).''' , )
parser.add_argument(
'''--masking_amount''' , default=0.1 , type=__A , help='''Amount to heads to masking at each masking step.''')
parser.add_argument('''--metric_name''' , default='''acc''' , type=__A , help='''Metric to use for head masking.''')
parser.add_argument(
'''--max_seq_length''' , default=128 , type=__A , help=(
'''The maximum total input sequence length after WordPiece tokenization. \n'''
'''Sequences longer than this will be truncated, sequences shorter padded.'''
) , )
parser.add_argument('''--batch_size''' , default=1 , type=__A , help='''Batch size.''')
parser.add_argument('''--seed''' , type=__A , default=42)
parser.add_argument('''--local_rank''' , type=__A , default=-1 , help='''local_rank for distributed training on gpus''')
parser.add_argument('''--no_cuda''' , action='''store_true''' , help='''Whether not to use CUDA when available''')
parser.add_argument('''--server_ip''' , type=__A , default='''''' , help='''Can be used for distant debugging.''')
parser.add_argument('''--server_port''' , type=__A , default='''''' , help='''Can be used for distant debugging.''')
_a = parser.parse_args()
if args.server_ip and args.server_port:
# Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
import ptvsd
print('''Waiting for debugger attach''')
ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=__A)
ptvsd.wait_for_attach()
# Setup devices and distributed training
if args.local_rank == -1 or args.no_cuda:
_a = torch.device('''cuda''' if torch.cuda.is_available() and not args.no_cuda else '''cpu''')
_a = 0 if args.no_cuda else torch.cuda.device_count()
else:
torch.cuda.set_device(args.local_rank)
_a = torch.device('''cuda''' , args.local_rank)
_a = 1
torch.distributed.init_process_group(backend='''nccl''') # Initializes the distributed backend
# Setup logging
logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN)
logger.info('''device: {} n_gpu: {}, distributed: {}'''.format(args.device , args.n_gpu , bool(args.local_rank != -1)))
_a = GPTaLMHeadModel.from_pretrained(args.model_name_or_path)
# Distributed and parallel training
model.to(args.device)
if args.local_rank != -1:
_a = nn.parallel.DistributedDataParallel(
__A , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=__A)
elif args.n_gpu > 1:
_a = nn.DataParallel(__A)
# Print/save training arguments
os.makedirs(args.output_dir , exist_ok=__A)
torch.save(__A , os.path.join(args.output_dir , '''run_args.bin'''))
logger.info('''Training/evaluation parameters %s''' , __A)
# Prepare dataset
_a = np.concatenate(
[
np.loadtxt(args.data_dir , dtype=np.intaa),
])
_a = (torch.from_numpy(__A),)
_a = TensorDataset(*__A)
_a = RandomSampler(__A)
_a = DataLoader(__A , sampler=__A , batch_size=args.batch_size)
# Compute head entropy and importance score
compute_heads_importance(__A , __A , __A)
# Try head masking (set heads to zero until the score goes under a threshole)
# and head pruning (remove masked heads and see the effect on the network)
if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0:
_a = mask_heads(__A , __A , __A)
prune_heads(__A , __A , __A , __A)
if __name__ == "__main__":
main()
| 11 | 0 |
import argparse
import json
import os
import fairseq
import torch
from fairseq.data import Dictionary
from transformers import (
WavaVecaConfig,
WavaVecaCTCTokenizer,
WavaVecaFeatureExtractor,
WavaVecaForCTC,
WavaVecaForPreTraining,
WavaVecaProcessor,
logging,
)
from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification
logging.set_verbosity_info()
UpperCAmelCase__ : Optional[int] = logging.get_logger(__name__)
UpperCAmelCase__ : List[Any] = {
"post_extract_proj": "feature_projection.projection",
"encoder.pos_conv.0": "encoder.pos_conv_embed.conv",
"self_attn.k_proj": "encoder.layers.*.attention.k_proj",
"self_attn.v_proj": "encoder.layers.*.attention.v_proj",
"self_attn.q_proj": "encoder.layers.*.attention.q_proj",
"self_attn.out_proj": "encoder.layers.*.attention.out_proj",
"self_attn_layer_norm": "encoder.layers.*.layer_norm",
"fc1": "encoder.layers.*.feed_forward.intermediate_dense",
"fc2": "encoder.layers.*.feed_forward.output_dense",
"final_layer_norm": "encoder.layers.*.final_layer_norm",
"encoder.layer_norm": "encoder.layer_norm",
"adapter_layer": "encoder.layers.*.adapter_layer",
"w2v_model.layer_norm": "feature_projection.layer_norm",
"quantizer.weight_proj": "quantizer.weight_proj",
"quantizer.vars": "quantizer.codevectors",
"project_q": "project_q",
"final_proj": "project_hid",
"w2v_encoder.proj": "lm_head",
"mask_emb": "masked_spec_embed",
"pooling_layer.linear": "projector",
"pooling_layer.projection": "classifier",
}
UpperCAmelCase__ : List[Any] = [
"lm_head",
"quantizer.weight_proj",
"quantizer.codevectors",
"project_q",
"project_hid",
"projector",
"classifier",
]
def A ( snake_case__ : int ) -> int:
'''simple docstring'''
__snake_case = {}
with open(snake_case__ , 'r' ) as file:
for line_number, line in enumerate(snake_case__ ):
__snake_case = line.strip()
if line:
__snake_case = line.split()
__snake_case = line_number
__snake_case = words[0]
__snake_case = value
return result
def A ( snake_case__ : List[str] , snake_case__ : int , snake_case__ : Tuple , snake_case__ : Tuple , snake_case__ : Tuple ) -> Optional[int]:
'''simple docstring'''
for attribute in key.split('.' ):
__snake_case = getattr(snake_case__ , snake_case__ )
__snake_case = None
for param_key in PARAM_MAPPING.keys():
if full_name.endswith(snake_case__ ):
__snake_case = PARAM_MAPPING[full_name.split('.' )[-1]]
__snake_case = 'param'
if weight_type is not None and weight_type != "param":
__snake_case = getattr(snake_case__ , snake_case__ ).shape
elif weight_type is not None and weight_type == "param":
__snake_case = hf_pointer
for attribute in hf_param_name.split('.' ):
__snake_case = getattr(snake_case__ , snake_case__ )
__snake_case = shape_pointer.shape
# let's reduce dimension
__snake_case = value[0]
else:
__snake_case = hf_pointer.shape
if hf_shape != value.shape:
raise ValueError(
f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be"
f" {value.shape} for {full_name}" )
if weight_type == "weight":
__snake_case = value
elif weight_type == "weight_g":
__snake_case = value
elif weight_type == "weight_v":
__snake_case = value
elif weight_type == "bias":
__snake_case = value
elif weight_type == "param":
for attribute in hf_param_name.split('.' ):
__snake_case = getattr(snake_case__ , snake_case__ )
__snake_case = value
else:
__snake_case = value
logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." )
def A ( snake_case__ : Optional[int] , snake_case__ : Tuple , snake_case__ : Union[str, Any] , snake_case__ : Optional[int] , snake_case__ : Tuple ) -> Optional[int]:
'''simple docstring'''
__snake_case = None
for param_key in PARAM_MAPPING.keys():
if full_name.endswith(snake_case__ ):
__snake_case = PARAM_MAPPING[full_name.split('.' )[-1]]
__snake_case = 'param'
if weight_type is not None and weight_type != "param":
__snake_case = '.'.join([key, weight_type] )
elif weight_type is not None and weight_type == "param":
__snake_case = '.'.join([key, hf_param_name] )
else:
__snake_case = key
__snake_case = value if 'lm_head' in full_key else value[0]
UpperCAmelCase__ : Tuple = {
"W_a": "linear_1.weight",
"W_b": "linear_2.weight",
"b_a": "linear_1.bias",
"b_b": "linear_2.bias",
"ln_W": "norm.weight",
"ln_b": "norm.bias",
}
def A ( snake_case__ : Any , snake_case__ : Tuple , snake_case__ : List[str]=None , snake_case__ : str=None ) -> str:
'''simple docstring'''
__snake_case = False
for key, mapped_key in MAPPING.items():
__snake_case = 'wav2vec2.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]:
__snake_case = True
if "*" in mapped_key:
__snake_case = name.split(snake_case__ )[0].split('.' )[-2]
__snake_case = mapped_key.replace('*' , snake_case__ )
if "weight_g" in name:
__snake_case = 'weight_g'
elif "weight_v" in name:
__snake_case = 'weight_v'
elif "bias" in name:
__snake_case = 'bias'
elif "weight" in name:
# TODO: don't match quantizer.weight_proj
__snake_case = 'weight'
else:
__snake_case = None
if hf_dict is not None:
rename_dict(snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ )
else:
set_recursively(snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ )
return is_used
return is_used
def A ( snake_case__ : Union[str, Any] , snake_case__ : str , snake_case__ : Optional[int] ) -> List[str]:
'''simple docstring'''
__snake_case = []
__snake_case = fairseq_model.state_dict()
__snake_case = hf_model.wavaveca.feature_extractor
for name, value in fairseq_dict.items():
__snake_case = False
if "conv_layers" in name:
load_conv_layer(
snake_case__ , snake_case__ , snake_case__ , snake_case__ , hf_model.config.feat_extract_norm == 'group' , )
__snake_case = True
else:
__snake_case = load_wavaveca_layer(snake_case__ , snake_case__ , snake_case__ )
if not is_used:
unused_weights.append(snake_case__ )
logger.warning(f"Unused weights: {unused_weights}" )
def A ( snake_case__ : Optional[int] , snake_case__ : Optional[Any] , snake_case__ : Any , snake_case__ : List[Any] , snake_case__ : Dict ) -> Any:
'''simple docstring'''
__snake_case = full_name.split('conv_layers.' )[-1]
__snake_case = name.split('.' )
__snake_case = int(items[0] )
__snake_case = int(items[1] )
if type_id == 0:
if "bias" in name:
if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
raise ValueError(
f"{full_name} has size {value.shape}, but"
f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." )
__snake_case = value
logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." )
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
raise ValueError(
f"{full_name} has size {value.shape}, but"
f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." )
__snake_case = value
logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." )
elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
if "bias" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
raise ValueError(
f"{full_name} has size {value.shape}, but"
f" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found." )
__snake_case = value
logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." )
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
raise ValueError(
f"{full_name} has size {value.shape}, but"
f" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found." )
__snake_case = value
logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." )
else:
unused_weights.append(snake_case__ )
@torch.no_grad()
def A ( snake_case__ : int , snake_case__ : List[str] , snake_case__ : int=None , snake_case__ : Optional[Any]=None , snake_case__ : List[str]=True , snake_case__ : Optional[int]=False ) -> Union[str, Any]:
'''simple docstring'''
if config_path is not None:
__snake_case = WavaVecaConfig.from_pretrained(snake_case__ )
else:
__snake_case = WavaVecaConfig()
if is_seq_class:
__snake_case = read_txt_into_dict(snake_case__ )
__snake_case = idalabel
__snake_case = WavaVecaForSequenceClassification(snake_case__ )
__snake_case = WavaVecaFeatureExtractor(
feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=snake_case__ , return_attention_mask=snake_case__ , )
feature_extractor.save_pretrained(snake_case__ )
elif is_finetuned:
if dict_path:
__snake_case = Dictionary.load(snake_case__ )
# important change bos & pad token id since CTC symbol is <pad> and
# not <s> as in fairseq
__snake_case = target_dict.pad_index
__snake_case = target_dict.bos_index
__snake_case = target_dict.eos_index
__snake_case = len(target_dict.symbols )
__snake_case = os.path.join(snake_case__ , 'vocab.json' )
if not os.path.isdir(snake_case__ ):
logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(snake_case__ ) )
return
os.makedirs(snake_case__ , exist_ok=snake_case__ )
__snake_case = target_dict.indices
# fairseq has the <pad> and <s> switched
__snake_case = 0
__snake_case = 1
with open(snake_case__ , 'w' , encoding='utf-8' ) as vocab_handle:
json.dump(snake_case__ , snake_case__ )
__snake_case = WavaVecaCTCTokenizer(
snake_case__ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=snake_case__ , )
__snake_case = True if config.feat_extract_norm == 'layer' else False
__snake_case = WavaVecaFeatureExtractor(
feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=snake_case__ , return_attention_mask=snake_case__ , )
__snake_case = WavaVecaProcessor(feature_extractor=snake_case__ , tokenizer=snake_case__ )
processor.save_pretrained(snake_case__ )
__snake_case = WavaVecaForCTC(snake_case__ )
else:
__snake_case = WavaVecaForPreTraining(snake_case__ )
if is_finetuned or is_seq_class:
__snake_case , __snake_case , __snake_case = fairseq.checkpoint_utils.load_model_ensemble_and_task(
[checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} )
else:
__snake_case = argparse.Namespace(task='audio_pretraining' )
__snake_case = fairseq.tasks.setup_task(snake_case__ )
__snake_case , __snake_case , __snake_case = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=snake_case__ )
__snake_case = model[0].eval()
recursively_load_weights(snake_case__ , snake_case__ , not is_finetuned )
hf_wavavec.save_pretrained(snake_case__ )
if __name__ == "__main__":
UpperCAmelCase__ : Any = argparse.ArgumentParser()
parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint")
parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model")
parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
parser.add_argument(
"--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not"
)
parser.add_argument(
"--is_seq_class",
action="store_true",
help="Whether the model to convert is a fine-tuned sequence classification model or not",
)
UpperCAmelCase__ : Tuple = parser.parse_args()
UpperCAmelCase__ : Dict = not args.not_finetuned and not args.is_seq_class
convert_wavaveca_checkpoint(
args.checkpoint_path,
args.pytorch_dump_folder_path,
args.config_path,
args.dict_path,
is_finetuned,
args.is_seq_class,
)
| 700 |
import inspect
from typing import Callable, List, Optional, Union
import torch
from transformers import (
CLIPImageProcessor,
CLIPTextModel,
CLIPTokenizer,
WhisperForConditionalGeneration,
WhisperProcessor,
)
from diffusers import (
AutoencoderKL,
DDIMScheduler,
DiffusionPipeline,
LMSDiscreteScheduler,
PNDMScheduler,
UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.utils import logging
UpperCAmelCase__ : Any = logging.get_logger(__name__) # pylint: disable=invalid-name
class __lowercase ( lowerCamelCase__ ):
def __init__( self , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) -> List[str]:
super().__init__()
if safety_checker is None:
logger.warning(
F"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered'
' results in services or applications open to the public. Both the diffusers team and Hugging Face'
' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling'
' it only for use-cases that involve analyzing network behavior or auditing its results. For more'
' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .')
self.register_modules(
speech_model=lowercase_ , speech_processor=lowercase_ , vae=lowercase_ , text_encoder=lowercase_ , tokenizer=lowercase_ , unet=lowercase_ , scheduler=lowercase_ , feature_extractor=lowercase_ , )
def _a ( self , lowercase_ = "auto") -> Union[str, Any]:
if slice_size == "auto":
__snake_case = self.unet.config.attention_head_dim // 2
self.unet.set_attention_slice(lowercase_)
def _a ( self) -> Any:
self.enable_attention_slicing(lowercase_)
@torch.no_grad()
def __call__( self , lowercase_ , lowercase_=1_6_0_0_0 , lowercase_ = 5_1_2 , lowercase_ = 5_1_2 , lowercase_ = 5_0 , lowercase_ = 7.5 , lowercase_ = None , lowercase_ = 1 , lowercase_ = 0.0 , lowercase_ = None , lowercase_ = None , lowercase_ = "pil" , lowercase_ = True , lowercase_ = None , lowercase_ = 1 , **lowercase_ , ) -> List[str]:
__snake_case = self.speech_processor.feature_extractor(
lowercase_ , return_tensors='pt' , sampling_rate=lowercase_).input_features.to(self.device)
__snake_case = self.speech_model.generate(lowercase_ , max_length=4_8_0_0_0_0)
__snake_case = self.speech_processor.tokenizer.batch_decode(lowercase_ , skip_special_tokens=lowercase_ , normalize=lowercase_)[
0
]
if isinstance(lowercase_ , lowercase_):
__snake_case = 1
elif isinstance(lowercase_ , lowercase_):
__snake_case = len(lowercase_)
else:
raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(lowercase_)}")
if height % 8 != 0 or width % 8 != 0:
raise ValueError(F"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
if (callback_steps is None) or (
callback_steps is not None and (not isinstance(lowercase_ , lowercase_) or callback_steps <= 0)
):
raise ValueError(
F"`callback_steps` has to be a positive integer but is {callback_steps} of type"
F" {type(lowercase_)}.")
# get prompt text embeddings
__snake_case = self.tokenizer(
lowercase_ , padding='max_length' , max_length=self.tokenizer.model_max_length , return_tensors='pt' , )
__snake_case = text_inputs.input_ids
if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
__snake_case = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])
logger.warning(
'The following part of your input was truncated because CLIP can only handle sequences up to'
F" {self.tokenizer.model_max_length} tokens: {removed_text}")
__snake_case = text_input_ids[:, : self.tokenizer.model_max_length]
__snake_case = self.text_encoder(text_input_ids.to(self.device))[0]
# duplicate text embeddings for each generation per prompt, using mps friendly method
__snake_case , __snake_case , __snake_case = text_embeddings.shape
__snake_case = text_embeddings.repeat(1 , lowercase_ , 1)
__snake_case = text_embeddings.view(bs_embed * num_images_per_prompt , lowercase_ , -1)
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
# corresponds to doing no classifier free guidance.
__snake_case = guidance_scale > 1.0
# get unconditional embeddings for classifier free guidance
if do_classifier_free_guidance:
__snake_case = 42
if negative_prompt is None:
__snake_case = [''] * batch_size
elif type(lowercase_) is not type(lowercase_):
raise TypeError(
F"`negative_prompt` should be the same type to `prompt`, but got {type(lowercase_)} !="
F" {type(lowercase_)}.")
elif isinstance(lowercase_ , lowercase_):
__snake_case = [negative_prompt]
elif batch_size != len(lowercase_):
raise ValueError(
F"`negative_prompt`: {negative_prompt} has batch size {len(lowercase_)}, but `prompt`:"
F" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
' the batch size of `prompt`.')
else:
__snake_case = negative_prompt
__snake_case = text_input_ids.shape[-1]
__snake_case = self.tokenizer(
lowercase_ , padding='max_length' , max_length=lowercase_ , truncation=lowercase_ , return_tensors='pt' , )
__snake_case = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
__snake_case = uncond_embeddings.shape[1]
__snake_case = uncond_embeddings.repeat(1 , lowercase_ , 1)
__snake_case = uncond_embeddings.view(batch_size * num_images_per_prompt , lowercase_ , -1)
# For classifier free guidance, we need to do two forward passes.
# Here we concatenate the unconditional and text embeddings into a single batch
# to avoid doing two forward passes
__snake_case = torch.cat([uncond_embeddings, text_embeddings])
# get the initial random noise unless the user supplied it
# Unlike in other pipelines, latents need to be generated in the target device
# for 1-to-1 results reproducibility with the CompVis implementation.
# However this currently doesn't work in `mps`.
__snake_case = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
__snake_case = text_embeddings.dtype
if latents is None:
if self.device.type == "mps":
# randn does not exist on mps
__snake_case = torch.randn(lowercase_ , generator=lowercase_ , device='cpu' , dtype=lowercase_).to(
self.device)
else:
__snake_case = torch.randn(lowercase_ , generator=lowercase_ , device=self.device , dtype=lowercase_)
else:
if latents.shape != latents_shape:
raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
__snake_case = latents.to(self.device)
# set timesteps
self.scheduler.set_timesteps(lowercase_)
# Some schedulers like PNDM have timesteps as arrays
# It's more optimized to move all timesteps to correct device beforehand
__snake_case = self.scheduler.timesteps.to(self.device)
# scale the initial noise by the standard deviation required by the scheduler
__snake_case = latents * self.scheduler.init_noise_sigma
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
# and should be between [0, 1]
__snake_case = 'eta' in set(inspect.signature(self.scheduler.step).parameters.keys())
__snake_case = {}
if accepts_eta:
__snake_case = eta
for i, t in enumerate(self.progress_bar(lowercase_)):
# expand the latents if we are doing classifier free guidance
__snake_case = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
__snake_case = self.scheduler.scale_model_input(lowercase_ , lowercase_)
# predict the noise residual
__snake_case = self.unet(lowercase_ , lowercase_ , encoder_hidden_states=lowercase_).sample
# perform guidance
if do_classifier_free_guidance:
__snake_case , __snake_case = noise_pred.chunk(2)
__snake_case = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
# compute the previous noisy sample x_t -> x_t-1
__snake_case = self.scheduler.step(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample
# call the callback, if provided
if callback is not None and i % callback_steps == 0:
callback(lowercase_ , lowercase_ , lowercase_)
__snake_case = 1 / 0.1_8215 * latents
__snake_case = self.vae.decode(lowercase_).sample
__snake_case = (image / 2 + 0.5).clamp(0 , 1)
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
__snake_case = image.cpu().permute(0 , 2 , 3 , 1).float().numpy()
if output_type == "pil":
__snake_case = self.numpy_to_pil(lowercase_)
if not return_dict:
return image
return StableDiffusionPipelineOutput(images=lowercase_ , nsfw_content_detected=lowercase_)
| 676 | 0 |
import unittest
from transformers import (
MODEL_FOR_CAUSAL_LM_MAPPING,
TF_MODEL_FOR_CAUSAL_LM_MAPPING,
TextGenerationPipeline,
logging,
pipeline,
)
from transformers.testing_utils import (
CaptureLogger,
is_pipeline_test,
require_accelerate,
require_tf,
require_torch,
require_torch_gpu,
require_torch_or_tf,
)
from .test_pipelines_common import ANY
@is_pipeline_test
@require_torch_or_tf
class _lowerCAmelCase ( unittest.TestCase ):
"""simple docstring"""
lowerCAmelCase__ =MODEL_FOR_CAUSAL_LM_MAPPING
lowerCAmelCase__ =TF_MODEL_FOR_CAUSAL_LM_MAPPING
@require_torch
def UpperCAmelCase ( self ) -> Any:
"""simple docstring"""
snake_case__ : str =pipeline(task='''text-generation''' , model='''sshleifer/tiny-ctrl''' , framework='''pt''' )
# Using `do_sample=False` to force deterministic output
snake_case__ : int =text_generator('''This is a test''' , do_sample=__SCREAMING_SNAKE_CASE )
self.assertEqual(
__SCREAMING_SNAKE_CASE , [
{
'''generated_text''': (
'''This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.'''
''' oscope. FiliFili@@'''
)
}
] , )
snake_case__ : Optional[Any] =text_generator(['''This is a test''', '''This is a second test'''] )
self.assertEqual(
__SCREAMING_SNAKE_CASE , [
[
{
'''generated_text''': (
'''This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.'''
''' oscope. FiliFili@@'''
)
}
],
[
{
'''generated_text''': (
'''This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy'''
''' oscope. oscope. FiliFili@@'''
)
}
],
] , )
snake_case__ : Optional[int] =text_generator('''This is a test''' , do_sample=__SCREAMING_SNAKE_CASE , num_return_sequences=2 , return_tensors=__SCREAMING_SNAKE_CASE )
self.assertEqual(
__SCREAMING_SNAKE_CASE , [
{'''generated_token_ids''': ANY(__SCREAMING_SNAKE_CASE )},
{'''generated_token_ids''': ANY(__SCREAMING_SNAKE_CASE )},
] , )
snake_case__ : Tuple =text_generator.model.config.eos_token_id
snake_case__ : List[Any] ='''<pad>'''
snake_case__ : Any =text_generator(
['''This is a test''', '''This is a second test'''] , do_sample=__SCREAMING_SNAKE_CASE , num_return_sequences=2 , batch_size=2 , return_tensors=__SCREAMING_SNAKE_CASE , )
self.assertEqual(
__SCREAMING_SNAKE_CASE , [
[
{'''generated_token_ids''': ANY(__SCREAMING_SNAKE_CASE )},
{'''generated_token_ids''': ANY(__SCREAMING_SNAKE_CASE )},
],
[
{'''generated_token_ids''': ANY(__SCREAMING_SNAKE_CASE )},
{'''generated_token_ids''': ANY(__SCREAMING_SNAKE_CASE )},
],
] , )
@require_tf
def UpperCAmelCase ( self ) -> Optional[Any]:
"""simple docstring"""
snake_case__ : str =pipeline(task='''text-generation''' , model='''sshleifer/tiny-ctrl''' , framework='''tf''' )
# Using `do_sample=False` to force deterministic output
snake_case__ : List[Any] =text_generator('''This is a test''' , do_sample=__SCREAMING_SNAKE_CASE )
self.assertEqual(
__SCREAMING_SNAKE_CASE , [
{
'''generated_text''': (
'''This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵'''
''' please,'''
)
}
] , )
snake_case__ : int =text_generator(['''This is a test''', '''This is a second test'''] , do_sample=__SCREAMING_SNAKE_CASE )
self.assertEqual(
__SCREAMING_SNAKE_CASE , [
[
{
'''generated_text''': (
'''This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵'''
''' please,'''
)
}
],
[
{
'''generated_text''': (
'''This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes'''
''' Cannes 閲閲Cannes Cannes Cannes 攵 please,'''
)
}
],
] , )
def UpperCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Dict:
"""simple docstring"""
snake_case__ : List[str] =TextGenerationPipeline(model=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE )
return text_generator, ["This is a test", "Another test"]
def UpperCAmelCase ( self ) -> Optional[int]:
"""simple docstring"""
snake_case__ : Union[str, Any] ='''Hello I believe in'''
snake_case__ : str =pipeline('''text-generation''' , model='''hf-internal-testing/tiny-random-gpt2''' )
snake_case__ : Optional[Any] =text_generator(__SCREAMING_SNAKE_CASE )
self.assertEqual(
__SCREAMING_SNAKE_CASE , [{'''generated_text''': '''Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe'''}] , )
snake_case__ : Union[str, Any] =text_generator(__SCREAMING_SNAKE_CASE , stop_sequence=''' fe''' )
self.assertEqual(__SCREAMING_SNAKE_CASE , [{'''generated_text''': '''Hello I believe in fe'''}] )
def UpperCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> List[str]:
"""simple docstring"""
snake_case__ : Any =text_generator.model
snake_case__ : List[Any] =text_generator.tokenizer
snake_case__ : Tuple =text_generator('''This is a test''' )
self.assertEqual(__SCREAMING_SNAKE_CASE , [{'''generated_text''': ANY(__SCREAMING_SNAKE_CASE )}] )
self.assertTrue(outputs[0]['''generated_text'''].startswith('''This is a test''' ) )
snake_case__ : str =text_generator('''This is a test''' , return_full_text=__SCREAMING_SNAKE_CASE )
self.assertEqual(__SCREAMING_SNAKE_CASE , [{'''generated_text''': ANY(__SCREAMING_SNAKE_CASE )}] )
self.assertNotIn('''This is a test''' , outputs[0]['''generated_text'''] )
snake_case__ : Optional[int] =pipeline(task='''text-generation''' , model=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE , return_full_text=__SCREAMING_SNAKE_CASE )
snake_case__ : Optional[int] =text_generator('''This is a test''' )
self.assertEqual(__SCREAMING_SNAKE_CASE , [{'''generated_text''': ANY(__SCREAMING_SNAKE_CASE )}] )
self.assertNotIn('''This is a test''' , outputs[0]['''generated_text'''] )
snake_case__ : Union[str, Any] =text_generator('''This is a test''' , return_full_text=__SCREAMING_SNAKE_CASE )
self.assertEqual(__SCREAMING_SNAKE_CASE , [{'''generated_text''': ANY(__SCREAMING_SNAKE_CASE )}] )
self.assertTrue(outputs[0]['''generated_text'''].startswith('''This is a test''' ) )
snake_case__ : List[Any] =text_generator(['''This is great !''', '''Something else'''] , num_return_sequences=2 , do_sample=__SCREAMING_SNAKE_CASE )
self.assertEqual(
__SCREAMING_SNAKE_CASE , [
[{'''generated_text''': ANY(__SCREAMING_SNAKE_CASE )}, {'''generated_text''': ANY(__SCREAMING_SNAKE_CASE )}],
[{'''generated_text''': ANY(__SCREAMING_SNAKE_CASE )}, {'''generated_text''': ANY(__SCREAMING_SNAKE_CASE )}],
] , )
if text_generator.tokenizer.pad_token is not None:
snake_case__ : str =text_generator(
['''This is great !''', '''Something else'''] , num_return_sequences=2 , batch_size=2 , do_sample=__SCREAMING_SNAKE_CASE )
self.assertEqual(
__SCREAMING_SNAKE_CASE , [
[{'''generated_text''': ANY(__SCREAMING_SNAKE_CASE )}, {'''generated_text''': ANY(__SCREAMING_SNAKE_CASE )}],
[{'''generated_text''': ANY(__SCREAMING_SNAKE_CASE )}, {'''generated_text''': ANY(__SCREAMING_SNAKE_CASE )}],
] , )
with self.assertRaises(__SCREAMING_SNAKE_CASE ):
snake_case__ : Union[str, Any] =text_generator('''test''' , return_full_text=__SCREAMING_SNAKE_CASE , return_text=__SCREAMING_SNAKE_CASE )
with self.assertRaises(__SCREAMING_SNAKE_CASE ):
snake_case__ : List[str] =text_generator('''test''' , return_full_text=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE )
with self.assertRaises(__SCREAMING_SNAKE_CASE ):
snake_case__ : List[str] =text_generator('''test''' , return_text=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE )
# Empty prompt is slighly special
# it requires BOS token to exist.
# Special case for Pegasus which will always append EOS so will
# work even without BOS.
if (
text_generator.tokenizer.bos_token_id is not None
or "Pegasus" in tokenizer.__class__.__name__
or "Git" in model.__class__.__name__
):
snake_case__ : List[Any] =text_generator('''''' )
self.assertEqual(__SCREAMING_SNAKE_CASE , [{'''generated_text''': ANY(__SCREAMING_SNAKE_CASE )}] )
else:
with self.assertRaises((ValueError, AssertionError) ):
snake_case__ : Optional[int] =text_generator('''''' )
if text_generator.framework == "tf":
# TF generation does not support max_new_tokens, and it's impossible
# to control long generation with only max_length without
# fancy calculation, dismissing tests for now.
return
# We don't care about infinite range models.
# They already work.
# Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly.
snake_case__ : Dict =['''RwkvForCausalLM''', '''XGLMForCausalLM''', '''GPTNeoXForCausalLM''']
if (
tokenizer.model_max_length < 1_0000
and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS
):
# Handling of large generations
with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError) ):
text_generator('''This is a test''' * 500 , max_new_tokens=20 )
snake_case__ : Any =text_generator('''This is a test''' * 500 , handle_long_generation='''hole''' , max_new_tokens=20 )
# Hole strategy cannot work
with self.assertRaises(__SCREAMING_SNAKE_CASE ):
text_generator(
'''This is a test''' * 500 , handle_long_generation='''hole''' , max_new_tokens=tokenizer.model_max_length + 10 , )
@require_torch
@require_accelerate
@require_torch_gpu
def UpperCAmelCase ( self ) -> List[Any]:
"""simple docstring"""
import torch
# Classic `model_kwargs`
snake_case__ : Dict =pipeline(
model='''hf-internal-testing/tiny-random-bloom''' , model_kwargs={'''device_map''': '''auto''', '''torch_dtype''': torch.bfloataa} , )
self.assertEqual(pipe.model.device , torch.device(0 ) )
self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa )
snake_case__ : Optional[int] =pipe('''This is a test''' )
self.assertEqual(
__SCREAMING_SNAKE_CASE , [
{
'''generated_text''': (
'''This is a test test test test test test test test test test test test test test test test'''
''' test'''
)
}
] , )
# Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.)
snake_case__ : Tuple =pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device_map='''auto''' , torch_dtype=torch.bfloataa )
self.assertEqual(pipe.model.device , torch.device(0 ) )
self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa )
snake_case__ : List[Any] =pipe('''This is a test''' )
self.assertEqual(
__SCREAMING_SNAKE_CASE , [
{
'''generated_text''': (
'''This is a test test test test test test test test test test test test test test test test'''
''' test'''
)
}
] , )
# torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602
snake_case__ : Dict =pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device_map='''auto''' )
self.assertEqual(pipe.model.device , torch.device(0 ) )
self.assertEqual(pipe.model.lm_head.weight.dtype , torch.floataa )
snake_case__ : Union[str, Any] =pipe('''This is a test''' )
self.assertEqual(
__SCREAMING_SNAKE_CASE , [
{
'''generated_text''': (
'''This is a test test test test test test test test test test test test test test test test'''
''' test'''
)
}
] , )
@require_torch
@require_torch_gpu
def UpperCAmelCase ( self ) -> Dict:
"""simple docstring"""
import torch
snake_case__ : str =pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device=0 , torch_dtype=torch.floataa )
pipe('''This is a test''' )
@require_torch
@require_accelerate
@require_torch_gpu
def UpperCAmelCase ( self ) -> Tuple:
"""simple docstring"""
import torch
snake_case__ : Any =pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device_map='''auto''' , torch_dtype=torch.floataa )
pipe('''This is a test''' , do_sample=__SCREAMING_SNAKE_CASE , top_p=0.5 )
def UpperCAmelCase ( self ) -> int:
"""simple docstring"""
snake_case__ : List[str] ='''Hello world'''
snake_case__ : int =pipeline('''text-generation''' , model='''hf-internal-testing/tiny-random-gpt2''' )
if text_generator.model.framework == "tf":
snake_case__ : List[Any] =logging.get_logger('''transformers.generation.tf_utils''' )
else:
snake_case__ : List[Any] =logging.get_logger('''transformers.generation.utils''' )
snake_case__ : Optional[int] ='''Both `max_new_tokens`''' # The beggining of the message to be checked in this test
# Both are set by the user -> log warning
with CaptureLogger(__SCREAMING_SNAKE_CASE ) as cl:
snake_case__ : Union[str, Any] =text_generator(__SCREAMING_SNAKE_CASE , max_length=10 , max_new_tokens=1 )
self.assertIn(__SCREAMING_SNAKE_CASE , cl.out )
# The user only sets one -> no warning
with CaptureLogger(__SCREAMING_SNAKE_CASE ) as cl:
snake_case__ : int =text_generator(__SCREAMING_SNAKE_CASE , max_new_tokens=1 )
self.assertNotIn(__SCREAMING_SNAKE_CASE , cl.out )
with CaptureLogger(__SCREAMING_SNAKE_CASE ) as cl:
snake_case__ : List[str] =text_generator(__SCREAMING_SNAKE_CASE , max_length=10 )
self.assertNotIn(__SCREAMING_SNAKE_CASE , cl.out )
| 381 |
def lowercase_ ( SCREAMING_SNAKE_CASE : bytes ):
"""simple docstring"""
return "".join([hex(SCREAMING_SNAKE_CASE )[2:].zfill(2 ).upper() for byte in list(SCREAMING_SNAKE_CASE )] )
def lowercase_ ( SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
# Check data validity, following RFC3548
# https://www.ietf.org/rfc/rfc3548.txt
if (len(SCREAMING_SNAKE_CASE ) % 2) != 0:
raise ValueError(
'''Base16 encoded data is invalid:
Data does not have an even number of hex digits.''' )
# Check the character set - the standard base16 alphabet
# is uppercase according to RFC3548 section 6
if not set(SCREAMING_SNAKE_CASE ) <= set('''0123456789ABCDEF''' ):
raise ValueError(
'''Base16 encoded data is invalid:
Data is not uppercase hex or it contains invalid characters.''' )
# For every two hexadecimal digits (= a byte), turn it into an integer.
# Then, string the result together into bytes, and return it.
return bytes(int(data[i] + data[i + 1] , 16 ) for i in range(0 , len(SCREAMING_SNAKE_CASE ) , 2 ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 381 | 1 |
from unittest import TestCase
from datasets import Sequence, Value
from datasets.arrow_dataset import Dataset
class _UpperCamelCase ( UpperCamelCase__ ):
def lowercase ( self: Dict ) -> Optional[int]:
"""simple docstring"""
return [
{"col_1": 3, "col_2": "a"},
{"col_1": 2, "col_2": "b"},
{"col_1": 1, "col_2": "c"},
{"col_1": 0, "col_2": "d"},
]
def lowercase ( self: Union[str, Any] ) -> Any:
"""simple docstring"""
UpperCamelCase_ = {"col_1": [3, 2, 1, 0], "col_2": ["a", "b", "c", "d"]}
return Dataset.from_dict(_SCREAMING_SNAKE_CASE )
def lowercase ( self: Union[str, Any] ) -> Optional[Any]:
"""simple docstring"""
UpperCamelCase_ = self._create_example_records()
UpperCamelCase_ = Dataset.from_list(_SCREAMING_SNAKE_CASE )
self.assertListEqual(dset.column_names , ["col_1", "col_2"] )
for i, r in enumerate(_SCREAMING_SNAKE_CASE ):
self.assertDictEqual(_SCREAMING_SNAKE_CASE , example_records[i] )
def lowercase ( self: Tuple ) -> int:
"""simple docstring"""
UpperCamelCase_ = self._create_example_records()
UpperCamelCase_ = Dataset.from_list(_SCREAMING_SNAKE_CASE )
UpperCamelCase_ = Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]} )
self.assertEqual(dset.info , dset_from_dict.info )
def lowercase ( self: Any ) -> int: # checks what happens with missing columns
"""simple docstring"""
UpperCamelCase_ = [{"col_1": 1}, {"col_2": "x"}]
UpperCamelCase_ = Dataset.from_list(_SCREAMING_SNAKE_CASE )
self.assertDictEqual(dset[0] , {"col_1": 1} )
self.assertDictEqual(dset[1] , {"col_1": None} ) # NB: first record is used for columns
def lowercase ( self: Any ) -> Dict: # checks if the type can be inferred from the second record
"""simple docstring"""
UpperCamelCase_ = [{"col_1": []}, {"col_1": [1, 2]}]
UpperCamelCase_ = Dataset.from_list(_SCREAMING_SNAKE_CASE )
self.assertEqual(dset.info.features["col_1"] , Sequence(Value("int64" ) ) )
def lowercase ( self: Dict ) -> Optional[int]:
"""simple docstring"""
UpperCamelCase_ = Dataset.from_list([] )
self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 0 )
self.assertListEqual(dset.column_names , [] )
| 717 |
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 _UpperCamelCase ( lowerCAmelCase_ , unittest.TestCase ):
_UpperCamelCase : Union[str, Any] = XLMTokenizer
_UpperCamelCase : Optional[int] = False
def lowercase ( self: Dict ) -> Union[str, Any]:
"""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(_SCREAMING_SNAKE_CASE , range(len(_SCREAMING_SNAKE_CASE ) ) ) )
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(_SCREAMING_SNAKE_CASE ) )
with open(self.merges_file , "w" ) as fp:
fp.write("\n".join(_SCREAMING_SNAKE_CASE ) )
def lowercase ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: List[str] ) -> str:
"""simple docstring"""
UpperCamelCase_ = "lower newer"
UpperCamelCase_ = "lower newer"
return input_text, output_text
def lowercase ( self: int ) -> Tuple:
"""simple docstring"""
UpperCamelCase_ = XLMTokenizer(self.vocab_file , self.merges_file )
UpperCamelCase_ = "lower"
UpperCamelCase_ = ["low", "er</w>"]
UpperCamelCase_ = tokenizer.tokenize(_SCREAMING_SNAKE_CASE )
self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
UpperCamelCase_ = tokens + ["<unk>"]
UpperCamelCase_ = [14, 15, 20]
self.assertListEqual(tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE )
@slow
def lowercase ( self: Optional[int] ) -> Tuple:
"""simple docstring"""
UpperCamelCase_ = XLMTokenizer.from_pretrained("xlm-mlm-en-2048" )
UpperCamelCase_ = tokenizer.encode("sequence builders" , add_special_tokens=_SCREAMING_SNAKE_CASE )
UpperCamelCase_ = tokenizer.encode("multi-sequence build" , add_special_tokens=_SCREAMING_SNAKE_CASE )
UpperCamelCase_ = tokenizer.build_inputs_with_special_tokens(_SCREAMING_SNAKE_CASE )
UpperCamelCase_ = tokenizer.build_inputs_with_special_tokens(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
assert encoded_sentence == [0] + text + [1]
assert encoded_pair == [0] + text + [1] + text_a + [1]
| 371 | 0 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
__UpperCAmelCase = logging.get_logger(__name__)
__UpperCAmelCase = {
'shi-labs/dinat-mini-in1k-224': 'https://huggingface.co/shi-labs/dinat-mini-in1k-224/resolve/main/config.json',
# See all Dinat models at https://huggingface.co/models?filter=dinat
}
class __lowercase ( __lowerCamelCase , __lowerCamelCase ):
snake_case_ = """dinat"""
snake_case_ = {
"""num_attention_heads""": """num_heads""",
"""num_hidden_layers""": """num_layers""",
}
def __init__( self : Union[str, Any] ,A : Tuple=4 ,A : Dict=3 ,A : Union[str, Any]=64 ,A : List[str]=[3, 4, 6, 5] ,A : Any=[2, 4, 8, 16] ,A : Optional[Any]=7 ,A : Optional[Any]=[[1, 8, 1], [1, 4, 1, 4], [1, 2, 1, 2, 1, 2], [1, 1, 1, 1, 1]] ,A : List[Any]=3.0 ,A : int=True ,A : int=0.0 ,A : List[str]=0.0 ,A : Any=0.1 ,A : List[str]="gelu" ,A : Dict=0.0_2 ,A : Optional[int]=1e-5 ,A : Dict=0.0 ,A : str=None ,A : List[Any]=None ,**A : int ,):
'''simple docstring'''
super().__init__(**A )
UpperCAmelCase__ : str = patch_size
UpperCAmelCase__ : Tuple = num_channels
UpperCAmelCase__ : Optional[int] = embed_dim
UpperCAmelCase__ : int = depths
UpperCAmelCase__ : str = len(A )
UpperCAmelCase__ : List[str] = num_heads
UpperCAmelCase__ : Optional[Any] = kernel_size
UpperCAmelCase__ : str = dilations
UpperCAmelCase__ : Union[str, Any] = mlp_ratio
UpperCAmelCase__ : Optional[Any] = qkv_bias
UpperCAmelCase__ : int = hidden_dropout_prob
UpperCAmelCase__ : int = attention_probs_dropout_prob
UpperCAmelCase__ : Tuple = drop_path_rate
UpperCAmelCase__ : Any = hidden_act
UpperCAmelCase__ : Optional[int] = layer_norm_eps
UpperCAmelCase__ : str = initializer_range
# we set the hidden_size attribute in order to make Dinat work with VisionEncoderDecoderModel
# this indicates the channel dimension after the last stage of the model
UpperCAmelCase__ : Optional[int] = int(embed_dim * 2 ** (len(A ) - 1) )
UpperCAmelCase__ : Optional[Any] = layer_scale_init_value
UpperCAmelCase__ : Optional[Any] = ["""stem"""] + [f"stage{idx}" for idx in range(1 ,len(A ) + 1 )]
UpperCAmelCase__ , UpperCAmelCase__ : int = get_aligned_output_features_output_indices(
out_features=A ,out_indices=A ,stage_names=self.stage_names )
| 65 |
"""simple docstring"""
from unittest.mock import Mock, patch
from file_transfer.send_file import send_file
@patch("""socket.socket""" )
@patch("""builtins.open""" )
def __magic_name__ ( lowercase , lowercase ):
# ===== initialization =====
SCREAMING_SNAKE_CASE_: int =Mock()
SCREAMING_SNAKE_CASE_: int =conn, Mock()
SCREAMING_SNAKE_CASE_: Tuple =iter([1, None] )
SCREAMING_SNAKE_CASE_: Optional[Any] =lambda lowercase : next(lowercase )
# ===== invoke =====
send_file(filename="""mytext.txt""" , testing=lowercase )
# ===== ensurance =====
sock.assert_called_once()
sock.return_value.bind.assert_called_once()
sock.return_value.listen.assert_called_once()
sock.return_value.accept.assert_called_once()
conn.recv.assert_called_once()
file.return_value.__enter__.assert_called_once()
file.return_value.__enter__.return_value.read.assert_called()
conn.send.assert_called_once()
conn.close.assert_called_once()
sock.return_value.shutdown.assert_called_once()
sock.return_value.close.assert_called_once()
| 409 | 0 |
"""simple docstring"""
import json
import os
import shutil
import tempfile
import unittest
from multiprocessing import get_context
from pathlib import Path
import datasets
import numpy as np
from datasets import load_dataset
from parameterized import parameterized
from transformers import AutoProcessor
from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor
from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES
from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available
from ..wavaveca.test_feature_extraction_wavaveca import floats_list
if is_pyctcdecode_available():
from huggingface_hub import snapshot_download
from pyctcdecode import BeamSearchDecoderCTC
from transformers.models.wavaveca_with_lm import WavaVecaProcessorWithLM
from transformers.models.wavaveca_with_lm.processing_wavaveca_with_lm import WavaVecaDecoderWithLMOutput
if is_torch_available():
from transformers import WavaVecaForCTC
@require_pyctcdecode
class __SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]:
_UpperCamelCase : Any = "| <pad> <unk> <s> </s> a b c d e f g h i j k".split()
_UpperCamelCase : Any = dict(zip(__a , range(len(__a ) ) ) )
_UpperCamelCase : Union[str, Any] = {
"unk_token": "<unk>",
"bos_token": "<s>",
"eos_token": "</s>",
}
_UpperCamelCase : List[str] = {
"feature_size": 1,
"padding_value": 0.0,
"sampling_rate": 1_6000,
"return_attention_mask": False,
"do_normalize": True,
}
_UpperCamelCase : Optional[Any] = tempfile.mkdtemp()
_UpperCamelCase : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
_UpperCamelCase : List[Any] = os.path.join(self.tmpdirname , __a )
with open(self.vocab_file , "w" , encoding="utf-8" ) as fp:
fp.write(json.dumps(__a ) + "\n" )
with open(self.feature_extraction_file , "w" , encoding="utf-8" ) as fp:
fp.write(json.dumps(__a ) + "\n" )
# load decoder from hub
_UpperCamelCase : List[Any] = "hf-internal-testing/ngram-beam-search-decoder"
def __SCREAMING_SNAKE_CASE ( self : Tuple , **__a : Union[str, Any] ) -> int:
_UpperCamelCase : Tuple = self.add_kwargs_tokens_map.copy()
kwargs.update(__a )
return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname , **__a )
def __SCREAMING_SNAKE_CASE ( self : Tuple , **__a : List[str] ) -> int:
return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname , **__a )
def __SCREAMING_SNAKE_CASE ( self : str , **__a : Optional[int] ) -> Tuple:
return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name , **__a )
def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]:
shutil.rmtree(self.tmpdirname )
def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]:
_UpperCamelCase : List[Any] = self.get_tokenizer()
_UpperCamelCase : Dict = self.get_feature_extractor()
_UpperCamelCase : Dict = self.get_decoder()
_UpperCamelCase : int = WavaVecaProcessorWithLM(tokenizer=__a , feature_extractor=__a , decoder=__a )
processor.save_pretrained(self.tmpdirname )
_UpperCamelCase : Optional[Any] = WavaVecaProcessorWithLM.from_pretrained(self.tmpdirname )
# tokenizer
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() )
self.assertIsInstance(processor.tokenizer , __a )
# feature extractor
self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() )
self.assertIsInstance(processor.feature_extractor , __a )
# decoder
self.assertEqual(processor.decoder._alphabet.labels , decoder._alphabet.labels )
self.assertEqual(
processor.decoder.model_container[decoder._model_key]._unigram_set , decoder.model_container[decoder._model_key]._unigram_set , )
self.assertIsInstance(processor.decoder , __a )
def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]:
_UpperCamelCase : List[Any] = WavaVecaProcessorWithLM(
tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() )
processor.save_pretrained(self.tmpdirname )
# make sure that error is thrown when decoder alphabet doesn't match
_UpperCamelCase : Union[str, Any] = WavaVecaProcessorWithLM.from_pretrained(
self.tmpdirname , alpha=5.0 , beta=3.0 , score_boundary=-7.0 , unk_score_offset=3 )
# decoder
self.assertEqual(processor.language_model.alpha , 5.0 )
self.assertEqual(processor.language_model.beta , 3.0 )
self.assertEqual(processor.language_model.score_boundary , -7.0 )
self.assertEqual(processor.language_model.unk_score_offset , 3 )
def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]:
_UpperCamelCase : int = self.get_tokenizer()
# add token to trigger raise
tokenizer.add_tokens(["xx"] )
with self.assertRaisesRegex(__a , "include" ):
WavaVecaProcessorWithLM(
tokenizer=__a , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() )
def __SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]:
_UpperCamelCase : Any = self.get_feature_extractor()
_UpperCamelCase : Dict = self.get_tokenizer()
_UpperCamelCase : str = self.get_decoder()
_UpperCamelCase : Tuple = WavaVecaProcessorWithLM(tokenizer=__a , feature_extractor=__a , decoder=__a )
_UpperCamelCase : Union[str, Any] = floats_list((3, 1000) )
_UpperCamelCase : List[Any] = feature_extractor(__a , return_tensors="np" )
_UpperCamelCase : Optional[Any] = processor(__a , 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 __SCREAMING_SNAKE_CASE ( self : Any ) -> int:
_UpperCamelCase : str = self.get_feature_extractor()
_UpperCamelCase : List[str] = self.get_tokenizer()
_UpperCamelCase : Union[str, Any] = self.get_decoder()
_UpperCamelCase : Dict = WavaVecaProcessorWithLM(tokenizer=__a , feature_extractor=__a , decoder=__a )
_UpperCamelCase : Optional[int] = "This is a test string"
_UpperCamelCase : Optional[int] = processor(text=__a )
_UpperCamelCase : Any = tokenizer(__a )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : Tuple=(2, 10, 16) , __a : int=77 ) -> List[Any]:
np.random.seed(__a )
return np.random.rand(*__a )
def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Union[str, Any]:
_UpperCamelCase : Optional[Any] = self.get_feature_extractor()
_UpperCamelCase : List[Any] = self.get_tokenizer()
_UpperCamelCase : Optional[Any] = self.get_decoder()
_UpperCamelCase : Optional[int] = WavaVecaProcessorWithLM(tokenizer=__a , feature_extractor=__a , decoder=__a )
_UpperCamelCase : Union[str, Any] = self._get_dummy_logits(shape=(10, 16) , seed=13 )
_UpperCamelCase : List[Any] = processor.decode(__a )
_UpperCamelCase : str = decoder.decode_beams(__a )[0]
self.assertEqual(decoded_decoder[0] , decoded_processor.text )
self.assertEqual("</s> <s> </s>" , decoded_processor.text )
self.assertEqual(decoded_decoder[-2] , decoded_processor.logit_score )
self.assertEqual(decoded_decoder[-1] , decoded_processor.lm_score )
@parameterized.expand([[None], ["fork"], ["spawn"]] )
def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : Tuple ) -> Any:
_UpperCamelCase : str = self.get_feature_extractor()
_UpperCamelCase : int = self.get_tokenizer()
_UpperCamelCase : str = self.get_decoder()
_UpperCamelCase : Dict = WavaVecaProcessorWithLM(tokenizer=__a , feature_extractor=__a , decoder=__a )
_UpperCamelCase : Any = self._get_dummy_logits()
# note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM.
# otherwise, the LM won't be available to the pool's sub-processes.
# manual logic used to allow parameterized test for both pool=None and pool=Pool(...)
if pool_context is None:
_UpperCamelCase : List[str] = processor.batch_decode(__a )
else:
with get_context(__a ).Pool() as pool:
_UpperCamelCase : List[str] = processor.batch_decode(__a , __a )
_UpperCamelCase : Any = list(__a )
with get_context("fork" ).Pool() as p:
_UpperCamelCase : Optional[int] = decoder.decode_beams_batch(__a , __a )
_UpperCamelCase : Dict = [], [], []
for beams in decoded_beams:
texts_decoder.append(beams[0][0] )
logit_scores_decoder.append(beams[0][-2] )
lm_scores_decoder.append(beams[0][-1] )
self.assertListEqual(__a , decoded_processor.text )
self.assertListEqual(["<s> <s> </s>", "<s> <s> <s>"] , decoded_processor.text )
self.assertListEqual(__a , decoded_processor.logit_score )
self.assertListEqual(__a , decoded_processor.lm_score )
def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int:
_UpperCamelCase : Dict = self.get_feature_extractor()
_UpperCamelCase : Any = self.get_tokenizer()
_UpperCamelCase : Optional[int] = self.get_decoder()
_UpperCamelCase : Optional[int] = WavaVecaProcessorWithLM(tokenizer=__a , feature_extractor=__a , decoder=__a )
_UpperCamelCase : int = self._get_dummy_logits()
_UpperCamelCase : Tuple = 15
_UpperCamelCase : List[Any] = -20.0
_UpperCamelCase : int = -4.0
_UpperCamelCase : Union[str, Any] = processor.batch_decode(
__a , beam_width=__a , beam_prune_logp=__a , token_min_logp=__a , )
_UpperCamelCase : List[str] = decoded_processor_out.text
_UpperCamelCase : Optional[int] = list(__a )
with get_context("fork" ).Pool() as pool:
_UpperCamelCase : List[str] = decoder.decode_beams_batch(
__a , __a , beam_width=__a , beam_prune_logp=__a , token_min_logp=__a , )
_UpperCamelCase : int = [d[0][0] for d in decoded_decoder_out]
_UpperCamelCase : List[Any] = [d[0][2] for d in decoded_decoder_out]
_UpperCamelCase : Optional[Any] = [d[0][3] for d in decoded_decoder_out]
self.assertListEqual(__a , __a )
self.assertListEqual(["</s> <s> <s>", "<s> <s> <s>"] , __a )
self.assertTrue(np.array_equal(__a , decoded_processor_out.logit_score ) )
self.assertTrue(np.allclose([-20.0_54, -18.4_47] , __a , atol=1e-3 ) )
self.assertTrue(np.array_equal(__a , decoded_processor_out.lm_score ) )
self.assertTrue(np.allclose([-15.5_54, -13.94_74] , __a , atol=1e-3 ) )
def __SCREAMING_SNAKE_CASE ( self : Any ) -> Any:
_UpperCamelCase : Optional[int] = self.get_feature_extractor()
_UpperCamelCase : Union[str, Any] = self.get_tokenizer()
_UpperCamelCase : Any = self.get_decoder()
_UpperCamelCase : Dict = WavaVecaProcessorWithLM(tokenizer=__a , feature_extractor=__a , decoder=__a )
_UpperCamelCase : Union[str, Any] = self._get_dummy_logits()
_UpperCamelCase : Optional[Any] = 2.0
_UpperCamelCase : Union[str, Any] = 5.0
_UpperCamelCase : Tuple = -20.0
_UpperCamelCase : str = True
_UpperCamelCase : Any = processor.batch_decode(
__a , alpha=__a , beta=__a , unk_score_offset=__a , lm_score_boundary=__a , )
_UpperCamelCase : str = decoded_processor_out.text
_UpperCamelCase : Union[str, Any] = list(__a )
decoder.reset_params(
alpha=__a , beta=__a , unk_score_offset=__a , lm_score_boundary=__a , )
with get_context("fork" ).Pool() as pool:
_UpperCamelCase : List[str] = decoder.decode_beams_batch(
__a , __a , )
_UpperCamelCase : str = [d[0][0] for d in decoded_decoder_out]
self.assertListEqual(__a , __a )
self.assertListEqual(["<s> </s> <s> </s> </s>", "</s> </s> <s> </s> </s>"] , __a )
_UpperCamelCase : Tuple = processor.decoder.model_container[processor.decoder._model_key]
self.assertEqual(lm_model.alpha , 2.0 )
self.assertEqual(lm_model.beta , 5.0 )
self.assertEqual(lm_model.unk_score_offset , -20.0 )
self.assertEqual(lm_model.score_boundary , __a )
def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict:
_UpperCamelCase : List[Any] = WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm" )
_UpperCamelCase : str = processor.decoder.model_container[processor.decoder._model_key]
_UpperCamelCase : Optional[Any] = Path(language_model._kenlm_model.path.decode("utf-8" ) ).parent.parent.absolute()
_UpperCamelCase : Dict = os.listdir(__a )
_UpperCamelCase : Dict = ["alphabet.json", "language_model"]
downloaded_decoder_files.sort()
expected_decoder_files.sort()
# test that only decoder relevant files from
# https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main
# are downloaded and none of the rest (e.g. README.md, ...)
self.assertListEqual(__a , __a )
def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]:
_UpperCamelCase : List[str] = snapshot_download("hf-internal-testing/processor_with_lm" )
_UpperCamelCase : int = WavaVecaProcessorWithLM.from_pretrained(__a )
_UpperCamelCase : Optional[Any] = processor.decoder.model_container[processor.decoder._model_key]
_UpperCamelCase : Dict = Path(language_model._kenlm_model.path.decode("utf-8" ) ).parent.parent.absolute()
_UpperCamelCase : Dict = os.listdir(__a )
_UpperCamelCase : Optional[Any] = os.listdir(__a )
local_decoder_files.sort()
expected_decoder_files.sort()
# test that both decoder form hub and local files in cache are the same
self.assertListEqual(__a , __a )
def __SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]:
_UpperCamelCase : List[Any] = WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm" )
_UpperCamelCase : Dict = AutoProcessor.from_pretrained("hf-internal-testing/processor_with_lm" )
_UpperCamelCase : Dict = floats_list((3, 1000) )
_UpperCamelCase : Optional[Any] = processor_wavaveca(__a , return_tensors="np" )
_UpperCamelCase : Dict = processor_auto(__a , return_tensors="np" )
for key in input_wavaveca.keys():
self.assertAlmostEqual(input_wavaveca[key].sum() , input_auto[key].sum() , delta=1e-2 )
_UpperCamelCase : List[str] = self._get_dummy_logits()
_UpperCamelCase : str = processor_wavaveca.batch_decode(__a )
_UpperCamelCase : str = processor_auto.batch_decode(__a )
self.assertListEqual(decoded_wavaveca.text , decoded_auto.text )
def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]:
_UpperCamelCase : Any = self.get_feature_extractor()
_UpperCamelCase : Optional[int] = self.get_tokenizer()
_UpperCamelCase : Any = self.get_decoder()
_UpperCamelCase : Tuple = WavaVecaProcessorWithLM(tokenizer=__a , feature_extractor=__a , decoder=__a )
self.assertListEqual(
processor.model_input_names , feature_extractor.model_input_names , msg="`processor` and `feature_extractor` model input names do not match" , )
@staticmethod
def __SCREAMING_SNAKE_CASE ( __a : Optional[Any] , __a : Optional[int] ) -> int:
_UpperCamelCase : Dict = [d[key] for d in offsets]
return retrieved_list
def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]:
_UpperCamelCase : Any = WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm" )
_UpperCamelCase : int = self._get_dummy_logits()[0]
_UpperCamelCase : List[str] = processor.decode(__a , output_word_offsets=__a )
# check Wav2Vec2CTCTokenizerOutput keys for word
self.assertEqual(len(outputs.keys() ) , 4 )
self.assertTrue("text" in outputs )
self.assertTrue("word_offsets" in outputs )
self.assertTrue(isinstance(__a , __a ) )
self.assertEqual(" ".join(self.get_from_offsets(outputs["word_offsets"] , "word" ) ) , outputs.text )
self.assertListEqual(self.get_from_offsets(outputs["word_offsets"] , "word" ) , ["<s>", "<s>", "</s>"] )
self.assertListEqual(self.get_from_offsets(outputs["word_offsets"] , "start_offset" ) , [0, 2, 4] )
self.assertListEqual(self.get_from_offsets(outputs["word_offsets"] , "end_offset" ) , [1, 3, 5] )
def __SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]:
_UpperCamelCase : List[str] = WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm" )
_UpperCamelCase : List[Any] = self._get_dummy_logits()
_UpperCamelCase : str = processor.batch_decode(__a , output_word_offsets=__a )
# check Wav2Vec2CTCTokenizerOutput keys for word
self.assertEqual(len(outputs.keys() ) , 4 )
self.assertTrue("text" in outputs )
self.assertTrue("word_offsets" in outputs )
self.assertTrue(isinstance(__a , __a ) )
self.assertListEqual(
[" ".join(self.get_from_offsets(__a , "word" ) ) for o in outputs["word_offsets"]] , outputs.text )
self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0] , "word" ) , ["<s>", "<s>", "</s>"] )
self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0] , "start_offset" ) , [0, 2, 4] )
self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0] , "end_offset" ) , [1, 3, 5] )
@slow
@require_torch
@require_torchaudio
def __SCREAMING_SNAKE_CASE ( self : Any ) -> Union[str, Any]:
import torch
_UpperCamelCase : Optional[int] = load_dataset("common_voice" , "en" , split="train" , streaming=__a )
_UpperCamelCase : Optional[int] = ds.cast_column("audio" , datasets.Audio(sampling_rate=1_6000 ) )
_UpperCamelCase : Any = iter(__a )
_UpperCamelCase : Union[str, Any] = next(__a )
_UpperCamelCase : Optional[Any] = AutoProcessor.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm" )
_UpperCamelCase : List[Any] = WavaVecaForCTC.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm" )
# compare to filename `common_voice_en_100038.mp3` of dataset viewer on https://huggingface.co/datasets/common_voice/viewer/en/train
_UpperCamelCase : int = processor(sample["audio"]["array"] , return_tensors="pt" ).input_values
with torch.no_grad():
_UpperCamelCase : Optional[Any] = model(__a ).logits.cpu().numpy()
_UpperCamelCase : Dict = processor.decode(logits[0] , output_word_offsets=__a )
_UpperCamelCase : Any = model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate
_UpperCamelCase : str = [
{
"start_time": d["start_offset"] * time_offset,
"end_time": d["end_offset"] * time_offset,
"word": d["word"],
}
for d in output["word_offsets"]
]
_UpperCamelCase : Dict = "WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL"
# output words
self.assertEqual(" ".join(self.get_from_offsets(__a , "word" ) ) , __a )
self.assertEqual(" ".join(self.get_from_offsets(__a , "word" ) ) , output.text )
# output times
_UpperCamelCase : List[str] = torch.tensor(self.get_from_offsets(__a , "start_time" ) )
_UpperCamelCase : List[Any] = torch.tensor(self.get_from_offsets(__a , "end_time" ) )
# fmt: off
_UpperCamelCase : List[Any] = torch.tensor([1.41_99, 1.65_99, 2.25_99, 3.0, 3.24, 3.59_99, 3.79_99, 4.09_99, 4.26, 4.94, 5.28, 5.65_99, 5.78, 5.94, 6.32, 6.53_99, 6.65_99] )
_UpperCamelCase : Tuple = torch.tensor([1.53_99, 1.89_99, 2.9, 3.16, 3.53_99, 3.72, 4.01_99, 4.17_99, 4.76, 5.15_99, 5.55_99, 5.69_99, 5.86, 6.19_99, 6.38, 6.61_99, 6.94] )
# fmt: on
self.assertTrue(torch.allclose(__a , __a , atol=0.01 ) )
self.assertTrue(torch.allclose(__a , __a , atol=0.01 ) )
| 719 |
"""simple docstring"""
import argparse
import collections
import os
import re
from transformers.utils import direct_transformers_import
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_table.py
lowerCamelCase__ = "src/transformers"
lowerCamelCase__ = "docs/source/en"
lowerCamelCase__ = "."
def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> List[str]:
"""simple docstring"""
with open(lowercase_ ,"r" ,encoding="utf-8" ,newline="\n" ) as f:
_UpperCamelCase : Union[str, Any] = f.readlines()
# Find the start prompt.
_UpperCamelCase : Dict = 0
while not lines[start_index].startswith(lowercase_ ):
start_index += 1
start_index += 1
_UpperCamelCase : Optional[int] = start_index
while not lines[end_index].startswith(lowercase_ ):
end_index += 1
end_index -= 1
while len(lines[start_index] ) <= 1:
start_index += 1
while len(lines[end_index] ) <= 1:
end_index -= 1
end_index += 1
return "".join(lines[start_index:end_index] ), start_index, end_index, lines
# Add here suffixes that are used to identify models, separated by |
lowerCamelCase__ = "Model|Encoder|Decoder|ForConditionalGeneration"
# Regexes that match TF/Flax/PT model names.
lowerCamelCase__ = re.compile(R"TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)")
lowerCamelCase__ = re.compile(R"Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)")
# Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes.
lowerCamelCase__ = re.compile(R"(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)")
# This is to make sure the transformers module imported is the one in the repo.
lowerCamelCase__ = direct_transformers_import(TRANSFORMERS_PATH)
def lowercase__ ( lowercase_ ) -> Any:
"""simple docstring"""
_UpperCamelCase : Tuple = re.finditer(".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)" ,lowercase_ )
return [m.group(0 ) for m in matches]
def lowercase__ ( lowercase_ ,lowercase_ ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase : str = 2 if text == "✅" or text == "❌" else len(lowercase_ )
_UpperCamelCase : Union[str, Any] = (width - text_length) // 2
_UpperCamelCase : Dict = width - text_length - left_indent
return " " * left_indent + text + " " * right_indent
def lowercase__ ( ) -> str:
"""simple docstring"""
_UpperCamelCase : Optional[Any] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
_UpperCamelCase : str = {
name: config_maping_names[code]
for code, name in transformers_module.MODEL_NAMES_MAPPING.items()
if code in config_maping_names
}
_UpperCamelCase : Dict = {name: config.replace("Config" ,"" ) for name, config in model_name_to_config.items()}
# Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax.
_UpperCamelCase : int = collections.defaultdict(lowercase_ )
_UpperCamelCase : Dict = collections.defaultdict(lowercase_ )
_UpperCamelCase : Dict = collections.defaultdict(lowercase_ )
_UpperCamelCase : int = collections.defaultdict(lowercase_ )
_UpperCamelCase : str = collections.defaultdict(lowercase_ )
# Let's lookup through all transformers object (once).
for attr_name in dir(lowercase_ ):
_UpperCamelCase : List[str] = None
if attr_name.endswith("Tokenizer" ):
_UpperCamelCase : Tuple = slow_tokenizers
_UpperCamelCase : Any = attr_name[:-9]
elif attr_name.endswith("TokenizerFast" ):
_UpperCamelCase : Optional[Any] = fast_tokenizers
_UpperCamelCase : List[str] = attr_name[:-13]
elif _re_tf_models.match(lowercase_ ) is not None:
_UpperCamelCase : List[Any] = tf_models
_UpperCamelCase : Dict = _re_tf_models.match(lowercase_ ).groups()[0]
elif _re_flax_models.match(lowercase_ ) is not None:
_UpperCamelCase : Dict = flax_models
_UpperCamelCase : Union[str, Any] = _re_flax_models.match(lowercase_ ).groups()[0]
elif _re_pt_models.match(lowercase_ ) is not None:
_UpperCamelCase : Optional[int] = pt_models
_UpperCamelCase : Any = _re_pt_models.match(lowercase_ ).groups()[0]
if lookup_dict is not None:
while len(lowercase_ ) > 0:
if attr_name in model_name_to_prefix.values():
_UpperCamelCase : Dict = True
break
# Try again after removing the last word in the name
_UpperCamelCase : List[str] = "".join(camel_case_split(lowercase_ )[:-1] )
# Let's build that table!
_UpperCamelCase : Any = list(model_name_to_config.keys() )
model_names.sort(key=str.lower )
_UpperCamelCase : List[str] = ["Model", "Tokenizer slow", "Tokenizer fast", "PyTorch support", "TensorFlow support", "Flax Support"]
# We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side).
_UpperCamelCase : Union[str, Any] = [len(lowercase_ ) + 2 for c in columns]
_UpperCamelCase : Any = max([len(lowercase_ ) for name in model_names] ) + 2
# Build the table per se
_UpperCamelCase : Tuple = "|" + "|".join([_center_text(lowercase_ ,lowercase_ ) for c, w in zip(lowercase_ ,lowercase_ )] ) + "|\n"
# Use ":-----:" format to center-aligned table cell texts
table += "|" + "|".join([":" + "-" * (w - 2) + ":" for w in widths] ) + "|\n"
_UpperCamelCase : Union[str, Any] = {True: "✅", False: "❌"}
for name in model_names:
_UpperCamelCase : Optional[int] = model_name_to_prefix[name]
_UpperCamelCase : Tuple = [
name,
check[slow_tokenizers[prefix]],
check[fast_tokenizers[prefix]],
check[pt_models[prefix]],
check[tf_models[prefix]],
check[flax_models[prefix]],
]
table += "|" + "|".join([_center_text(lowercase_ ,lowercase_ ) for l, w in zip(lowercase_ ,lowercase_ )] ) + "|\n"
return table
def lowercase__ ( lowercase_=False ) -> List[Any]:
"""simple docstring"""
_UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : str = _find_text_in_file(
filename=os.path.join(lowercase_ ,"index.md" ) ,start_prompt="<!--This table is updated automatically from the auto modules" ,end_prompt="<!-- End table-->" ,)
_UpperCamelCase : Any = get_model_table_from_auto_modules()
if current_table != new_table:
if overwrite:
with open(os.path.join(lowercase_ ,"index.md" ) ,"w" ,encoding="utf-8" ,newline="\n" ) as f:
f.writelines(lines[:start_index] + [new_table] + lines[end_index:] )
else:
raise ValueError(
"The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this." )
if __name__ == "__main__":
lowerCamelCase__ = argparse.ArgumentParser()
parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.")
lowerCamelCase__ = parser.parse_args()
check_model_table(args.fix_and_overwrite)
| 51 | 0 |
def a_ ( UpperCamelCase_ : list ) -> list:
"""simple docstring"""
if len(snake_case__ ) <= 1:
return lst
lowerCamelCase = 1
while i < len(snake_case__ ):
if lst[i - 1] <= lst[i]:
i += 1
else:
lowerCamelCase = lst[i], lst[i - 1]
i -= 1
if i == 0:
lowerCamelCase = 1
return lst
if __name__ == "__main__":
_lowerCAmelCase : List[Any] = input('Enter numbers separated by a comma:\n').strip()
_lowerCAmelCase : Union[str, Any] = [int(item) for item in user_input.split(',')]
print(gnome_sort(unsorted))
| 246 |
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 ( snake_case__ : Dict ) -> Optional[int]:
return EnvironmentCommand()
class lowerCAmelCase_ ( a__ ):
@staticmethod
def snake_case_ ( SCREAMING_SNAKE_CASE_ ) -> Tuple:
UpperCamelCase : List[Any] = parser.add_parser('env' )
download_parser.set_defaults(func=SCREAMING_SNAKE_CASE_ )
def snake_case_ ( self ) -> Optional[Any]:
UpperCamelCase : Any = huggingface_hub.__version__
UpperCamelCase : int = 'not installed'
UpperCamelCase : Union[str, Any] = 'NA'
if is_torch_available():
import torch
UpperCamelCase : Any = torch.__version__
UpperCamelCase : str = torch.cuda.is_available()
UpperCamelCase : Dict = 'not installed'
if is_transformers_available():
import transformers
UpperCamelCase : str = transformers.__version__
UpperCamelCase : Optional[Any] = 'not installed'
if is_accelerate_available():
import accelerate
UpperCamelCase : Dict = accelerate.__version__
UpperCamelCase : List[str] = 'not installed'
if is_xformers_available():
import xformers
UpperCamelCase : List[str] = xformers.__version__
UpperCamelCase : Dict = {
'`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 snake_case_ ( SCREAMING_SNAKE_CASE_ ) -> Tuple:
return "\n".join([F"""- {prop}: {val}""" for prop, val in d.items()] ) + "\n"
| 40 | 0 |
'''simple docstring'''
from __future__ import annotations
import unittest
from transformers import BlenderbotConfig, BlenderbotTokenizer, is_tf_available
from transformers.testing_utils import require_tf, require_tokenizers, slow
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotForConditionalGeneration, TFBlenderbotModel
@require_tf
class snake_case_ :
"""simple docstring"""
_lowerCamelCase = BlenderbotConfig
_lowerCamelCase = {}
_lowerCamelCase = "gelu"
def __init__( self ,lowercase ,lowercase=13 ,lowercase=7 ,lowercase=True ,lowercase=False ,lowercase=99 ,lowercase=32 ,lowercase=2 ,lowercase=4 ,lowercase=37 ,lowercase=0.1 ,lowercase=0.1 ,lowercase=20 ,lowercase=2 ,lowercase=1 ,lowercase=0 ,):
"""simple docstring"""
UpperCAmelCase_ : List[Any] = parent
UpperCAmelCase_ : List[str] = batch_size
UpperCAmelCase_ : Tuple = seq_length
UpperCAmelCase_ : str = is_training
UpperCAmelCase_ : List[str] = use_labels
UpperCAmelCase_ : List[Any] = vocab_size
UpperCAmelCase_ : Dict = hidden_size
UpperCAmelCase_ : List[str] = num_hidden_layers
UpperCAmelCase_ : Tuple = num_attention_heads
UpperCAmelCase_ : Tuple = intermediate_size
UpperCAmelCase_ : Tuple = hidden_dropout_prob
UpperCAmelCase_ : Any = attention_probs_dropout_prob
UpperCAmelCase_ : Optional[Any] = max_position_embeddings
UpperCAmelCase_ : List[Any] = eos_token_id
UpperCAmelCase_ : Union[str, Any] = pad_token_id
UpperCAmelCase_ : Union[str, Any] = bos_token_id
def A_ ( self):
"""simple docstring"""
UpperCAmelCase_ : Any = ids_tensor([self.batch_size, self.seq_length - 1] ,self.vocab_size)
UpperCAmelCase_ : List[str] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size) ,1)
UpperCAmelCase_ : Optional[int] = tf.concat([input_ids, eos_tensor] ,axis=1)
UpperCAmelCase_ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size)
UpperCAmelCase_ : Union[str, Any] = self.config_cls(
vocab_size=self.vocab_size ,d_model=self.hidden_size ,encoder_layers=self.num_hidden_layers ,decoder_layers=self.num_hidden_layers ,encoder_attention_heads=self.num_attention_heads ,decoder_attention_heads=self.num_attention_heads ,encoder_ffn_dim=self.intermediate_size ,decoder_ffn_dim=self.intermediate_size ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,eos_token_ids=[2] ,bos_token_id=self.bos_token_id ,pad_token_id=self.pad_token_id ,decoder_start_token_id=self.pad_token_id ,**self.config_updates ,)
UpperCAmelCase_ : Union[str, Any] = prepare_blenderbot_inputs_dict(UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_)
return config, inputs_dict
def A_ ( self ,lowercase ,lowercase):
"""simple docstring"""
UpperCAmelCase_ : str = TFBlenderbotModel(config=UpperCamelCase_).get_decoder()
UpperCAmelCase_ : Union[str, Any] = inputs_dict["input_ids"]
UpperCAmelCase_ : Dict = input_ids[:1, :]
UpperCAmelCase_ : int = inputs_dict["attention_mask"][:1, :]
UpperCAmelCase_ : Union[str, Any] = inputs_dict["head_mask"]
UpperCAmelCase_ : Union[str, Any] = 1
# first forward pass
UpperCAmelCase_ : List[Any] = model(UpperCamelCase_ ,attention_mask=UpperCamelCase_ ,head_mask=UpperCamelCase_ ,use_cache=UpperCamelCase_)
UpperCAmelCase_ : List[str] = outputs.to_tuple()
# create hypothetical next token and extent to next_input_ids
UpperCAmelCase_ : Union[str, Any] = ids_tensor((self.batch_size, 3) ,config.vocab_size)
UpperCAmelCase_ : int = tf.cast(ids_tensor((self.batch_size, 3) ,2) ,tf.inta)
# append to next input_ids and
UpperCAmelCase_ : str = tf.concat([input_ids, next_tokens] ,axis=-1)
UpperCAmelCase_ : Dict = tf.concat([attention_mask, next_attn_mask] ,axis=-1)
UpperCAmelCase_ : Tuple = model(UpperCamelCase_ ,attention_mask=UpperCamelCase_)[0]
UpperCAmelCase_ : Union[str, Any] = model(UpperCamelCase_ ,attention_mask=UpperCamelCase_ ,past_key_values=UpperCamelCase_)[0]
self.parent.assertEqual(next_tokens.shape[1] ,output_from_past.shape[1])
# select random slice
UpperCAmelCase_ : List[Any] = int(ids_tensor((1,) ,output_from_past.shape[-1]))
UpperCAmelCase_ : Tuple = output_from_no_past[:, -3:, random_slice_idx]
UpperCAmelCase_ : Dict = output_from_past[:, :, random_slice_idx]
# test that outputs are equal for slice
tf.debugging.assert_near(UpperCamelCase_ ,UpperCamelCase_ ,rtol=1E-3)
def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case=None , __snake_case=None , __snake_case=None , __snake_case=None , __snake_case=None , ) -> Union[str, Any]:
'''simple docstring'''
if attention_mask is None:
UpperCAmelCase_ : Union[str, Any] = tf.cast(tf.math.not_equal(lowerCamelCase__ , config.pad_token_id ) , tf.inta )
if decoder_attention_mask is None:
UpperCAmelCase_ : int = tf.concat(
[
tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ),
tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ),
] , axis=-1 , )
if head_mask is None:
UpperCAmelCase_ : Dict = tf.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
UpperCAmelCase_ : Optional[int] = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
if cross_attn_head_mask is None:
UpperCAmelCase_ : Optional[int] = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
return {
"input_ids": input_ids,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"decoder_attention_mask": decoder_attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"cross_attn_head_mask": cross_attn_head_mask,
}
@require_tf
class snake_case_ (lowercase__ , lowercase__ , unittest.TestCase ):
"""simple docstring"""
_lowerCamelCase = (TFBlenderbotForConditionalGeneration, TFBlenderbotModel) if is_tf_available() else ()
_lowerCamelCase = (TFBlenderbotForConditionalGeneration,) if is_tf_available() else ()
_lowerCamelCase = (
{
"conversational": TFBlenderbotForConditionalGeneration,
"feature-extraction": TFBlenderbotModel,
"summarization": TFBlenderbotForConditionalGeneration,
"text2text-generation": TFBlenderbotForConditionalGeneration,
"translation": TFBlenderbotForConditionalGeneration,
}
if is_tf_available()
else {}
)
_lowerCamelCase = True
_lowerCamelCase = False
_lowerCamelCase = False
def A_ ( self):
"""simple docstring"""
UpperCAmelCase_ : Optional[int] = TFBlenderbotModelTester(self)
UpperCAmelCase_ : str = ConfigTester(self ,config_class=UpperCamelCase_)
def A_ ( self):
"""simple docstring"""
self.config_tester.run_common_tests()
def A_ ( self):
"""simple docstring"""
UpperCAmelCase_ : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*UpperCamelCase_)
@require_tokenizers
@require_tf
class snake_case_ (unittest.TestCase ):
"""simple docstring"""
_lowerCamelCase = ["My friends are cool but they eat too many carbs."]
_lowerCamelCase = "facebook/blenderbot-400M-distill"
@cached_property
def A_ ( self):
"""simple docstring"""
return BlenderbotTokenizer.from_pretrained(self.model_name)
@cached_property
def A_ ( self):
"""simple docstring"""
UpperCAmelCase_ : Union[str, Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name)
return model
@slow
def A_ ( self):
"""simple docstring"""
UpperCAmelCase_ : List[str] = self.tokenizer(self.src_text ,return_tensors="tf")
UpperCAmelCase_ : List[str] = self.model.generate(
model_inputs.input_ids ,)
UpperCAmelCase_ : int = self.tokenizer.batch_decode(generated_ids.numpy() ,skip_special_tokens=UpperCamelCase_)[0]
assert (
generated_words
== " That's unfortunate. Are they trying to lose weight or are they just trying to be healthier?"
)
| 710 |
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch
import math
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, randn_tensor
from .scheduling_utils import SchedulerMixin, SchedulerOutput
@dataclass
class snake_case_ (lowercase__ ):
"""simple docstring"""
_lowerCamelCase = 42
_lowerCamelCase = 42
class snake_case_ (lowercase__ , lowercase__ ):
"""simple docstring"""
_lowerCamelCase = 1
@register_to_config
def __init__( self ,lowercase = 2000 ,lowercase = 0.15 ,lowercase = 0.01 ,lowercase = 1348.0 ,lowercase = 1E-5 ,lowercase = 1 ,):
"""simple docstring"""
UpperCAmelCase_ : Optional[int] = sigma_max
# setable values
UpperCAmelCase_ : Optional[int] = None
self.set_sigmas(lowercase ,lowercase ,lowercase ,lowercase)
def A_ ( self ,lowercase ,lowercase = None):
"""simple docstring"""
return sample
def A_ ( self ,lowercase ,lowercase = None ,lowercase = None):
"""simple docstring"""
UpperCAmelCase_ : int = sampling_eps if sampling_eps is not None else self.config.sampling_eps
UpperCAmelCase_ : List[Any] = torch.linspace(1 ,lowercase ,lowercase ,device=lowercase)
def A_ ( self ,lowercase ,lowercase = None ,lowercase = None ,lowercase = None):
"""simple docstring"""
UpperCAmelCase_ : Any = sigma_min if sigma_min is not None else self.config.sigma_min
UpperCAmelCase_ : int = sigma_max if sigma_max is not None else self.config.sigma_max
UpperCAmelCase_ : Union[str, Any] = sampling_eps if sampling_eps is not None else self.config.sampling_eps
if self.timesteps is None:
self.set_timesteps(lowercase ,lowercase)
UpperCAmelCase_ : Union[str, Any] = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps)
UpperCAmelCase_ : Optional[int] = torch.exp(torch.linspace(math.log(lowercase) ,math.log(lowercase) ,lowercase))
UpperCAmelCase_ : Any = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps])
def A_ ( self ,lowercase ,lowercase):
"""simple docstring"""
return torch.where(
timesteps == 0 ,torch.zeros_like(t.to(timesteps.device)) ,self.discrete_sigmas[timesteps - 1].to(timesteps.device) ,)
def A_ ( self ,lowercase ,lowercase ,lowercase ,lowercase = None ,lowercase = True ,):
"""simple docstring"""
if self.timesteps is None:
raise ValueError(
"`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler")
UpperCAmelCase_ : Optional[int] = timestep * torch.ones(
sample.shape[0] ,device=sample.device) # torch.repeat_interleave(timestep, sample.shape[0])
UpperCAmelCase_ : Tuple = (timestep * (len(self.timesteps) - 1)).long()
# mps requires indices to be in the same device, so we use cpu as is the default with cuda
UpperCAmelCase_ : Optional[int] = timesteps.to(self.discrete_sigmas.device)
UpperCAmelCase_ : Optional[Any] = self.discrete_sigmas[timesteps].to(sample.device)
UpperCAmelCase_ : Optional[Any] = self.get_adjacent_sigma(lowercase ,lowercase).to(sample.device)
UpperCAmelCase_ : Any = torch.zeros_like(lowercase)
UpperCAmelCase_ : Dict = (sigma**2 - adjacent_sigma**2) ** 0.5
# equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x)
# also equation 47 shows the analog from SDE models to ancestral sampling methods
UpperCAmelCase_ : Dict = diffusion.flatten()
while len(diffusion.shape) < len(sample.shape):
UpperCAmelCase_ : List[str] = diffusion.unsqueeze(-1)
UpperCAmelCase_ : List[Any] = drift - diffusion**2 * model_output
# equation 6: sample noise for the diffusion term of
UpperCAmelCase_ : Union[str, Any] = randn_tensor(
sample.shape ,layout=sample.layout ,generator=lowercase ,device=sample.device ,dtype=sample.dtype)
UpperCAmelCase_ : Any = sample - drift # subtract because `dt` is a small negative timestep
# TODO is the variable diffusion the correct scaling term for the noise?
UpperCAmelCase_ : Tuple = prev_sample_mean + diffusion * noise # add impact of diffusion field g
if not return_dict:
return (prev_sample, prev_sample_mean)
return SdeVeOutput(prev_sample=lowercase ,prev_sample_mean=lowercase)
def A_ ( self ,lowercase ,lowercase ,lowercase = None ,lowercase = True ,):
"""simple docstring"""
if self.timesteps is None:
raise ValueError(
"`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler")
# For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z"
# sample noise for correction
UpperCAmelCase_ : int = randn_tensor(sample.shape ,layout=sample.layout ,generator=lowercase).to(sample.device)
# compute step size from the model_output, the noise, and the snr
UpperCAmelCase_ : Union[str, Any] = torch.norm(model_output.reshape(model_output.shape[0] ,-1) ,dim=-1).mean()
UpperCAmelCase_ : Optional[Any] = torch.norm(noise.reshape(noise.shape[0] ,-1) ,dim=-1).mean()
UpperCAmelCase_ : List[Any] = (self.config.snr * noise_norm / grad_norm) ** 2 * 2
UpperCAmelCase_ : Optional[Any] = step_size * torch.ones(sample.shape[0]).to(sample.device)
# self.repeat_scalar(step_size, sample.shape[0])
# compute corrected sample: model_output term and noise term
UpperCAmelCase_ : Any = step_size.flatten()
while len(step_size.shape) < len(sample.shape):
UpperCAmelCase_ : Tuple = step_size.unsqueeze(-1)
UpperCAmelCase_ : Dict = sample + step_size * model_output
UpperCAmelCase_ : int = prev_sample_mean + ((step_size * 2) ** 0.5) * noise
if not return_dict:
return (prev_sample,)
return SchedulerOutput(prev_sample=lowercase)
def A_ ( self ,lowercase ,lowercase ,lowercase ,):
"""simple docstring"""
UpperCAmelCase_ : Any = timesteps.to(original_samples.device)
UpperCAmelCase_ : List[str] = self.discrete_sigmas.to(original_samples.device)[timesteps]
UpperCAmelCase_ : Tuple = (
noise * sigmas[:, None, None, None]
if noise is not None
else torch.randn_like(lowercase) * sigmas[:, None, None, None]
)
UpperCAmelCase_ : Tuple = noise + original_samples
return noisy_samples
def __len__( self):
"""simple docstring"""
return self.config.num_train_timesteps
| 455 | 0 |
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import EsmConfig, is_tf_available
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import numpy
import tensorflow as tf
from transformers.models.esm.modeling_tf_esm import (
TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST,
TFEsmForMaskedLM,
TFEsmForSequenceClassification,
TFEsmForTokenClassification,
TFEsmModel,
)
class __snake_case :
"""simple docstring"""
def __init__( self :List[str] , UpperCamelCase__ :List[str] , ):
_a = parent
_a = 13
_a = 7
_a = True
_a = True
_a = True
_a = 99
_a = 32
_a = 2
_a = 4
_a = 37
_a = "gelu"
_a = 0.1
_a = 0.1
_a = 512
_a = 16
_a = 2
_a = 0.02
_a = 3
_a = 4
_a = None
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
_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 = None
_a = None
_a = None
if self.use_labels:
_a = ids_tensor([self.batch_size] , self.type_sequence_label_size )
_a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
_a = ids_tensor([self.batch_size] , self.num_choices )
_a = EsmConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , pad_token_id=1 , 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, input_mask, sequence_labels, token_labels, choice_labels
def SCREAMING_SNAKE_CASE_ ( self :int ):
(
(
_a
) , (
_a
) , (
_a
) , (
_a
) , (
_a
) , (
_a
) ,
) = self.prepare_config_and_inputs()
_a = True
_a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] )
_a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 )
return (
config,
input_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
)
def SCREAMING_SNAKE_CASE_ ( self :str , UpperCamelCase__ :Any , UpperCamelCase__ :Optional[int] , UpperCamelCase__ :List[str] , UpperCamelCase__ :str , UpperCamelCase__ :List[Any] , UpperCamelCase__ :Tuple ):
_a = TFEsmModel(config=snake_case_ )
_a = {"input_ids": input_ids, "attention_mask": input_mask}
_a = model(snake_case_ )
_a = [input_ids, input_mask]
_a = model(snake_case_ )
_a = model(snake_case_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] , UpperCamelCase__ :List[Any] , UpperCamelCase__ :Union[str, Any] , UpperCamelCase__ :List[Any] , UpperCamelCase__ :Tuple , UpperCamelCase__ :Optional[int] , UpperCamelCase__ :Tuple , UpperCamelCase__ :Tuple , UpperCamelCase__ :int , ):
_a = True
_a = TFEsmModel(config=snake_case_ )
_a = {
"input_ids": input_ids,
"attention_mask": input_mask,
"encoder_hidden_states": encoder_hidden_states,
"encoder_attention_mask": encoder_attention_mask,
}
_a = model(snake_case_ )
_a = [input_ids, input_mask]
_a = model(snake_case_ , encoder_hidden_states=snake_case_ )
# Also check the case where encoder outputs are not passed
_a = model(snake_case_ , attention_mask=snake_case_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def SCREAMING_SNAKE_CASE_ ( self :Tuple , UpperCamelCase__ :Union[str, Any] , UpperCamelCase__ :str , UpperCamelCase__ :Optional[int] , UpperCamelCase__ :Optional[Any] , UpperCamelCase__ :Optional[Any] , UpperCamelCase__ :Any ):
_a = TFEsmForMaskedLM(config=snake_case_ )
_a = model([input_ids, input_mask] )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] , UpperCamelCase__ :Union[str, Any] , UpperCamelCase__ :List[str] , UpperCamelCase__ :Any , UpperCamelCase__ :Dict , UpperCamelCase__ :Dict , UpperCamelCase__ :List[str] ):
_a = self.num_labels
_a = TFEsmForTokenClassification(config=snake_case_ )
_a = {"input_ids": input_ids, "attention_mask": input_mask}
_a = model(snake_case_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
_a = self.prepare_config_and_inputs()
(
(
_a
) , (
_a
) , (
_a
) , (
_a
) , (
_a
) , (
_a
) ,
) = config_and_inputs
_a = {"input_ids": input_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_tf
class __snake_case ( __snake_case , __snake_case , unittest.TestCase ):
"""simple docstring"""
lowerCAmelCase_ : Optional[Any] = (
(
TFEsmModel,
TFEsmForMaskedLM,
TFEsmForSequenceClassification,
TFEsmForTokenClassification,
)
if is_tf_available()
else ()
)
lowerCAmelCase_ : Optional[Any] = (
{
'feature-extraction': TFEsmModel,
'fill-mask': TFEsmForMaskedLM,
'text-classification': TFEsmForSequenceClassification,
'token-classification': TFEsmForTokenClassification,
'zero-shot': TFEsmForSequenceClassification,
}
if is_tf_available()
else {}
)
lowerCAmelCase_ : Union[str, Any] = False
lowerCAmelCase_ : int = False
def SCREAMING_SNAKE_CASE_ ( self :Any ):
_a = TFEsmModelTester(self )
_a = ConfigTester(self , config_class=snake_case_ , hidden_size=37 )
def SCREAMING_SNAKE_CASE_ ( self :int ):
self.config_tester.run_common_tests()
def SCREAMING_SNAKE_CASE_ ( self :Any ):
_a = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*snake_case_ )
def SCREAMING_SNAKE_CASE_ ( self :str ):
_a = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_model_as_decoder(*snake_case_ )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
_a = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*snake_case_ )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
_a = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*snake_case_ )
@slow
def SCREAMING_SNAKE_CASE_ ( self :str ):
for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_a = TFEsmModel.from_pretrained(snake_case_ )
self.assertIsNotNone(snake_case_ )
@unittest.skip("Protein models do not support embedding resizing." )
def SCREAMING_SNAKE_CASE_ ( self :Any ):
pass
@unittest.skip("Protein models do not support embedding resizing." )
def SCREAMING_SNAKE_CASE_ ( self :Any ):
pass
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
_a , _a = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_a = model_class(snake_case_ )
assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer )
if model_class is TFEsmForMaskedLM:
# Output embedding test differs from the main test because they're a matrix, not a layer
_a = model.get_bias()
assert isinstance(snake_case_ , snake_case_ )
for k, v in name.items():
assert isinstance(snake_case_ , tf.Variable )
else:
_a = model.get_output_embeddings()
assert x is None
_a = model.get_bias()
assert name is None
@require_tf
class __snake_case ( unittest.TestCase ):
"""simple docstring"""
@slow
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
_a = TFEsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D" )
_a = tf.constant([[0, 1, 2, 3, 4, 5]] )
_a = model(snake_case_ )[0]
_a = [1, 6, 33]
self.assertEqual(list(output.numpy().shape ) , snake_case_ )
# compare the actual values for a slice.
_a = tf.constant(
[
[
[8.921518, -10.589814, -6.4671307],
[-6.3967156, -13.911377, -1.1211915],
[-7.781247, -13.951557, -3.740592],
]
] )
self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-2 ) )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Any ):
_a = TFEsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D" )
_a = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] )
_a = model(snake_case_ )[0]
# compare the actual values for a slice.
_a = tf.constant(
[
[
[0.14443092, 0.54125327, 0.3247739],
[0.30340484, 0.00526676, 0.31077722],
[0.32278043, -0.24987096, 0.3414628],
]
] )
self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
| 388 |
from __future__ import annotations
from fractions import Fraction
from math import gcd, sqrt
def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> bool:
"""simple docstring"""
_A = int(number**0.5 )
return number == sq * sq
def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> tuple[int, int]:
"""simple docstring"""
_A = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den
_A = x_den * y_den * z_den
_A = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
top //= hcf
bottom //= hcf
return top, bottom
def __lowerCAmelCase( _SCREAMING_SNAKE_CASE = 35 ) -> int:
"""simple docstring"""
_A = set()
_A = 42
_A = Fraction(0 )
_A = 42
for x_num in range(1 , order + 1 ):
for x_den in range(x_num + 1 , order + 1 ):
for y_num in range(1 , order + 1 ):
for y_den in range(y_num + 1 , order + 1 ):
# n=1
_A = x_num * y_den + x_den * y_num
_A = x_den * y_den
_A = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
_A = add_three(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
unique_s.add(_SCREAMING_SNAKE_CASE )
# n=2
_A = (
x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num
)
_A = x_den * x_den * y_den * y_den
if is_sq(_SCREAMING_SNAKE_CASE ) and is_sq(_SCREAMING_SNAKE_CASE ):
_A = int(sqrt(_SCREAMING_SNAKE_CASE ) )
_A = int(sqrt(_SCREAMING_SNAKE_CASE ) )
_A = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
_A = add_three(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
unique_s.add(_SCREAMING_SNAKE_CASE )
# n=-1
_A = x_num * y_num
_A = x_den * y_num + x_num * y_den
_A = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
_A = add_three(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
unique_s.add(_SCREAMING_SNAKE_CASE )
# n=2
_A = x_num * x_num * y_num * y_num
_A = (
x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den
)
if is_sq(_SCREAMING_SNAKE_CASE ) and is_sq(_SCREAMING_SNAKE_CASE ):
_A = int(sqrt(_SCREAMING_SNAKE_CASE ) )
_A = int(sqrt(_SCREAMING_SNAKE_CASE ) )
_A = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
_A = add_three(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
unique_s.add(_SCREAMING_SNAKE_CASE )
for num, den in unique_s:
total += Fraction(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
return total.denominator + total.numerator
if __name__ == "__main__":
print(f"{solution() = }")
| 27 | 0 |
import heapq
def _lowerCamelCase ( __A : dict ) -> set[int]:
_UpperCAmelCase : list[list] = []
# for each node and his adjacency list add them and the rank of the node to queue
# using heapq module the queue will be filled like a Priority Queue
# heapq works with a min priority queue, so I used -1*len(v) to build it
for key, value in graph.items():
# O(log(n))
heapq.heappush(__A , [-1 * len(__A ), (key, value)] )
# chosen_vertices = set of chosen vertices
_UpperCAmelCase : Union[str, Any] = set()
# while queue isn't empty and there are still edges
# (queue[0][0] is the rank of the node with max rank)
while queue and queue[0][0] != 0:
# extract vertex with max rank from queue and add it to chosen_vertices
_UpperCAmelCase : Tuple = heapq.heappop(__A )[1][0]
chosen_vertices.add(__A )
# Remove all arcs adjacent to argmax
for elem in queue:
# if v haven't adjacent node, skip
if elem[0] == 0:
continue
# if argmax is reachable from elem
# remove argmax from elem's adjacent list and update his rank
if argmax in elem[1][1]:
_UpperCAmelCase : Dict = elem[1][1].index(__A )
del elem[1][1][index]
elem[0] += 1
# re-order the queue
heapq.heapify(__A )
return chosen_vertices
if __name__ == "__main__":
import doctest
doctest.testmod()
SCREAMING_SNAKE_CASE = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]}
print(F'Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}')
| 186 |
import argparse
import os
import re
SCREAMING_SNAKE_CASE = 'src/transformers/models/auto'
# re pattern that matches mapping introductions:
# SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict
SCREAMING_SNAKE_CASE = re.compile(R'[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict')
# re pattern that matches identifiers in mappings
SCREAMING_SNAKE_CASE = re.compile(R'\s*\(\s*"(\S[^"]+)"')
def _lowerCamelCase ( __A : Optional[int] , __A : bool = False ) -> int:
with open(__A , '''r''' , encoding='''utf-8''' ) as f:
_UpperCAmelCase : Union[str, Any] = f.read()
_UpperCAmelCase : Any = content.split('''\n''' )
_UpperCAmelCase : Any = []
_UpperCAmelCase : Tuple = 0
while line_idx < len(__A ):
if _re_intro_mapping.search(lines[line_idx] ) is not None:
_UpperCAmelCase : Union[str, Any] = len(re.search(r'''^(\s*)\S''' , lines[line_idx] ).groups()[0] ) + 8
# Start of a new mapping!
while not lines[line_idx].startswith(''' ''' * indent + '''(''' ):
new_lines.append(lines[line_idx] )
line_idx += 1
_UpperCAmelCase : str = []
while lines[line_idx].strip() != "]":
# Blocks either fit in one line or not
if lines[line_idx].strip() == "(":
_UpperCAmelCase : List[str] = line_idx
while not lines[line_idx].startswith(''' ''' * indent + ''')''' ):
line_idx += 1
blocks.append('''\n'''.join(lines[start_idx : line_idx + 1] ) )
else:
blocks.append(lines[line_idx] )
line_idx += 1
# Sort blocks by their identifiers
_UpperCAmelCase : Tuple = sorted(__A , key=lambda __A : _re_identifier.search(__A ).groups()[0] )
new_lines += blocks
else:
new_lines.append(lines[line_idx] )
line_idx += 1
if overwrite:
with open(__A , '''w''' , encoding='''utf-8''' ) as f:
f.write('''\n'''.join(__A ) )
elif "\n".join(__A ) != content:
return True
def _lowerCamelCase ( __A : bool = False ) -> List[str]:
_UpperCAmelCase : List[str] = [os.path.join(__A , __A ) for f in os.listdir(__A ) if f.endswith('''.py''' )]
_UpperCAmelCase : List[Any] = [sort_auto_mapping(__A , overwrite=__A ) for fname in fnames]
if not overwrite and any(__A ):
_UpperCAmelCase : Optional[int] = [f for f, d in zip(__A , __A ) if d]
raise ValueError(
f'''The following files have auto mappings that need sorting: {', '.join(__A )}. Run `make style` to fix'''
''' this.''' )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE = argparse.ArgumentParser()
parser.add_argument('--check_only', action='store_true', help='Whether to only check or fix style.')
SCREAMING_SNAKE_CASE = parser.parse_args()
sort_all_auto_mappings(not args.check_only)
| 186 | 1 |
import argparse
import json
import os
import time
import zipfile
from get_ci_error_statistics import download_artifact, get_artifacts_links
from transformers import logging
snake_case__ : str = logging.get_logger(__name__)
def lowercase ( _lowerCAmelCase , _lowerCAmelCase ):
UpperCAmelCase__ = set()
UpperCAmelCase__ = []
def parse_line(_lowerCAmelCase ):
for line in fp:
if isinstance(_lowerCAmelCase , _lowerCAmelCase ):
UpperCAmelCase__ = line.decode("""UTF-8""" )
if "warnings summary (final)" in line:
continue
# This means we are outside the body of a warning
elif not line.startswith(""" """ ):
# process a single warning and move it to `selected_warnings`.
if len(_lowerCAmelCase ) > 0:
UpperCAmelCase__ = """\n""".join(_lowerCAmelCase )
# Only keep the warnings specified in `targets`
if any(F''': {x}: ''' in warning for x in targets ):
selected_warnings.add(_lowerCAmelCase )
buffer.clear()
continue
else:
UpperCAmelCase__ = line.strip()
buffer.append(_lowerCAmelCase )
if from_gh:
for filename in os.listdir(_lowerCAmelCase ):
UpperCAmelCase__ = os.path.join(_lowerCAmelCase , _lowerCAmelCase )
if not os.path.isdir(_lowerCAmelCase ):
# read the file
if filename != "warnings.txt":
continue
with open(_lowerCAmelCase ) as fp:
parse_line(_lowerCAmelCase )
else:
try:
with zipfile.ZipFile(_lowerCAmelCase ) as z:
for filename in z.namelist():
if not os.path.isdir(_lowerCAmelCase ):
# read the file
if filename != "warnings.txt":
continue
with z.open(_lowerCAmelCase ) as fp:
parse_line(_lowerCAmelCase )
except Exception:
logger.warning(
F'''{artifact_path} is either an invalid zip file or something else wrong. This file is skipped.''' )
return selected_warnings
def lowercase ( _lowerCAmelCase , _lowerCAmelCase ):
UpperCAmelCase__ = set()
UpperCAmelCase__ = [os.path.join(_lowerCAmelCase , _lowerCAmelCase ) for p in os.listdir(_lowerCAmelCase ) if (p.endswith(""".zip""" ) or from_gh)]
for p in paths:
selected_warnings.update(extract_warnings_from_single_artifact(_lowerCAmelCase , _lowerCAmelCase ) )
return selected_warnings
if __name__ == "__main__":
def lowercase ( _lowerCAmelCase ):
return values.split(""",""" )
snake_case__ : List[str] = argparse.ArgumentParser()
# Required parameters
parser.add_argument('''--workflow_run_id''', type=str, required=True, help='''A GitHub Actions workflow run id.''')
parser.add_argument(
'''--output_dir''',
type=str,
required=True,
help='''Where to store the downloaded artifacts and other result files.''',
)
parser.add_argument('''--token''', default=None, type=str, help='''A token that has actions:read permission.''')
# optional parameters
parser.add_argument(
'''--targets''',
default='''DeprecationWarning,UserWarning,FutureWarning''',
type=list_str,
help='''Comma-separated list of target warning(s) which we want to extract.''',
)
parser.add_argument(
'''--from_gh''',
action='''store_true''',
help='''If running from a GitHub action workflow and collecting warnings from its artifacts.''',
)
snake_case__ : Union[str, Any] = parser.parse_args()
snake_case__ : Optional[int] = args.from_gh
if from_gh:
# The artifacts have to be downloaded using `actions/download-artifact@v3`
pass
else:
os.makedirs(args.output_dir, exist_ok=True)
# get download links
snake_case__ : Union[str, Any] = get_artifacts_links(args.workflow_run_id, token=args.token)
with open(os.path.join(args.output_dir, '''artifacts.json'''), '''w''', encoding='''UTF-8''') as fp:
json.dump(artifacts, fp, ensure_ascii=False, indent=4)
# download artifacts
for idx, (name, url) in enumerate(artifacts.items()):
print(name)
print(url)
print('''=''' * 8_0)
download_artifact(name, url, args.output_dir, args.token)
# Be gentle to GitHub
time.sleep(1)
# extract warnings from artifacts
snake_case__ : List[str] = extract_warnings(args.output_dir, args.targets)
snake_case__ : Optional[int] = sorted(selected_warnings)
with open(os.path.join(args.output_dir, '''selected_warnings.json'''), '''w''', encoding='''UTF-8''') as fp:
json.dump(selected_warnings, fp, ensure_ascii=False, indent=4)
| 392 |
import copy
import inspect
import unittest
import numpy as np
from huggingface_hub import hf_hub_download
from transformers import TimesformerConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import (
MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
TimesformerForVideoClassification,
TimesformerModel,
)
from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from transformers import VideoMAEImageProcessor
class snake_case :
'''simple docstring'''
def __init__( self : Union[str, Any] , lowerCamelCase_ : Any , lowerCamelCase_ : Union[str, Any]=13 , lowerCamelCase_ : List[Any]=10 , lowerCamelCase_ : Any=3 , lowerCamelCase_ : Tuple=2 , lowerCamelCase_ : int=2 , lowerCamelCase_ : List[Any]=True , lowerCamelCase_ : List[Any]=True , lowerCamelCase_ : str=32 , lowerCamelCase_ : Union[str, Any]=5 , lowerCamelCase_ : Any=4 , lowerCamelCase_ : int=37 , lowerCamelCase_ : Dict="gelu" , lowerCamelCase_ : Optional[int]=0.1 , lowerCamelCase_ : List[Any]=0.1 , lowerCamelCase_ : Optional[Any]=10 , lowerCamelCase_ : str=0.02 , lowerCamelCase_ : str="divided_space_time" , lowerCamelCase_ : Dict=None , ) ->Optional[int]:
'''simple docstring'''
UpperCAmelCase__ = parent
UpperCAmelCase__ = batch_size
UpperCAmelCase__ = image_size
UpperCAmelCase__ = num_channels
UpperCAmelCase__ = patch_size
UpperCAmelCase__ = num_frames
UpperCAmelCase__ = is_training
UpperCAmelCase__ = use_labels
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__ = attention_type
UpperCAmelCase__ = initializer_range
UpperCAmelCase__ = scope
UpperCAmelCase__ = num_labels
# in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token
UpperCAmelCase__ = (image_size // patch_size) ** 2
UpperCAmelCase__ = (num_frames) * self.num_patches_per_frame + 1
def UpperCAmelCase ( self : int ) ->Tuple:
'''simple docstring'''
UpperCAmelCase__ = floats_tensor(
[self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] )
UpperCAmelCase__ = None
if self.use_labels:
UpperCAmelCase__ = ids_tensor([self.batch_size] , self.num_labels )
UpperCAmelCase__ = self.get_config()
return config, pixel_values, labels
def UpperCAmelCase ( self : str ) ->List[Any]:
'''simple docstring'''
UpperCAmelCase__ = TimesformerConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , 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 , initializer_range=self.initializer_range , attention_type=self.attention_type , )
UpperCAmelCase__ = self.num_labels
return config
def UpperCAmelCase ( self : List[Any] , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : List[Any] , lowerCamelCase_ : int ) ->int:
'''simple docstring'''
UpperCAmelCase__ = TimesformerModel(config=lowerCamelCase_ )
model.to(lowerCamelCase_ )
model.eval()
UpperCAmelCase__ = model(lowerCamelCase_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def UpperCAmelCase ( self : Union[str, Any] , lowerCamelCase_ : List[Any] , lowerCamelCase_ : List[str] , lowerCamelCase_ : Union[str, Any] ) ->Tuple:
'''simple docstring'''
UpperCAmelCase__ = TimesformerForVideoClassification(lowerCamelCase_ )
model.to(lowerCamelCase_ )
model.eval()
UpperCAmelCase__ = model(lowerCamelCase_ )
# verify the logits shape
UpperCAmelCase__ = torch.Size((self.batch_size, self.num_labels) )
self.parent.assertEqual(result.logits.shape , lowerCamelCase_ )
def UpperCAmelCase ( self : str ) ->Any:
'''simple docstring'''
UpperCAmelCase__ = self.prepare_config_and_inputs()
UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = config_and_inputs
UpperCAmelCase__ = {"""pixel_values""": pixel_values}
return config, inputs_dict
@require_torch
class snake_case ( _snake_case , _snake_case , unittest.TestCase ):
'''simple docstring'''
UpperCamelCase__ : List[Any] = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
UpperCamelCase__ : Union[str, Any] = (
{"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification}
if is_torch_available()
else {}
)
UpperCamelCase__ : Union[str, Any] = False
UpperCamelCase__ : Tuple = False
UpperCamelCase__ : int = False
UpperCamelCase__ : List[Any] = False
def UpperCAmelCase ( self : int ) ->Dict:
'''simple docstring'''
UpperCAmelCase__ = TimesformerModelTester(self )
UpperCAmelCase__ = ConfigTester(
self , config_class=lowerCamelCase_ , has_text_modality=lowerCamelCase_ , hidden_size=37 )
def UpperCAmelCase ( self : Union[str, Any] , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : int , lowerCamelCase_ : Any=False ) ->int:
'''simple docstring'''
UpperCAmelCase__ = copy.deepcopy(lowerCamelCase_ )
if return_labels:
if model_class in get_values(lowerCamelCase_ ):
UpperCAmelCase__ = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=lowerCamelCase_ )
return inputs_dict
def UpperCAmelCase ( self : Optional[int] ) ->Any:
'''simple docstring'''
self.config_tester.run_common_tests()
@unittest.skip(reason="""TimeSformer does not use inputs_embeds""" )
def UpperCAmelCase ( self : str ) ->Any:
'''simple docstring'''
pass
def UpperCAmelCase ( self : Optional[Any] ) ->Any:
'''simple docstring'''
UpperCAmelCase__ , UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCAmelCase__ = model_class(lowerCamelCase_ )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
UpperCAmelCase__ = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(lowerCamelCase_ , nn.Linear ) )
def UpperCAmelCase ( self : Optional[int] ) ->Any:
'''simple docstring'''
UpperCAmelCase__ , UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCAmelCase__ = model_class(lowerCamelCase_ )
UpperCAmelCase__ = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
UpperCAmelCase__ = [*signature.parameters.keys()]
UpperCAmelCase__ = ["""pixel_values"""]
self.assertListEqual(arg_names[:1] , lowerCamelCase_ )
def UpperCAmelCase ( self : Tuple ) ->int:
'''simple docstring'''
UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCamelCase_ )
def UpperCAmelCase ( self : int ) ->Dict:
'''simple docstring'''
UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_video_classification(*lowerCamelCase_ )
@slow
def UpperCAmelCase ( self : Optional[int] ) ->Any:
'''simple docstring'''
for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
UpperCAmelCase__ = TimesformerModel.from_pretrained(lowerCamelCase_ )
self.assertIsNotNone(lowerCamelCase_ )
def UpperCAmelCase ( self : str ) ->Dict:
'''simple docstring'''
if not self.has_attentions:
pass
else:
UpperCAmelCase__ , UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common()
UpperCAmelCase__ = True
for model_class in self.all_model_classes:
UpperCAmelCase__ = self.model_tester.seq_length
UpperCAmelCase__ = self.model_tester.num_frames
UpperCAmelCase__ = True
UpperCAmelCase__ = False
UpperCAmelCase__ = True
UpperCAmelCase__ = model_class(lowerCamelCase_ )
model.to(lowerCamelCase_ )
model.eval()
with torch.no_grad():
UpperCAmelCase__ = model(**self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) )
UpperCAmelCase__ = outputs.attentions
self.assertEqual(len(lowerCamelCase_ ) , self.model_tester.num_hidden_layers )
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
UpperCAmelCase__ = True
UpperCAmelCase__ = model_class(lowerCamelCase_ )
model.to(lowerCamelCase_ )
model.eval()
with torch.no_grad():
UpperCAmelCase__ = model(**self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) )
UpperCAmelCase__ = outputs.attentions
self.assertEqual(len(lowerCamelCase_ ) , self.model_tester.num_hidden_layers )
# attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
self.assertListEqual(
list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , )
UpperCAmelCase__ = len(lowerCamelCase_ )
# Check attention is always last and order is fine
UpperCAmelCase__ = True
UpperCAmelCase__ = True
UpperCAmelCase__ = model_class(lowerCamelCase_ )
model.to(lowerCamelCase_ )
model.eval()
with torch.no_grad():
UpperCAmelCase__ = model(**self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) )
self.assertEqual(out_len + 1 , len(lowerCamelCase_ ) )
UpperCAmelCase__ = outputs.attentions
self.assertEqual(len(lowerCamelCase_ ) , self.model_tester.num_hidden_layers )
# attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
self.assertListEqual(
list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , )
def UpperCAmelCase ( self : List[str] ) ->int:
'''simple docstring'''
def check_hidden_states_output(lowerCamelCase_ : List[str] , lowerCamelCase_ : Any , lowerCamelCase_ : List[str] ):
UpperCAmelCase__ = model_class(lowerCamelCase_ )
model.to(lowerCamelCase_ )
model.eval()
with torch.no_grad():
UpperCAmelCase__ = model(**self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) )
UpperCAmelCase__ = outputs.hidden_states
UpperCAmelCase__ = self.model_tester.num_hidden_layers + 1
self.assertEqual(len(lowerCamelCase_ ) , lowerCamelCase_ )
UpperCAmelCase__ = self.model_tester.seq_length
self.assertListEqual(
list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , )
UpperCAmelCase__ , UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCAmelCase__ = True
check_hidden_states_output(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
UpperCAmelCase__ = True
check_hidden_states_output(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
def lowercase ( ):
UpperCAmelCase__ = hf_hub_download(
repo_id="""hf-internal-testing/spaghetti-video""" , filename="""eating_spaghetti.npy""" , repo_type="""dataset""" )
UpperCAmelCase__ = np.load(_lowerCAmelCase )
return list(_lowerCAmelCase )
@require_torch
@require_vision
class snake_case ( unittest.TestCase ):
'''simple docstring'''
@cached_property
def UpperCAmelCase ( self : int ) ->List[Any]:
'''simple docstring'''
return (
VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] )
if is_vision_available()
else None
)
@slow
def UpperCAmelCase ( self : int ) ->Any:
'''simple docstring'''
UpperCAmelCase__ = TimesformerForVideoClassification.from_pretrained("""facebook/timesformer-base-finetuned-k400""" ).to(
lowerCamelCase_ )
UpperCAmelCase__ = self.default_image_processor
UpperCAmelCase__ = prepare_video()
UpperCAmelCase__ = image_processor(video[:8] , return_tensors="""pt""" ).to(lowerCamelCase_ )
# forward pass
with torch.no_grad():
UpperCAmelCase__ = model(**lowerCamelCase_ )
# verify the logits
UpperCAmelCase__ = torch.Size((1, 400) )
self.assertEqual(outputs.logits.shape , lowerCamelCase_ )
UpperCAmelCase__ = torch.tensor([-0.3016, -0.7713, -0.4205] ).to(lowerCamelCase_ )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase_ , atol=1E-4 ) )
| 392 | 1 |
import gc
import random
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
import diffusers
from diffusers import (
AutoencoderKL,
EulerDiscreteScheduler,
StableDiffusionLatentUpscalePipeline,
StableDiffusionPipeline,
UNetaDConditionModel,
)
from diffusers.schedulers import KarrasDiffusionSchedulers
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin
enable_full_determinism()
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Union[str, Any] ) -> List[str]:
'''simple docstring'''
A__ = [tensor.shape for tensor in tensor_list]
return all(shape == shapes[0] for shape in shapes[1:] )
class a__ ( snake_case , snake_case , snake_case , unittest.TestCase ):
"""simple docstring"""
__lowerCamelCase = StableDiffusionLatentUpscalePipeline
__lowerCamelCase = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
'height',
'width',
'cross_attention_kwargs',
'negative_prompt_embeds',
'prompt_embeds',
}
__lowerCamelCase = PipelineTesterMixin.required_optional_params - {'num_images_per_prompt'}
__lowerCamelCase = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
__lowerCamelCase = frozenset(
[] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
__lowerCamelCase = frozenset([] )
__lowerCamelCase = True
@property
def UpperCamelCase ( self ) -> int:
'''simple docstring'''
A__ = 1
A__ = 4
A__ = (16, 16)
A__ = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(lowercase )
return image
def UpperCamelCase ( self ) -> str:
'''simple docstring'''
torch.manual_seed(0 )
A__ = UNetaDConditionModel(
act_fn="gelu" , attention_head_dim=8 , norm_num_groups=lowercase , block_out_channels=[32, 32, 64, 64] , time_cond_proj_dim=160 , conv_in_kernel=1 , conv_out_kernel=1 , cross_attention_dim=32 , down_block_types=(
"KDownBlock2D",
"KCrossAttnDownBlock2D",
"KCrossAttnDownBlock2D",
"KCrossAttnDownBlock2D",
) , in_channels=8 , mid_block_type=lowercase , only_cross_attention=lowercase , out_channels=5 , resnet_time_scale_shift="scale_shift" , time_embedding_type="fourier" , timestep_post_act="gelu" , up_block_types=("KCrossAttnUpBlock2D", "KCrossAttnUpBlock2D", "KCrossAttnUpBlock2D", "KUpBlock2D") , )
A__ = AutoencoderKL(
block_out_channels=[32, 32, 64, 64] , in_channels=3 , out_channels=3 , down_block_types=[
"DownEncoderBlock2D",
"DownEncoderBlock2D",
"DownEncoderBlock2D",
"DownEncoderBlock2D",
] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , )
A__ = EulerDiscreteScheduler(prediction_type="sample" )
A__ = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="quick_gelu" , projection_dim=512 , )
A__ = CLIPTextModel(lowercase )
A__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )
A__ = {
"unet": model.eval(),
"vae": vae.eval(),
"scheduler": scheduler,
"text_encoder": text_encoder,
"tokenizer": tokenizer,
}
return components
def UpperCamelCase ( self , lowercase , lowercase=0 ) -> Optional[Any]:
'''simple docstring'''
if str(lowercase ).startswith("mps" ):
A__ = torch.manual_seed(lowercase )
else:
A__ = torch.Generator(device=lowercase ).manual_seed(lowercase )
A__ = {
"prompt": "A painting of a squirrel eating a burger",
"image": self.dummy_image.cpu(),
"generator": generator,
"num_inference_steps": 2,
"output_type": "numpy",
}
return inputs
def UpperCamelCase ( self ) -> List[Any]:
'''simple docstring'''
A__ = "cpu"
A__ = self.get_dummy_components()
A__ = self.pipeline_class(**lowercase )
pipe.to(lowercase )
pipe.set_progress_bar_config(disable=lowercase )
A__ = self.get_dummy_inputs(lowercase )
A__ = pipe(**lowercase ).images
A__ = image[0, -3:, -3:, -1]
self.assertEqual(image.shape , (1, 256, 256, 3) )
A__ = np.array(
[0.4722_2412, 0.4192_1633, 0.4471_7434, 0.4687_4192, 0.4258_8258, 0.4615_0726, 0.467_7534, 0.4558_3832, 0.4857_9055] )
A__ = np.abs(image_slice.flatten() - expected_slice ).max()
self.assertLessEqual(lowercase , 1e-3 )
def UpperCamelCase ( self ) -> str:
'''simple docstring'''
super().test_attention_slicing_forward_pass(expected_max_diff=7e-3 )
def UpperCamelCase ( self ) -> Optional[Any]:
'''simple docstring'''
super().test_cpu_offload_forward_pass(expected_max_diff=3e-3 )
def UpperCamelCase ( self ) -> List[str]:
'''simple docstring'''
super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 )
def UpperCamelCase ( self ) -> Union[str, Any]:
'''simple docstring'''
super().test_inference_batch_single_identical(expected_max_diff=7e-3 )
def UpperCamelCase ( self ) -> str:
'''simple docstring'''
super().test_pt_np_pil_outputs_equivalent(expected_max_diff=3e-3 )
def UpperCamelCase ( self ) -> List[Any]:
'''simple docstring'''
super().test_save_load_local(expected_max_difference=3e-3 )
def UpperCamelCase ( self ) -> Optional[Any]:
'''simple docstring'''
super().test_save_load_optional_components(expected_max_difference=3e-3 )
def UpperCamelCase ( self ) -> List[str]:
'''simple docstring'''
A__ = [
"DDIMScheduler",
"DDPMScheduler",
"PNDMScheduler",
"HeunDiscreteScheduler",
"EulerAncestralDiscreteScheduler",
"KDPM2DiscreteScheduler",
"KDPM2AncestralDiscreteScheduler",
"DPMSolverSDEScheduler",
]
A__ = self.get_dummy_components()
A__ = self.pipeline_class(**lowercase )
# make sure that PNDM does not need warm-up
pipe.scheduler.register_to_config(skip_prk_steps=lowercase )
pipe.to(lowercase )
pipe.set_progress_bar_config(disable=lowercase )
A__ = self.get_dummy_inputs(lowercase )
A__ = 2
A__ = []
for scheduler_enum in KarrasDiffusionSchedulers:
if scheduler_enum.name in skip_schedulers:
# no sigma schedulers are not supported
# no schedulers
continue
A__ = getattr(lowercase , scheduler_enum.name )
A__ = scheduler_cls.from_config(pipe.scheduler.config )
A__ = pipe(**lowercase )[0]
outputs.append(lowercase )
assert check_same_shape(lowercase )
@require_torch_gpu
@slow
class a__ ( unittest.TestCase ):
"""simple docstring"""
def UpperCamelCase ( self ) -> List[str]:
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCamelCase ( self ) -> Tuple:
'''simple docstring'''
A__ = torch.manual_seed(33 )
A__ = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4" , torch_dtype=torch.floataa )
pipe.to("cuda" )
A__ = StableDiffusionLatentUpscalePipeline.from_pretrained(
"stabilityai/sd-x2-latent-upscaler" , torch_dtype=torch.floataa )
upscaler.to("cuda" )
A__ = "a photo of an astronaut high resolution, unreal engine, ultra realistic"
A__ = pipe(lowercase , generator=lowercase , output_type="latent" ).images
A__ = upscaler(
prompt=lowercase , image=lowercase , num_inference_steps=20 , guidance_scale=0 , generator=lowercase , output_type="np" , ).images[0]
A__ = load_numpy(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/astronaut_1024.npy" )
assert np.abs((expected_image - image).mean() ) < 5e-2
def UpperCamelCase ( self ) -> Tuple:
'''simple docstring'''
A__ = torch.manual_seed(33 )
A__ = StableDiffusionLatentUpscalePipeline.from_pretrained(
"stabilityai/sd-x2-latent-upscaler" , torch_dtype=torch.floataa )
upscaler.to("cuda" )
A__ = "the temple of fire by Ross Tran and Gerardo Dottori, oil on canvas"
A__ = load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_512.png" )
A__ = upscaler(
prompt=lowercase , image=lowercase , num_inference_steps=20 , guidance_scale=0 , generator=lowercase , output_type="np" , ).images[0]
A__ = load_numpy(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_1024.npy" )
assert np.abs((expected_image - image).max() ) < 5e-2
| 626 |
import gc
import unittest
import numpy as np
import torch
from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel
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 UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS, UNCONDITIONAL_AUDIO_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
class a__ ( snake_case , unittest.TestCase ):
"""simple docstring"""
__lowerCamelCase = DanceDiffusionPipeline
__lowerCamelCase = UNCONDITIONAL_AUDIO_GENERATION_PARAMS
__lowerCamelCase = PipelineTesterMixin.required_optional_params - {
'callback',
'latents',
'callback_steps',
'output_type',
'num_images_per_prompt',
}
__lowerCamelCase = UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS
__lowerCamelCase = False
__lowerCamelCase = False
def UpperCamelCase ( self ) -> Optional[int]:
'''simple docstring'''
torch.manual_seed(0 )
A__ = UNetaDModel(
block_out_channels=(32, 32, 64) , extra_in_channels=16 , sample_size=512 , sample_rate=16000 , in_channels=2 , out_channels=2 , flip_sin_to_cos=lowercase , use_timestep_embedding=lowercase , time_embedding_type="fourier" , mid_block_type="UNetMidBlock1D" , down_block_types=("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") , up_block_types=("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") , )
A__ = IPNDMScheduler()
A__ = {
"unet": unet,
"scheduler": scheduler,
}
return components
def UpperCamelCase ( self , lowercase , lowercase=0 ) -> Union[str, Any]:
'''simple docstring'''
if str(lowercase ).startswith("mps" ):
A__ = torch.manual_seed(lowercase )
else:
A__ = torch.Generator(device=lowercase ).manual_seed(lowercase )
A__ = {
"batch_size": 1,
"generator": generator,
"num_inference_steps": 4,
}
return inputs
def UpperCamelCase ( self ) -> Any:
'''simple docstring'''
A__ = "cpu" # ensure determinism for the device-dependent torch.Generator
A__ = self.get_dummy_components()
A__ = DanceDiffusionPipeline(**lowercase )
A__ = pipe.to(lowercase )
pipe.set_progress_bar_config(disable=lowercase )
A__ = self.get_dummy_inputs(lowercase )
A__ = pipe(**lowercase )
A__ = output.audios
A__ = audio[0, -3:, -3:]
assert audio.shape == (1, 2, components["unet"].sample_size)
A__ = np.array([-0.7265, 1.0000, -0.8388, 0.1175, 0.9498, -1.0000] )
assert np.abs(audio_slice.flatten() - expected_slice ).max() < 1e-2
@skip_mps
def UpperCamelCase ( self ) -> Dict:
'''simple docstring'''
return super().test_save_load_local()
@skip_mps
def UpperCamelCase ( self ) -> int:
'''simple docstring'''
return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 )
@skip_mps
def UpperCamelCase ( self ) -> Optional[Any]:
'''simple docstring'''
return super().test_save_load_optional_components()
@skip_mps
def UpperCamelCase ( self ) -> int:
'''simple docstring'''
return super().test_attention_slicing_forward_pass()
def UpperCamelCase ( self ) -> str:
'''simple docstring'''
super().test_inference_batch_single_identical(expected_max_diff=3e-3 )
@slow
@require_torch_gpu
class a__ ( unittest.TestCase ):
"""simple docstring"""
def UpperCamelCase ( self ) -> int:
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCamelCase ( self ) -> int:
'''simple docstring'''
A__ = torch_device
A__ = DanceDiffusionPipeline.from_pretrained("harmonai/maestro-150k" )
A__ = pipe.to(lowercase )
pipe.set_progress_bar_config(disable=lowercase )
A__ = torch.manual_seed(0 )
A__ = pipe(generator=lowercase , num_inference_steps=100 , audio_length_in_s=4.096 )
A__ = output.audios
A__ = audio[0, -3:, -3:]
assert audio.shape == (1, 2, pipe.unet.sample_size)
A__ = np.array([-0.0192, -0.0231, -0.0318, -0.0059, 0.0002, -0.0020] )
assert np.abs(audio_slice.flatten() - expected_slice ).max() < 1e-2
def UpperCamelCase ( self ) -> List[Any]:
'''simple docstring'''
A__ = torch_device
A__ = DanceDiffusionPipeline.from_pretrained("harmonai/maestro-150k" , torch_dtype=torch.floataa )
A__ = pipe.to(lowercase )
pipe.set_progress_bar_config(disable=lowercase )
A__ = torch.manual_seed(0 )
A__ = pipe(generator=lowercase , num_inference_steps=100 , audio_length_in_s=4.096 )
A__ = output.audios
A__ = audio[0, -3:, -3:]
assert audio.shape == (1, 2, pipe.unet.sample_size)
A__ = np.array([-0.0367, -0.0488, -0.0771, -0.0525, -0.0444, -0.0341] )
assert np.abs(audio_slice.flatten() - expected_slice ).max() < 1e-2
| 626 | 1 |
"""simple docstring"""
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
__A : List[str] = logging.get_logger(__name__)
__A : int = {
"sail/poolformer_s12": "https://huggingface.co/sail/poolformer_s12/resolve/main/config.json",
# See all PoolFormer models at https://huggingface.co/models?filter=poolformer
}
class _a ( lowerCAmelCase):
"""simple docstring"""
UpperCamelCase__ = """poolformer"""
def __init__( self : Union[str, Any] , __UpperCamelCase : int=3 , __UpperCamelCase : Optional[Any]=1_6 , __UpperCamelCase : Any=1_6 , __UpperCamelCase : Union[str, Any]=3 , __UpperCamelCase : Tuple=4.0 , __UpperCamelCase : Any=[2, 2, 6, 2] , __UpperCamelCase : Optional[Any]=[6_4, 1_2_8, 3_2_0, 5_1_2] , __UpperCamelCase : Optional[int]=[7, 3, 3, 3] , __UpperCamelCase : Tuple=[4, 2, 2, 2] , __UpperCamelCase : List[Any]=[2, 1, 1, 1] , __UpperCamelCase : List[Any]=4 , __UpperCamelCase : Dict=0.0 , __UpperCamelCase : Union[str, Any]="gelu" , __UpperCamelCase : Optional[Any]=True , __UpperCamelCase : List[Any]=1e-5 , __UpperCamelCase : Tuple=0.0_2 , **__UpperCamelCase : int , )->Optional[Any]:
_UpperCAmelCase = num_channels
_UpperCAmelCase = patch_size
_UpperCAmelCase = stride
_UpperCAmelCase = padding
_UpperCAmelCase = pool_size
_UpperCAmelCase = hidden_sizes
_UpperCAmelCase = mlp_ratio
_UpperCAmelCase = depths
_UpperCAmelCase = patch_sizes
_UpperCAmelCase = strides
_UpperCAmelCase = num_encoder_blocks
_UpperCAmelCase = drop_path_rate
_UpperCAmelCase = hidden_act
_UpperCAmelCase = use_layer_scale
_UpperCAmelCase = layer_scale_init_value
_UpperCAmelCase = initializer_range
super().__init__(**__UpperCamelCase )
class _a ( lowerCAmelCase):
"""simple docstring"""
UpperCamelCase__ = version.parse("""1.11""")
@property
def lowercase__ ( self : Dict )->Mapping[str, Mapping[int, str]]:
return OrderedDict(
[
('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
] )
@property
def lowercase__ ( self : Dict )->float:
return 2e-3
| 602 |
"""simple docstring"""
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
__A : Tuple = logging.get_logger(__name__)
__A : List[Any] = {"vocab_file": "spm_char.model"}
__A : Optional[Any] = {
"vocab_file": {
"microsoft/speecht5_asr": "https://huggingface.co/microsoft/speecht5_asr/resolve/main/spm_char.model",
"microsoft/speecht5_tts": "https://huggingface.co/microsoft/speecht5_tts/resolve/main/spm_char.model",
"microsoft/speecht5_vc": "https://huggingface.co/microsoft/speecht5_vc/resolve/main/spm_char.model",
}
}
__A : Any = {
"microsoft/speecht5_asr": 1024,
"microsoft/speecht5_tts": 1024,
"microsoft/speecht5_vc": 1024,
}
class _a ( lowerCAmelCase):
"""simple docstring"""
UpperCamelCase__ = VOCAB_FILES_NAMES
UpperCamelCase__ = PRETRAINED_VOCAB_FILES_MAP
UpperCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
UpperCamelCase__ = ["""input_ids""", """attention_mask"""]
def __init__( self : Union[str, Any] , __UpperCamelCase : Optional[Any] , __UpperCamelCase : Any="<s>" , __UpperCamelCase : List[str]="</s>" , __UpperCamelCase : Dict="<unk>" , __UpperCamelCase : Union[str, Any]="<pad>" , __UpperCamelCase : Optional[Dict[str, Any]] = None , **__UpperCamelCase : Union[str, Any] , )->None:
_UpperCAmelCase = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
bos_token=__UpperCamelCase , eos_token=__UpperCamelCase , unk_token=__UpperCamelCase , pad_token=__UpperCamelCase , sp_model_kwargs=self.sp_model_kwargs , **__UpperCamelCase , )
_UpperCAmelCase = vocab_file
_UpperCAmelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(__UpperCamelCase )
@property
def lowercase__ ( self : Any )->Optional[int]:
return self.sp_model.get_piece_size()
def lowercase__ ( self : Dict )->int:
_UpperCAmelCase = {self.convert_ids_to_tokens(__UpperCamelCase ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self : Optional[Any] )->Dict:
_UpperCAmelCase = self.__dict__.copy()
_UpperCAmelCase = None
return state
def __setstate__( self : str , __UpperCamelCase : Optional[Any] )->List[Any]:
_UpperCAmelCase = d
# for backward compatibility
if not hasattr(self , '''sp_model_kwargs''' ):
_UpperCAmelCase = {}
_UpperCAmelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def lowercase__ ( self : Optional[int] , __UpperCamelCase : str )->List[str]:
return self.sp_model.encode(__UpperCamelCase , out_type=__UpperCamelCase )
def lowercase__ ( self : Optional[int] , __UpperCamelCase : Dict )->Any:
return self.sp_model.piece_to_id(__UpperCamelCase )
def lowercase__ ( self : List[str] , __UpperCamelCase : Tuple )->Optional[int]:
_UpperCAmelCase = self.sp_model.IdToPiece(__UpperCamelCase )
return token
def lowercase__ ( self : Union[str, Any] , __UpperCamelCase : Any )->Any:
_UpperCAmelCase = []
_UpperCAmelCase = ''''''
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
out_string += self.sp_model.decode(__UpperCamelCase ) + token
_UpperCAmelCase = []
else:
current_sub_tokens.append(__UpperCamelCase )
out_string += self.sp_model.decode(__UpperCamelCase )
return out_string.strip()
def lowercase__ ( self : Any , __UpperCamelCase : Optional[Any] , __UpperCamelCase : Optional[int]=None )->List[int]:
if token_ids_a is None:
return token_ids_a + [self.eos_token_id]
# We don't expect to process pairs, but leave the pair logic for API consistency
return token_ids_a + token_ids_a + [self.eos_token_id]
def lowercase__ ( self : str , __UpperCamelCase : List[int] , __UpperCamelCase : Optional[List[int]] = None , __UpperCamelCase : bool = False )->List[int]:
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=__UpperCamelCase , token_ids_a=__UpperCamelCase , already_has_special_tokens=__UpperCamelCase )
_UpperCAmelCase = [1]
if token_ids_a is None:
return ([0] * len(__UpperCamelCase )) + suffix_ones
return ([0] * len(__UpperCamelCase )) + ([0] * len(__UpperCamelCase )) + suffix_ones
def lowercase__ ( self : Dict , __UpperCamelCase : str , __UpperCamelCase : Optional[str] = None )->Tuple[str]:
if not os.path.isdir(__UpperCamelCase ):
logger.error(F'Vocabulary path ({save_directory}) should be a directory' )
return
_UpperCAmelCase = os.path.join(
__UpperCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCamelCase ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , __UpperCamelCase )
elif not os.path.isfile(self.vocab_file ):
with open(__UpperCamelCase , '''wb''' ) as fi:
_UpperCAmelCase = self.sp_model.serialized_model_proto()
fi.write(__UpperCamelCase )
return (out_vocab_file,)
| 602 | 1 |
'''simple docstring'''
from typing import List, Optional, Tuple, Union
import torch
from ...schedulers import DDIMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class _a ( __a ):
"""simple docstring"""
def __init__( self : Optional[int] , lowercase_ : Tuple , lowercase_ : Tuple ):
'''simple docstring'''
super().__init__()
# make sure scheduler can always be converted to DDIM
lowercase_ = DDIMScheduler.from_config(scheduler.config )
self.register_modules(unet=lowercase_ , scheduler=lowercase_ )
@torch.no_grad()
def __call__( self : Dict , lowercase_ : int = 1 , lowercase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowercase_ : float = 0.0 , lowercase_ : int = 50 , lowercase_ : Optional[bool] = None , lowercase_ : Optional[str] = "pil" , lowercase_ : bool = True , ):
'''simple docstring'''
if isinstance(self.unet.config.sample_size , lowercase_ ):
lowercase_ = (
batch_size,
self.unet.config.in_channels,
self.unet.config.sample_size,
self.unet.config.sample_size,
)
else:
lowercase_ = (batch_size, self.unet.config.in_channels, *self.unet.config.sample_size)
if isinstance(lowercase_ , lowercase_ ) and len(lowercase_ ) != batch_size:
raise ValueError(
F"""You have passed a list of generators of length {len(lowercase_ )}, but requested an effective batch"""
F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" )
lowercase_ = randn_tensor(lowercase_ , generator=lowercase_ , device=self.device , dtype=self.unet.dtype )
# set step values
self.scheduler.set_timesteps(lowercase_ )
for t in self.progress_bar(self.scheduler.timesteps ):
# 1. predict noise model_output
lowercase_ = self.unet(lowercase_ , lowercase_ ).sample
# 2. predict previous mean of image x_t-1 and add variance depending on eta
# eta corresponds to η in paper and should be between [0, 1]
# do x_t -> x_t-1
lowercase_ = self.scheduler.step(
lowercase_ , lowercase_ , lowercase_ , eta=lowercase_ , use_clipped_model_output=lowercase_ , generator=lowercase_ ).prev_sample
lowercase_ = (image / 2 + 0.5).clamp(0 , 1 )
lowercase_ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
lowercase_ = self.numpy_to_pil(lowercase_ )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=lowercase_ )
| 719 | '''simple docstring'''
from typing import List, Optional, Tuple, Union
import torch
from ...schedulers import DDIMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class _a ( __a ):
"""simple docstring"""
def __init__( self : Optional[int] , lowercase_ : Tuple , lowercase_ : Tuple ):
'''simple docstring'''
super().__init__()
# make sure scheduler can always be converted to DDIM
lowercase_ = DDIMScheduler.from_config(scheduler.config )
self.register_modules(unet=lowercase_ , scheduler=lowercase_ )
@torch.no_grad()
def __call__( self : Dict , lowercase_ : int = 1 , lowercase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowercase_ : float = 0.0 , lowercase_ : int = 50 , lowercase_ : Optional[bool] = None , lowercase_ : Optional[str] = "pil" , lowercase_ : bool = True , ):
'''simple docstring'''
if isinstance(self.unet.config.sample_size , lowercase_ ):
lowercase_ = (
batch_size,
self.unet.config.in_channels,
self.unet.config.sample_size,
self.unet.config.sample_size,
)
else:
lowercase_ = (batch_size, self.unet.config.in_channels, *self.unet.config.sample_size)
if isinstance(lowercase_ , lowercase_ ) and len(lowercase_ ) != batch_size:
raise ValueError(
F"""You have passed a list of generators of length {len(lowercase_ )}, but requested an effective batch"""
F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" )
lowercase_ = randn_tensor(lowercase_ , generator=lowercase_ , device=self.device , dtype=self.unet.dtype )
# set step values
self.scheduler.set_timesteps(lowercase_ )
for t in self.progress_bar(self.scheduler.timesteps ):
# 1. predict noise model_output
lowercase_ = self.unet(lowercase_ , lowercase_ ).sample
# 2. predict previous mean of image x_t-1 and add variance depending on eta
# eta corresponds to η in paper and should be between [0, 1]
# do x_t -> x_t-1
lowercase_ = self.scheduler.step(
lowercase_ , lowercase_ , lowercase_ , eta=lowercase_ , use_clipped_model_output=lowercase_ , generator=lowercase_ ).prev_sample
lowercase_ = (image / 2 + 0.5).clamp(0 , 1 )
lowercase_ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
lowercase_ = self.numpy_to_pil(lowercase_ )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=lowercase_ )
| 603 | 0 |
import numpy as np
UpperCAmelCase__ : Tuple = [
["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 :
def __init__( self) -> None:
__snake_case = np.array(lowercase_)
def _a ( self , lowercase_) -> np.ndarray:
__snake_case , __snake_case = np.where(letter == self.SQUARE)
__snake_case = np.concatenate([indexa + 1, indexa + 1])
return indexes
def _a ( self , lowercase_ , lowercase_) -> str:
__snake_case = self.SQUARE[indexa - 1, indexa - 1]
return letter
def _a ( self , lowercase_) -> str:
__snake_case = message.lower()
__snake_case = message.replace(' ' , '')
__snake_case = message.replace('j' , 'i')
__snake_case = np.empty((2, len(lowercase_)))
for letter_index in range(len(lowercase_)):
__snake_case = self.letter_to_numbers(message[letter_index])
__snake_case = numbers[0]
__snake_case = numbers[1]
__snake_case = first_step.reshape(2 * len(lowercase_))
__snake_case = ''
for numbers_index in range(len(lowercase_)):
__snake_case = int(second_step[numbers_index * 2])
__snake_case = int(second_step[(numbers_index * 2) + 1])
__snake_case = self.numbers_to_letter(lowercase_ , lowercase_)
__snake_case = encoded_message + letter
return encoded_message
def _a ( self , lowercase_) -> str:
__snake_case = message.lower()
message.replace(' ' , '')
__snake_case = np.empty(2 * len(lowercase_))
for letter_index in range(len(lowercase_)):
__snake_case = self.letter_to_numbers(message[letter_index])
__snake_case = numbers[0]
__snake_case = numbers[1]
__snake_case = first_step.reshape((2, len(lowercase_)))
__snake_case = ''
for numbers_index in range(len(lowercase_)):
__snake_case = int(second_step[0, numbers_index])
__snake_case = int(second_step[1, numbers_index])
__snake_case = self.numbers_to_letter(lowercase_ , lowercase_)
__snake_case = decoded_message + letter
return decoded_message
| 313 |
def A ( snake_case__ : str ) -> list:
'''simple docstring'''
if n_term == "":
return []
__snake_case = []
for temp in range(int(snake_case__ ) ):
series.append(f"1/{temp + 1}" if series else '1' )
return series
if __name__ == "__main__":
UpperCAmelCase__ : List[Any] = input("Enter the last number (nth term) of the Harmonic Series")
print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n")
print(harmonic_series(nth_term))
| 313 | 1 |
# NOTE: This file is deprecated and will be removed in a future version.
# It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works
from ...utils import deprecate
from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401
from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401
deprecate(
"stable diffusion controlnet",
"0.22.0",
"Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.",
standard_warn=False,
stacklevel=3,
)
| 704 | from collections import Counter
from pathlib import Path
from typing import Optional, Tuple
import yaml
class lowerCamelCase (yaml.SafeLoader ):
"""simple docstring"""
def __A ( self : str , __magic_name__ : str ) -> str:
SCREAMING_SNAKE_CASE_ = [self.constructed_objects[key_node] for key_node, _ in node.value]
SCREAMING_SNAKE_CASE_ = [tuple(__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else key for key in keys]
SCREAMING_SNAKE_CASE_ = Counter(__magic_name__ )
SCREAMING_SNAKE_CASE_ = [key for key in counter if counter[key] > 1]
if duplicate_keys:
raise TypeError(F'''Got duplicate yaml keys: {duplicate_keys}''' )
def __A ( self : int , __magic_name__ : int , __magic_name__ : List[str]=False ) -> Optional[Any]:
SCREAMING_SNAKE_CASE_ = super().construct_mapping(__magic_name__ , deep=__magic_name__ )
self._check_no_duplicates_on_constructed_node(__magic_name__ )
return mapping
def a__ ( __UpperCamelCase ):
SCREAMING_SNAKE_CASE_ = list(readme_content.splitlines() )
if full_content and full_content[0] == "---" and "---" in full_content[1:]:
SCREAMING_SNAKE_CASE_ = full_content[1:].index("---" ) + 1
SCREAMING_SNAKE_CASE_ = "\n".join(full_content[1:sep_idx] )
return yamlblock, "\n".join(full_content[sep_idx + 1 :] )
return None, "\n".join(__UpperCamelCase )
class lowerCamelCase (SCREAMING_SNAKE_CASE__ ):
"""simple docstring"""
lowerCamelCase__ = {'''train_eval_index'''} # train-eval-index in the YAML metadata
@classmethod
def __A ( cls : Dict , __magic_name__ : Path ) -> "DatasetMetadata":
with open(__magic_name__ , encoding="utf-8" ) as readme_file:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = _split_yaml_from_readme(readme_file.read() )
if yaml_string is not None:
return cls.from_yaml_string(__magic_name__ )
else:
return cls()
def __A ( self : str , __magic_name__ : Path ) -> List[str]:
if path.exists():
with open(__magic_name__ , encoding="utf-8" ) as readme_file:
SCREAMING_SNAKE_CASE_ = readme_file.read()
else:
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = self._to_readme(__magic_name__ )
with open(__magic_name__ , "w" , encoding="utf-8" ) as readme_file:
readme_file.write(__magic_name__ )
def __A ( self : Any , __magic_name__ : Optional[str] = None ) -> str:
if readme_content is not None:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = _split_yaml_from_readme(__magic_name__ )
SCREAMING_SNAKE_CASE_ = "---\n" + self.to_yaml_string() + "---\n" + content
else:
SCREAMING_SNAKE_CASE_ = "---\n" + self.to_yaml_string() + "---\n"
return full_content
@classmethod
def __A ( cls : List[Any] , __magic_name__ : str ) -> "DatasetMetadata":
SCREAMING_SNAKE_CASE_ = yaml.load(__magic_name__ , Loader=_NoDuplicateSafeLoader ) or {}
# Convert the YAML keys to DatasetMetadata fields
SCREAMING_SNAKE_CASE_ = {
(key.replace("-" , "_" ) if key.replace("-" , "_" ) in cls._FIELDS_WITH_DASHES else key): value
for key, value in metadata_dict.items()
}
return cls(**__magic_name__ )
def __A ( self : Optional[Any] ) -> str:
return yaml.safe_dump(
{
(key.replace("_" , "-" ) if key in self._FIELDS_WITH_DASHES else key): value
for key, value in self.items()
} , sort_keys=__magic_name__ , allow_unicode=__magic_name__ , encoding="utf-8" , ).decode("utf-8" )
A : 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
A : Optional[Any] = ArgumentParser(usage="Validate the yaml metadata block of a README.md file.")
ap.add_argument("readme_filepath")
A : Union[str, Any] = ap.parse_args()
A : Union[str, Any] = Path(args.readme_filepath)
A : List[Any] = DatasetMetadata.from_readme(readme_filepath)
print(dataset_metadata)
dataset_metadata.to_readme(readme_filepath)
| 356 | 0 |
from typing import Any
class A_ :
'''simple docstring'''
def __init__(self , lowercase__ ) -> List[str]:
__UpperCAmelCase = data
__UpperCAmelCase = None
def __repr__(self ) -> str:
return F'''Node({self.data})'''
class A_ :
'''simple docstring'''
def __init__(self ) -> Union[str, Any]:
__UpperCAmelCase = None
def __iter__(self ) -> Any:
__UpperCAmelCase = self.head
while node:
yield node.data
__UpperCAmelCase = node.next
def __len__(self ) -> int:
return sum(1 for _ in self )
def __repr__(self ) -> str:
return "->".join([str(lowercase__ ) for item in self] )
def __getitem__(self , lowercase__ ) -> Any:
if not 0 <= index < len(self ):
raise ValueError('''list index out of range.''' )
for i, node in enumerate(self ):
if i == index:
return node
return None
def __setitem__(self , lowercase__ , lowercase__ ) -> None:
if not 0 <= index < len(self ):
raise ValueError('''list index out of range.''' )
__UpperCAmelCase = self.head
for _ in range(lowercase__ ):
__UpperCAmelCase = current.next
__UpperCAmelCase = data
def lowerCAmelCase_ (self , lowercase__ ) -> None:
self.insert_nth(len(self ) , lowercase__ )
def lowerCAmelCase_ (self , lowercase__ ) -> None:
self.insert_nth(0 , lowercase__ )
def lowerCAmelCase_ (self , lowercase__ , lowercase__ ) -> None:
if not 0 <= index <= len(self ):
raise IndexError('''list index out of range''' )
__UpperCAmelCase = Node(lowercase__ )
if self.head is None:
__UpperCAmelCase = new_node
elif index == 0:
__UpperCAmelCase = self.head # link new_node to head
__UpperCAmelCase = new_node
else:
__UpperCAmelCase = self.head
for _ in range(index - 1 ):
__UpperCAmelCase = temp.next
__UpperCAmelCase = temp.next
__UpperCAmelCase = new_node
def lowerCAmelCase_ (self ) -> None: # print every node data
print(self )
def lowerCAmelCase_ (self ) -> Any:
return self.delete_nth(0 )
def lowerCAmelCase_ (self ) -> Any: # delete from tail
return self.delete_nth(len(self ) - 1 )
def lowerCAmelCase_ (self , lowercase__ = 0 ) -> Any:
if not 0 <= index <= len(self ) - 1: # test if index is valid
raise IndexError('''List index out of range.''' )
__UpperCAmelCase = self.head # default first node
if index == 0:
__UpperCAmelCase = self.head.next
else:
__UpperCAmelCase = self.head
for _ in range(index - 1 ):
__UpperCAmelCase = temp.next
__UpperCAmelCase = temp.next
__UpperCAmelCase = temp.next.next
return delete_node.data
def lowerCAmelCase_ (self ) -> bool:
return self.head is None
def lowerCAmelCase_ (self ) -> None:
__UpperCAmelCase = None
__UpperCAmelCase = self.head
while current:
# Store the current node's next node.
__UpperCAmelCase = current.next
# Make the current node's next point backwards
__UpperCAmelCase = prev
# Make the previous node be the current node
__UpperCAmelCase = current
# Make the current node the next node (to progress iteration)
__UpperCAmelCase = next_node
# Return prev in order to put the head at the end
__UpperCAmelCase = prev
def __a ( ) -> None:
'''simple docstring'''
__UpperCAmelCase = LinkedList()
assert linked_list.is_empty() is True
assert str(SCREAMING_SNAKE_CASE ) == ""
try:
linked_list.delete_head()
raise AssertionError # This should not happen.
except IndexError:
assert True # This should happen.
try:
linked_list.delete_tail()
raise AssertionError # This should not happen.
except IndexError:
assert True # This should happen.
for i in range(1_0 ):
assert len(SCREAMING_SNAKE_CASE ) == i
linked_list.insert_nth(SCREAMING_SNAKE_CASE , i + 1 )
assert str(SCREAMING_SNAKE_CASE ) == "->".join(str(SCREAMING_SNAKE_CASE ) for i in range(1 , 1_1 ) )
linked_list.insert_head(0 )
linked_list.insert_tail(1_1 )
assert str(SCREAMING_SNAKE_CASE ) == "->".join(str(SCREAMING_SNAKE_CASE ) for i in range(0 , 1_2 ) )
assert linked_list.delete_head() == 0
assert linked_list.delete_nth(9 ) == 1_0
assert linked_list.delete_tail() == 1_1
assert len(SCREAMING_SNAKE_CASE ) == 9
assert str(SCREAMING_SNAKE_CASE ) == "->".join(str(SCREAMING_SNAKE_CASE ) for i in range(1 , 1_0 ) )
assert all(linked_list[i] == i + 1 for i in range(0 , 9 ) ) is True
for i in range(0 , 9 ):
__UpperCAmelCase = -i
assert all(linked_list[i] == -i for i in range(0 , 9 ) ) is True
linked_list.reverse()
assert str(SCREAMING_SNAKE_CASE ) == "->".join(str(SCREAMING_SNAKE_CASE ) for i in range(-8 , 1 ) )
def __a ( ) -> None:
'''simple docstring'''
__UpperCAmelCase = [
-9,
1_0_0,
Node(7_7_3_4_5_1_1_2 ),
'''dlrow olleH''',
7,
5_5_5_5,
0,
-192.55555,
'''Hello, world!''',
77.9,
Node(1_0 ),
None,
None,
12.20,
]
__UpperCAmelCase = LinkedList()
for i in test_input:
linked_list.insert_tail(SCREAMING_SNAKE_CASE )
# Check if it's empty or not
assert linked_list.is_empty() is False
assert (
str(SCREAMING_SNAKE_CASE ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->"
"-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2"
)
# Delete the head
__UpperCAmelCase = linked_list.delete_head()
assert result == -9
assert (
str(SCREAMING_SNAKE_CASE ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None->None->12.2"
)
# Delete the tail
__UpperCAmelCase = linked_list.delete_tail()
assert result == 12.2
assert (
str(SCREAMING_SNAKE_CASE ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None->None"
)
# Delete a node in specific location in linked list
__UpperCAmelCase = linked_list.delete_nth(1_0 )
assert result is None
assert (
str(SCREAMING_SNAKE_CASE ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None"
)
# Add a Node instance to its head
linked_list.insert_head(Node('''Hello again, world!''' ) )
assert (
str(SCREAMING_SNAKE_CASE )
== "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->"
"7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None"
)
# Add None to its tail
linked_list.insert_tail(SCREAMING_SNAKE_CASE )
assert (
str(SCREAMING_SNAKE_CASE )
== "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->"
"7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None"
)
# Reverse the linked list
linked_list.reverse()
assert (
str(SCREAMING_SNAKE_CASE )
== "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->"
"7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)"
)
def __a ( ) -> Any:
'''simple docstring'''
from doctest import testmod
testmod()
__UpperCAmelCase = LinkedList()
linked_list.insert_head(input('''Inserting 1st at head ''' ).strip() )
linked_list.insert_head(input('''Inserting 2nd at head ''' ).strip() )
print('''\nPrint list:''' )
linked_list.print_list()
linked_list.insert_tail(input('''\nInserting 1st at tail ''' ).strip() )
linked_list.insert_tail(input('''Inserting 2nd at tail ''' ).strip() )
print('''\nPrint list:''' )
linked_list.print_list()
print('''\nDelete head''' )
linked_list.delete_head()
print('''Delete tail''' )
linked_list.delete_tail()
print('''\nPrint list:''' )
linked_list.print_list()
print('''\nReverse linked list''' )
linked_list.reverse()
print('''\nPrint list:''' )
linked_list.print_list()
print('''\nString representation of linked list:''' )
print(SCREAMING_SNAKE_CASE )
print('''\nReading/changing Node data using indexing:''' )
print(f'''Element at Position 1: {linked_list[1]}''' )
__UpperCAmelCase = input('''Enter New Value: ''' ).strip()
print('''New list:''' )
print(SCREAMING_SNAKE_CASE )
print(f'''length of linked_list is : {len(SCREAMING_SNAKE_CASE )}''' )
if __name__ == "__main__":
main()
| 303 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
A_ : List[Any] = logging.get_logger(__name__)
A_ : Optional[Any] = {
'google/switch-base-8': 'https://huggingface.co/google/switch-base-8/blob/main/config.json',
}
class A_ ( _a ):
'''simple docstring'''
a__ = "switch_transformers"
a__ = ["past_key_values"]
a__ = {"hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"}
def __init__(self , lowercase__=32_128 , lowercase__=768 , lowercase__=64 , lowercase__=2_048 , lowercase__=64 , lowercase__=12 , lowercase__=3 , lowercase__=12 , lowercase__=3 , lowercase__=12 , lowercase__=8 , lowercase__=False , lowercase__=0.01 , lowercase__="float32" , lowercase__=False , lowercase__=32 , lowercase__=128 , lowercase__=0.1 , lowercase__=1E-6 , lowercase__=0.001 , lowercase__=0.001 , lowercase__=1.0 , lowercase__="relu" , lowercase__=True , lowercase__=False , lowercase__=True , lowercase__=0 , lowercase__=1 , **lowercase__ , ) -> Dict:
__UpperCAmelCase = vocab_size
__UpperCAmelCase = d_model
__UpperCAmelCase = d_kv
__UpperCAmelCase = d_ff
__UpperCAmelCase = num_sparse_encoder_layers
__UpperCAmelCase = num_layers
__UpperCAmelCase = (
num_decoder_layers if num_decoder_layers is not None else self.num_layers
) # default = symmetry
__UpperCAmelCase = num_sparse_decoder_layers
# This tells us, each how many encoder layer we'll have to set a sparse layer.
if self.num_sparse_encoder_layers > 0:
__UpperCAmelCase = self.num_layers // self.num_sparse_encoder_layers
else:
__UpperCAmelCase = self.num_layers # HACK: this will create 0 sparse layers
# This tells us, each how many encoder layer we'll have to set a sparse layer.
if self.num_sparse_decoder_layers > 0:
__UpperCAmelCase = self.num_decoder_layers // self.num_sparse_decoder_layers
else:
__UpperCAmelCase = self.num_decoder_layers # HACK: this will create 0 sparse layers
__UpperCAmelCase = num_heads
__UpperCAmelCase = num_experts
__UpperCAmelCase = expert_capacity
__UpperCAmelCase = router_bias
__UpperCAmelCase = router_jitter_noise
if router_dtype not in ["float32", "float16", "bfloat16"]:
raise ValueError(F'''`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}''' )
__UpperCAmelCase = router_dtype
__UpperCAmelCase = router_ignore_padding_tokens
__UpperCAmelCase = relative_attention_num_buckets
__UpperCAmelCase = relative_attention_max_distance
__UpperCAmelCase = dropout_rate
__UpperCAmelCase = layer_norm_epsilon
__UpperCAmelCase = initializer_factor
__UpperCAmelCase = feed_forward_proj
__UpperCAmelCase = use_cache
__UpperCAmelCase = add_router_probs
__UpperCAmelCase = router_z_loss_coef
__UpperCAmelCase = router_aux_loss_coef
__UpperCAmelCase = self.feed_forward_proj.split('''-''' )
__UpperCAmelCase = act_info[-1]
__UpperCAmelCase = act_info[0] == '''gated'''
if len(lowercase__ ) > 1 and act_info[0] != "gated" or len(lowercase__ ) > 2:
raise ValueError(
F'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.'''
'''Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. '''
'''\'gated-gelu\' or \'relu\'''' )
# for backwards compatibility
if feed_forward_proj == "gated-gelu":
__UpperCAmelCase = '''gelu_new'''
super().__init__(
pad_token_id=lowercase__ , eos_token_id=lowercase__ , is_encoder_decoder=lowercase__ , **lowercase__ , )
| 303 | 1 |
'''simple docstring'''
from __future__ import annotations
def _a ( SCREAMING_SNAKE_CASE__ : list[int] ) -> list[int]: # This function is recursive
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Optional[Any] = len(SCREAMING_SNAKE_CASE__ )
# If the array contains only one element, we return it (it's the stop condition of
# recursion)
if array_length <= 1:
return array
# Else
SCREAMING_SNAKE_CASE__ : Dict = array[0]
SCREAMING_SNAKE_CASE__ : int = False
SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1
SCREAMING_SNAKE_CASE__ : list[int] = []
while not is_found and i < array_length:
if array[i] < pivot:
SCREAMING_SNAKE_CASE__ : int = True
SCREAMING_SNAKE_CASE__ : Optional[int] = [element for element in array[i:] if element >= array[i]]
SCREAMING_SNAKE_CASE__ : Tuple = longest_subsequence(SCREAMING_SNAKE_CASE__ )
if len(SCREAMING_SNAKE_CASE__ ) > len(SCREAMING_SNAKE_CASE__ ):
SCREAMING_SNAKE_CASE__ : int = temp_array
else:
i += 1
SCREAMING_SNAKE_CASE__ : int = [element for element in array[1:] if element >= pivot]
SCREAMING_SNAKE_CASE__ : int = [pivot, *longest_subsequence(SCREAMING_SNAKE_CASE__ )]
if len(SCREAMING_SNAKE_CASE__ ) > len(SCREAMING_SNAKE_CASE__ ):
return temp_array
else:
return longest_subseq
if __name__ == "__main__":
import doctest
doctest.testmod()
| 701 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
_lowerCamelCase : Union[str, Any] = {
'''configuration_x_clip''': [
'''XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''XCLIPConfig''',
'''XCLIPTextConfig''',
'''XCLIPVisionConfig''',
],
'''processing_x_clip''': ['''XCLIPProcessor'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase : str = [
'''XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''XCLIPModel''',
'''XCLIPPreTrainedModel''',
'''XCLIPTextModel''',
'''XCLIPVisionModel''',
]
if TYPE_CHECKING:
from .configuration_x_clip import (
XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
XCLIPConfig,
XCLIPTextConfig,
XCLIPVisionConfig,
)
from .processing_x_clip import XCLIPProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_x_clip import (
XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
XCLIPModel,
XCLIPPreTrainedModel,
XCLIPTextModel,
XCLIPVisionModel,
)
else:
import sys
_lowerCamelCase : Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 157 | 0 |
'''simple docstring'''
import json
import re
from typing import TYPE_CHECKING, List, Optional, Tuple, Union
import numpy as np
from ...utils import is_tf_available, is_torch_available, logging
if TYPE_CHECKING:
if is_torch_available():
import torch
if is_tf_available():
import tensorflow as tf
from tokenizers import pre_tokenizers
from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from .tokenization_codegen import CodeGenTokenizer
__lowerCamelCase : Optional[int] = logging.get_logger(__name__)
__lowerCamelCase : Dict = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
__lowerCamelCase : Dict = {
"vocab_file": {
"Salesforce/codegen-350M-mono": "https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json",
},
"merges_file": {
"Salesforce/codegen-350M-mono": "https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt",
},
"tokenizer_file": {
"Salesforce/codegen-350M-mono": (
"https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/tokenizer.json"
),
},
}
__lowerCamelCase : int = {
"Salesforce/codegen-350M-mono": 2048,
}
class UpperCAmelCase ( _lowercase ):
UpperCAmelCase : Dict = VOCAB_FILES_NAMES
UpperCAmelCase : Tuple = PRETRAINED_VOCAB_FILES_MAP
UpperCAmelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
UpperCAmelCase : Any = ['''input_ids''', '''attention_mask''']
UpperCAmelCase : Optional[Any] = CodeGenTokenizer
def __init__(self : Union[str, Any] , A__ : Optional[Any]=None , A__ : Union[str, Any]=None , A__ : List[Any]=None , A__ : Union[str, Any]="<|endoftext|>" , A__ : int="<|endoftext|>" , A__ : Tuple="<|endoftext|>" , A__ : int=False , **A__ : Tuple , ) -> Union[str, Any]:
super().__init__(
A__ , A__ , tokenizer_file=A__ , unk_token=A__ , bos_token=A__ , eos_token=A__ , add_prefix_space=A__ , **A__ , )
if kwargs.pop("add_bos_token" , A__ ):
lowercase = kwargs.pop("name_or_path" , "" )
raise ValueError(
"Currenty GPT2's fast tokenizer does NOT support adding a BOS token."
"Instead you should use GPT2's slow tokenizer class `CodeGenTokenizer` as follows: \n"
f'`CodeGenTokenizer.from_pretrained(\'{model_id}\')`\nor\n'
f'`AutoTokenizer.from_pretrained(\'{model_id}\', use_fast=False)`\n'
"This issue will be fixed soon, see: https://github.com/huggingface/tokenizers/pull/1005."
" so that the fast tokenizer works correctly." )
lowercase = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
if pre_tok_state.get("add_prefix_space" , A__ ) != add_prefix_space:
lowercase = getattr(A__ , pre_tok_state.pop("type" ) )
lowercase = add_prefix_space
lowercase = pre_tok_class(**A__ )
lowercase = add_prefix_space
def UpperCAmelCase__ (self : Optional[int] , *A__ : Optional[int] , **A__ : int ) -> BatchEncoding:
lowercase = 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 UpperCAmelCase__ (self : Union[str, Any] , *A__ : Any , **A__ : Dict ) -> BatchEncoding:
lowercase = 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 UpperCAmelCase__ (self : Union[str, Any] , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]:
lowercase = self._tokenizer.model.save(A__ , name=A__ )
return tuple(A__ )
def UpperCAmelCase__ (self : Tuple , A__ : Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"] , A__ : bool = False , A__ : bool = None , A__ : Optional[List[str]] = None , **A__ : Optional[Any] , ) -> str:
lowercase = super().decode(
token_ids=A__ , skip_special_tokens=A__ , clean_up_tokenization_spaces=A__ , **A__ , )
if truncate_before_pattern is not None and len(A__ ) > 0:
lowercase = self.truncate(A__ , A__ )
return decoded_text
def UpperCAmelCase__ (self : List[str] , A__ : Optional[Any] , A__ : Union[str, Any] ) -> Any:
def find_re(A__ : int , A__ : Optional[int] , A__ : Tuple ):
lowercase = pattern.search(A__ , A__ )
return m.start() if m else -1
lowercase = [re.compile(A__ , re.MULTILINE ) for pattern in truncate_before_pattern]
lowercase = list(re.finditer("^print" , A__ , re.MULTILINE ) )
if len(A__ ) > 1:
lowercase = completion[: prints[1].start()]
lowercase = list(re.finditer("^def" , A__ , re.MULTILINE ) )
if len(A__ ) > 1:
lowercase = completion[: defs[1].start()]
lowercase = 0
lowercase = [
pos for pos in [find_re(A__ , A__ , A__ ) for terminal in terminals] if pos != -1
]
if len(A__ ) > 0:
return completion[: min(A__ )]
else:
return completion
| 310 |
'''simple docstring'''
import gzip
import hashlib
import json
import multiprocessing
import os
import re
import shutil
import time
from pathlib import Path
import numpy as np
from arguments import PreprocessingArguments
from datasets import load_dataset
from minhash_deduplication import deduplicate_dataset
from transformers import AutoTokenizer, HfArgumentParser
__lowerCamelCase : Optional[int] = re.compile(r"\s+")
def UpperCAmelCase_ ( lowerCAmelCase_ ):
"""simple docstring"""
return {"hash": hashlib.mda(re.sub(lowerCAmelCase_ , "" , example["content"] ).encode("utf-8" ) ).hexdigest()}
def UpperCAmelCase_ ( lowerCAmelCase_ ):
"""simple docstring"""
lowercase = [len(lowerCAmelCase_ ) for line in example["content"].splitlines()]
return {"line_mean": np.mean(lowerCAmelCase_ ), "line_max": max(lowerCAmelCase_ )}
def UpperCAmelCase_ ( lowerCAmelCase_ ):
"""simple docstring"""
lowercase = np.mean([c.isalnum() for c in example["content"]] )
return {"alpha_frac": alpha_frac}
def UpperCAmelCase_ ( lowerCAmelCase_ , lowerCAmelCase_ ):
"""simple docstring"""
if example["hash"] in uniques:
uniques.remove(example["hash"] )
return True
else:
return False
def UpperCAmelCase_ ( lowerCAmelCase_ , lowerCAmelCase_=5 ):
"""simple docstring"""
lowercase = ["auto-generated", "autogenerated", "automatically generated"]
lowercase = example["content"].splitlines()
for _, line in zip(range(lowerCAmelCase_ ) , lowerCAmelCase_ ):
for keyword in keywords:
if keyword in line.lower():
return {"autogenerated": True}
else:
return {"autogenerated": False}
def UpperCAmelCase_ ( lowerCAmelCase_ , lowerCAmelCase_=5 , lowerCAmelCase_=0.05 ):
"""simple docstring"""
lowercase = ["unit tests", "test file", "configuration file"]
lowercase = example["content"].splitlines()
lowercase = 0
lowercase = 0
# first test
for _, line in zip(range(lowerCAmelCase_ ) , lowerCAmelCase_ ):
for keyword in keywords:
if keyword in line.lower():
return {"config_or_test": True}
# second test
lowercase = example["content"].count("\n" )
lowercase = int(coeff * nlines )
for line in lines:
count_config += line.lower().count("config" )
count_test += line.lower().count("test" )
if count_config > threshold or count_test > threshold:
return {"config_or_test": True}
return {"config_or_test": False}
def UpperCAmelCase_ ( lowerCAmelCase_ ):
"""simple docstring"""
lowercase = ["def ", "class ", "for ", "while "]
lowercase = example["content"].splitlines()
for line in lines:
for keyword in keywords:
if keyword in line.lower():
return {"has_no_keywords": False}
return {"has_no_keywords": True}
def UpperCAmelCase_ ( lowerCAmelCase_ , lowerCAmelCase_=4 ):
"""simple docstring"""
lowercase = example["content"].splitlines()
lowercase = 0
for line in lines:
counter += line.lower().count("=" )
if counter > minimum:
return {"has_few_assignments": False}
return {"has_few_assignments": True}
def UpperCAmelCase_ ( lowerCAmelCase_ ):
"""simple docstring"""
lowercase = tokenizer(example["content"] , truncation=lowerCAmelCase_ )["input_ids"]
lowercase = len(example["content"] ) / len(lowerCAmelCase_ )
return {"ratio": ratio}
def UpperCAmelCase_ ( lowerCAmelCase_ ):
"""simple docstring"""
lowercase = {}
results.update(get_hash(lowerCAmelCase_ ) )
results.update(line_stats(lowerCAmelCase_ ) )
results.update(alpha_stats(lowerCAmelCase_ ) )
results.update(char_token_ratio(lowerCAmelCase_ ) )
results.update(is_autogenerated(lowerCAmelCase_ ) )
results.update(is_config_or_test(lowerCAmelCase_ ) )
results.update(has_no_keywords(lowerCAmelCase_ ) )
results.update(has_few_assignments(lowerCAmelCase_ ) )
return results
def UpperCAmelCase_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ):
"""simple docstring"""
if not check_uniques(lowerCAmelCase_ , lowerCAmelCase_ ):
return False
elif example["autogenerated"]:
return False
elif example["line_max"] > args.line_max:
return False
elif example["line_mean"] > args.line_mean:
return False
elif example["alpha_frac"] < args.alpha_frac:
return False
elif example["ratio"] < args.min_token_ratio:
return False
elif example["config_or_test"] and np.random.rand() <= args.filter_proba:
return False
elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba:
return False
elif example["has_few_assignments"]:
return False
else:
return True
def UpperCAmelCase_ ( lowerCAmelCase_ ):
"""simple docstring"""
with open(lowerCAmelCase_ , "rb" ) as f_in:
with gzip.open(str(lowerCAmelCase_ ) + ".gz" , "wb" , compresslevel=6 ) as f_out:
shutil.copyfileobj(lowerCAmelCase_ , lowerCAmelCase_ )
os.unlink(lowerCAmelCase_ )
# Settings
__lowerCamelCase : Tuple = HfArgumentParser(PreprocessingArguments)
__lowerCamelCase : Dict = parser.parse_args()
if args.num_workers is None:
__lowerCamelCase : List[str] = multiprocessing.cpu_count()
__lowerCamelCase : Tuple = AutoTokenizer.from_pretrained(args.tokenizer_dir)
# Load dataset
__lowerCamelCase : Tuple = time.time()
__lowerCamelCase : List[Any] = load_dataset(args.dataset_name, split="train")
print(f"Time to load dataset: {time.time()-t_start:.2f}")
# Run preprocessing
__lowerCamelCase : Optional[Any] = time.time()
__lowerCamelCase : Union[str, Any] = ds.map(preprocess, num_proc=args.num_workers)
print(f"Time to preprocess dataset: {time.time()-t_start:.2f}")
# Deduplicate hashes
__lowerCamelCase : Any = set(ds.unique("hash"))
__lowerCamelCase : str = len(uniques) / len(ds)
print(f"Fraction of duplicates: {1-frac:.2%}")
# Deduplicate data and apply heuristics
__lowerCamelCase : Optional[int] = time.time()
__lowerCamelCase : int = ds.filter(filter, fn_kwargs={"uniques": uniques, "args": args})
print(f"Time to filter dataset: {time.time()-t_start:.2f}")
print(f"Size of filtered dataset: {len(ds_filter)}")
# Deduplicate with minhash and jaccard similarity
if args.near_deduplication:
__lowerCamelCase : List[str] = time.time()
__lowerCamelCase , __lowerCamelCase : List[str] = deduplicate_dataset(ds_filter, args.jaccard_threshold)
print(f"Time to deduplicate dataset: {time.time()-t_start:.2f}")
print(f"Size of deduplicate dataset: {len(ds_filter)}")
# Save data in batches of samples_per_file
__lowerCamelCase : int = Path(args.output_dir)
output_dir.mkdir(exist_ok=True)
# save duplicate_clusters in the output_dir as artifacts
# not sure it is the right place the save it
if args.near_deduplication:
with open(output_dir / "duplicate_clusters.json", "w") as f:
json.dump(duplicate_clusters, f)
__lowerCamelCase : Tuple = output_dir / "data"
data_dir.mkdir(exist_ok=True)
__lowerCamelCase : Union[str, Any] = time.time()
for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)):
__lowerCamelCase : Optional[int] = str(data_dir / f"file-{file_number+1:012}.json")
__lowerCamelCase : str = min(len(ds_filter), index + args.samples_per_file)
ds_filter.select(list(range(index, end_index))).to_json(file_path)
compress_file(file_path)
print(f"Time to save dataset: {time.time()-t_start:.2f}")
| 310 | 1 |
import unittest
from diffusers import FlaxAutoencoderKL
from diffusers.utils import is_flax_available
from diffusers.utils.testing_utils import require_flax
from .test_modeling_common_flax import FlaxModelTesterMixin
if is_flax_available():
import jax
@require_flax
class lowerCamelCase__( __lowerCamelCase , unittest.TestCase):
UpperCAmelCase__ : Optional[int] = FlaxAutoencoderKL
@property
def lowerCAmelCase__ ( self: Tuple ):
__lowerCamelCase = 4
__lowerCamelCase = 3
__lowerCamelCase = (32, 32)
__lowerCamelCase = jax.random.PRNGKey(0 )
__lowerCamelCase = jax.random.uniform(UpperCamelCase_ , ((batch_size, num_channels) + sizes) )
return {"sample": image, "prng_key": prng_key}
def lowerCAmelCase__ ( self: Dict ):
__lowerCamelCase = {
"""block_out_channels""": [32, 64],
"""in_channels""": 3,
"""out_channels""": 3,
"""down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""],
"""up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""],
"""latent_channels""": 4,
}
__lowerCamelCase = self.dummy_input
return init_dict, inputs_dict
| 702 |
import math
def lowerCamelCase__ ( A__ : int ):
'''simple docstring'''
__lowerCamelCase = []
__lowerCamelCase = 2
__lowerCamelCase = int(math.sqrt(A__ ) ) # Size of every segment
__lowerCamelCase = [True] * (end + 1)
__lowerCamelCase = []
while start <= end:
if temp[start] is True:
in_prime.append(A__ )
for i in range(start * start , end + 1 , A__ ):
__lowerCamelCase = False
start += 1
prime += in_prime
__lowerCamelCase = end + 1
__lowerCamelCase = min(2 * end , A__ )
while low <= n:
__lowerCamelCase = [True] * (high - low + 1)
for each in in_prime:
__lowerCamelCase = math.floor(low / each ) * each
if t < low:
t += each
for j in range(A__ , high + 1 , A__ ):
__lowerCamelCase = False
for j in range(len(A__ ) ):
if temp[j] is True:
prime.append(j + low )
__lowerCamelCase = high + 1
__lowerCamelCase = min(high + end , A__ )
return prime
print(sieve(10**6))
| 80 | 0 |
'''simple docstring'''
import argparse
from pathlib import Path
import requests
import torch
from PIL import Image
from transformers import (
RobertaTokenizer,
TrOCRConfig,
TrOCRForCausalLM,
TrOCRProcessor,
VisionEncoderDecoderModel,
ViTConfig,
ViTImageProcessor,
ViTModel,
)
from transformers.utils import logging
logging.set_verbosity_info()
a = logging.get_logger(__name__)
def __magic_name__ ( __UpperCAmelCase , __UpperCAmelCase ) -> Tuple:
'''simple docstring'''
__SCREAMING_SNAKE_CASE = []
for i in range(encoder_config.num_hidden_layers ):
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
rename_keys.append(
(f"""encoder.deit.blocks.{i}.norm1.weight""", f"""encoder.encoder.layer.{i}.layernorm_before.weight""") )
rename_keys.append((f"""encoder.deit.blocks.{i}.norm1.bias""", f"""encoder.encoder.layer.{i}.layernorm_before.bias""") )
rename_keys.append(
(f"""encoder.deit.blocks.{i}.attn.proj.weight""", f"""encoder.encoder.layer.{i}.attention.output.dense.weight""") )
rename_keys.append(
(f"""encoder.deit.blocks.{i}.attn.proj.bias""", f"""encoder.encoder.layer.{i}.attention.output.dense.bias""") )
rename_keys.append(
(f"""encoder.deit.blocks.{i}.norm2.weight""", f"""encoder.encoder.layer.{i}.layernorm_after.weight""") )
rename_keys.append((f"""encoder.deit.blocks.{i}.norm2.bias""", f"""encoder.encoder.layer.{i}.layernorm_after.bias""") )
rename_keys.append(
(f"""encoder.deit.blocks.{i}.mlp.fc1.weight""", f"""encoder.encoder.layer.{i}.intermediate.dense.weight""") )
rename_keys.append(
(f"""encoder.deit.blocks.{i}.mlp.fc1.bias""", f"""encoder.encoder.layer.{i}.intermediate.dense.bias""") )
rename_keys.append(
(f"""encoder.deit.blocks.{i}.mlp.fc2.weight""", f"""encoder.encoder.layer.{i}.output.dense.weight""") )
rename_keys.append((f"""encoder.deit.blocks.{i}.mlp.fc2.bias""", f"""encoder.encoder.layer.{i}.output.dense.bias""") )
# cls token, position embeddings and patch embeddings of encoder
rename_keys.extend(
[
("""encoder.deit.cls_token""", """encoder.embeddings.cls_token"""),
("""encoder.deit.pos_embed""", """encoder.embeddings.position_embeddings"""),
("""encoder.deit.patch_embed.proj.weight""", """encoder.embeddings.patch_embeddings.projection.weight"""),
("""encoder.deit.patch_embed.proj.bias""", """encoder.embeddings.patch_embeddings.projection.bias"""),
("""encoder.deit.norm.weight""", """encoder.layernorm.weight"""),
("""encoder.deit.norm.bias""", """encoder.layernorm.bias"""),
] )
return rename_keys
def __magic_name__ ( __UpperCAmelCase , __UpperCAmelCase ) -> Tuple:
'''simple docstring'''
for i in range(encoder_config.num_hidden_layers ):
# queries, keys and values (only weights, no biases)
__SCREAMING_SNAKE_CASE = state_dict.pop(f"""encoder.deit.blocks.{i}.attn.qkv.weight""" )
__SCREAMING_SNAKE_CASE = in_proj_weight[
: encoder_config.hidden_size, :
]
__SCREAMING_SNAKE_CASE = in_proj_weight[
encoder_config.hidden_size : encoder_config.hidden_size * 2, :
]
__SCREAMING_SNAKE_CASE = in_proj_weight[
-encoder_config.hidden_size :, :
]
def __magic_name__ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]:
'''simple docstring'''
__SCREAMING_SNAKE_CASE = dct.pop(__UpperCAmelCase )
__SCREAMING_SNAKE_CASE = val
def __magic_name__ ( __UpperCAmelCase ) -> List[Any]:
'''simple docstring'''
if "handwritten" in checkpoint_url:
__SCREAMING_SNAKE_CASE = """https://fki.tic.heia-fr.ch/static/img/a01-122-02-00.jpg""" # industry
# url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-12.jpg" # have
# url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-10.jpg" # let
# url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg" #
# url = "https://fki.tic.heia-fr.ch/static/img/a01-122.jpg"
elif "printed" in checkpoint_url or "stage1" in checkpoint_url:
__SCREAMING_SNAKE_CASE = """https://www.researchgate.net/profile/Dinh-Sang/publication/338099565/figure/fig8/AS:840413229350922@1577381536857/An-receipt-example-in-the-SROIE-2019-dataset_Q640.jpg"""
__SCREAMING_SNAKE_CASE = Image.open(requests.get(__UpperCAmelCase , stream=__UpperCAmelCase ).raw ).convert("""RGB""" )
return im
@torch.no_grad()
def __magic_name__ ( __UpperCAmelCase , __UpperCAmelCase ) -> int:
'''simple docstring'''
__SCREAMING_SNAKE_CASE = ViTConfig(image_size=384 , qkv_bias=__UpperCAmelCase )
__SCREAMING_SNAKE_CASE = TrOCRConfig()
# size of the architecture
if "base" in checkpoint_url:
__SCREAMING_SNAKE_CASE = 768
elif "large" in checkpoint_url:
# use ViT-large encoder
__SCREAMING_SNAKE_CASE = 1024
__SCREAMING_SNAKE_CASE = 4096
__SCREAMING_SNAKE_CASE = 24
__SCREAMING_SNAKE_CASE = 16
__SCREAMING_SNAKE_CASE = 1024
else:
raise ValueError("""Should either find 'base' or 'large' in checkpoint URL""" )
# the large-printed + stage1 checkpoints uses sinusoidal position embeddings, no layernorm afterwards
if "large-printed" in checkpoint_url or "stage1" in checkpoint_url:
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = """relu"""
__SCREAMING_SNAKE_CASE = 1024
__SCREAMING_SNAKE_CASE = True
__SCREAMING_SNAKE_CASE = False
__SCREAMING_SNAKE_CASE = False
# load HuggingFace model
__SCREAMING_SNAKE_CASE = ViTModel(__UpperCAmelCase , add_pooling_layer=__UpperCAmelCase )
__SCREAMING_SNAKE_CASE = TrOCRForCausalLM(__UpperCAmelCase )
__SCREAMING_SNAKE_CASE = VisionEncoderDecoderModel(encoder=__UpperCAmelCase , decoder=__UpperCAmelCase )
model.eval()
# load state_dict of original model, rename some keys
__SCREAMING_SNAKE_CASE = torch.hub.load_state_dict_from_url(__UpperCAmelCase , map_location="""cpu""" , check_hash=__UpperCAmelCase )["""model"""]
__SCREAMING_SNAKE_CASE = create_rename_keys(__UpperCAmelCase , __UpperCAmelCase )
for src, dest in rename_keys:
rename_key(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
read_in_q_k_v(__UpperCAmelCase , __UpperCAmelCase )
# remove parameters we don't need
del state_dict["encoder.deit.head.weight"]
del state_dict["encoder.deit.head.bias"]
del state_dict["decoder.version"]
# add prefix to decoder keys
for key, val in state_dict.copy().items():
__SCREAMING_SNAKE_CASE = state_dict.pop(__UpperCAmelCase )
if key.startswith("""decoder""" ) and "output_projection" not in key:
__SCREAMING_SNAKE_CASE = val
else:
__SCREAMING_SNAKE_CASE = val
# load state dict
model.load_state_dict(__UpperCAmelCase )
# Check outputs on an image
__SCREAMING_SNAKE_CASE = ViTImageProcessor(size=encoder_config.image_size )
__SCREAMING_SNAKE_CASE = RobertaTokenizer.from_pretrained("""roberta-large""" )
__SCREAMING_SNAKE_CASE = TrOCRProcessor(__UpperCAmelCase , __UpperCAmelCase )
__SCREAMING_SNAKE_CASE = processor(images=prepare_img(__UpperCAmelCase ) , return_tensors="""pt""" ).pixel_values
# verify logits
__SCREAMING_SNAKE_CASE = torch.tensor([[model.config.decoder.decoder_start_token_id]] )
__SCREAMING_SNAKE_CASE = model(pixel_values=__UpperCAmelCase , decoder_input_ids=__UpperCAmelCase )
__SCREAMING_SNAKE_CASE = outputs.logits
__SCREAMING_SNAKE_CASE = torch.Size([1, 1, 50265] )
if "trocr-base-handwritten" in checkpoint_url:
__SCREAMING_SNAKE_CASE = torch.tensor(
[-1.4_5_0_2, -4.6_6_8_3, -0.5_3_4_7, -2.9_2_9_1, 9.1_4_3_5, -3.0_5_7_1, 8.9_7_6_4, 1.7_5_6_0, 8.7_3_5_8, -1.5_3_1_1] )
elif "trocr-large-handwritten" in checkpoint_url:
__SCREAMING_SNAKE_CASE = torch.tensor(
[-2.6_4_3_7, -1.3_1_2_9, -2.2_5_9_6, -5.3_4_5_5, 6.3_5_3_9, 1.7_6_0_4, 5.4_9_9_1, 1.4_7_0_2, 5.6_1_1_3, 2.0_1_7_0] )
elif "trocr-base-printed" in checkpoint_url:
__SCREAMING_SNAKE_CASE = torch.tensor(
[-5.6_8_1_6, -5.8_3_8_8, 1.1_3_9_8, -6.9_0_3_4, 6.8_5_0_5, -2.4_3_9_3, 1.2_2_8_4, -1.0_2_3_2, -1.9_6_6_1, -3.9_2_1_0] )
elif "trocr-large-printed" in checkpoint_url:
__SCREAMING_SNAKE_CASE = torch.tensor(
[-6.0_1_6_2, -7.0_9_5_9, 4.4_1_5_5, -5.1_0_6_3, 7.0_4_6_8, -3.1_6_3_1, 2.6_4_6_6, -0.3_0_8_1, -0.8_1_0_6, -1.7_5_3_5] )
if "stage1" not in checkpoint_url:
assert logits.shape == expected_shape, "Shape of logits not as expected"
assert torch.allclose(logits[0, 0, :10] , __UpperCAmelCase , atol=1e-3 ), "First elements of logits not as expected"
Path(__UpperCAmelCase ).mkdir(exist_ok=__UpperCAmelCase )
print(f"""Saving model to {pytorch_dump_folder_path}""" )
model.save_pretrained(__UpperCAmelCase )
print(f"""Saving processor to {pytorch_dump_folder_path}""" )
processor.save_pretrained(__UpperCAmelCase )
if __name__ == "__main__":
a = argparse.ArgumentParser()
parser.add_argument(
"--checkpoint_url",
default="https://layoutlm.blob.core.windows.net/trocr/model_zoo/fairseq/trocr-base-handwritten.pt",
type=str,
help="URL to the original PyTorch checkpoint (.pth file).",
)
parser.add_argument(
"--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model."
)
a = parser.parse_args()
convert_tr_ocr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
| 109 |
'''simple docstring'''
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
a = {
"gwf-440k": {
"url": "https://model-server.zqevans2.workers.dev/gwf-440k.ckpt",
"sample_rate": 48000,
"sample_size": 65536,
},
"jmann-small-190k": {
"url": "https://model-server.zqevans2.workers.dev/jmann-small-190k.ckpt",
"sample_rate": 48000,
"sample_size": 65536,
},
"jmann-large-580k": {
"url": "https://model-server.zqevans2.workers.dev/jmann-large-580k.ckpt",
"sample_rate": 48000,
"sample_size": 131072,
},
"maestro-uncond-150k": {
"url": "https://model-server.zqevans2.workers.dev/maestro-uncond-150k.ckpt",
"sample_rate": 16000,
"sample_size": 65536,
},
"unlocked-uncond-250k": {
"url": "https://model-server.zqevans2.workers.dev/unlocked-uncond-250k.ckpt",
"sample_rate": 16000,
"sample_size": 65536,
},
"honk-140k": {
"url": "https://model-server.zqevans2.workers.dev/honk-140k.ckpt",
"sample_rate": 16000,
"sample_size": 65536,
},
}
def __magic_name__ ( __UpperCAmelCase , __UpperCAmelCase ) -> Union[str, Any]:
'''simple docstring'''
return torch.atana(__UpperCAmelCase , __UpperCAmelCase ) / math.pi * 2
def __magic_name__ ( __UpperCAmelCase ) -> Optional[int]:
'''simple docstring'''
__SCREAMING_SNAKE_CASE = torch.sin(t * math.pi / 2 ) ** 2
__SCREAMING_SNAKE_CASE = (1 - sigma**2) ** 0.5
return alpha_sigma_to_t(__UpperCAmelCase , __UpperCAmelCase )
class __a ( _snake_case ):
pass
class __a ( nn.Module ):
def __init__( self : Union[str, Any] ,lowerCamelCase : Union[str, Any] ):
'''simple docstring'''
super().__init__()
__SCREAMING_SNAKE_CASE = DiffusionAttnUnetaD(lowerCamelCase ,n_attn_layers=4 )
__SCREAMING_SNAKE_CASE = deepcopy(self.diffusion )
__SCREAMING_SNAKE_CASE = torch.quasirandom.SobolEngine(1 ,scramble=lowerCamelCase )
def __magic_name__ ( __UpperCAmelCase ) -> List[str]:
'''simple docstring'''
__SCREAMING_SNAKE_CASE = MODELS_MAP[model_name]["""url"""]
os.system(f"""wget {url} ./""" )
return f"""./{model_name}.ckpt"""
a = {
"1": "resnets.0",
"2": "attentions.0",
"3": "resnets.1",
"4": "attentions.1",
"5": "resnets.2",
"6": "attentions.2",
}
a = {
"8": "resnets.0",
"9": "attentions.0",
"10": "resnets.1",
"11": "attentions.1",
"12": "resnets.2",
"13": "attentions.2",
}
a = {
"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",
}
a = {
"0": "resnets.0",
"1": "resnets.1",
"2": "resnets.2",
"4": "resnets.0",
"5": "resnets.1",
"6": "resnets.2",
}
a = {
"skip": "conv_skip",
"main.0": "conv_1",
"main.1": "group_norm_1",
"main.3": "conv_2",
"main.4": "group_norm_2",
}
a = {
"norm": "group_norm",
"qkv_proj": ["query", "key", "value"],
"out_proj": ["proj_attn"],
}
def __magic_name__ ( __UpperCAmelCase ) -> int:
'''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 __magic_name__ ( __UpperCAmelCase ) -> Union[str, Any]:
'''simple docstring'''
for key, value in ATTN_MAP.items():
if name.startswith(__UpperCAmelCase ) and not isinstance(__UpperCAmelCase , __UpperCAmelCase ):
return name.replace(__UpperCAmelCase , __UpperCAmelCase )
elif name.startswith(__UpperCAmelCase ):
return [name.replace(__UpperCAmelCase , __UpperCAmelCase ) for v in value]
raise ValueError(f"""Attn error with {name}""" )
def __magic_name__ ( __UpperCAmelCase , __UpperCAmelCase=13 ) -> Optional[int]:
'''simple docstring'''
__SCREAMING_SNAKE_CASE = input_string
if string.split(""".""" )[0] == "timestep_embed":
return string.replace("""timestep_embed""" , """time_proj""" )
__SCREAMING_SNAKE_CASE = 0
if string.startswith("""net.3.""" ):
depth += 1
__SCREAMING_SNAKE_CASE = string[6:]
elif string.startswith("""net.""" ):
__SCREAMING_SNAKE_CASE = string[4:]
while string.startswith("""main.7.""" ):
depth += 1
__SCREAMING_SNAKE_CASE = string[7:]
if string.startswith("""main.""" ):
__SCREAMING_SNAKE_CASE = string[5:]
# mid block
if string[:2].isdigit():
__SCREAMING_SNAKE_CASE = string[:2]
__SCREAMING_SNAKE_CASE = string[2:]
else:
__SCREAMING_SNAKE_CASE = string[0]
__SCREAMING_SNAKE_CASE = string[1:]
if depth == max_depth:
__SCREAMING_SNAKE_CASE = MID_NUM_TO_LAYER[layer_num]
__SCREAMING_SNAKE_CASE = """mid_block"""
elif depth > 0 and int(__UpperCAmelCase ) < 7:
__SCREAMING_SNAKE_CASE = DOWN_NUM_TO_LAYER[layer_num]
__SCREAMING_SNAKE_CASE = f"""down_blocks.{depth}"""
elif depth > 0 and int(__UpperCAmelCase ) > 7:
__SCREAMING_SNAKE_CASE = UP_NUM_TO_LAYER[layer_num]
__SCREAMING_SNAKE_CASE = f"""up_blocks.{max_depth - depth - 1}"""
elif depth == 0:
__SCREAMING_SNAKE_CASE = DEPTH_0_TO_LAYER[layer_num]
__SCREAMING_SNAKE_CASE = f"""up_blocks.{max_depth - 1}""" if int(__UpperCAmelCase ) > 3 else """down_blocks.0"""
if not string_left.startswith(""".""" ):
raise ValueError(f"""Naming error with {input_string} and string_left: {string_left}.""" )
__SCREAMING_SNAKE_CASE = string_left[1:]
if "resnets" in new_layer:
__SCREAMING_SNAKE_CASE = convert_resconv_naming(__UpperCAmelCase )
elif "attentions" in new_layer:
__SCREAMING_SNAKE_CASE = convert_attn_naming(__UpperCAmelCase )
__SCREAMING_SNAKE_CASE = new_string_left
if not isinstance(__UpperCAmelCase , __UpperCAmelCase ):
__SCREAMING_SNAKE_CASE = prefix + """.""" + new_layer + """.""" + string_left
else:
__SCREAMING_SNAKE_CASE = [prefix + """.""" + new_layer + """.""" + s for s in string_left]
return new_string
def __magic_name__ ( __UpperCAmelCase ) -> Optional[int]:
'''simple docstring'''
__SCREAMING_SNAKE_CASE = {}
for k, v in state_dict.items():
if k.endswith("""kernel""" ):
# up- and downsample layers, don't have trainable weights
continue
__SCREAMING_SNAKE_CASE = rename(__UpperCAmelCase )
# check if we need to transform from Conv => Linear for attention
if isinstance(__UpperCAmelCase , __UpperCAmelCase ):
__SCREAMING_SNAKE_CASE = transform_conv_attns(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
else:
__SCREAMING_SNAKE_CASE = v
return new_state_dict
def __magic_name__ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]:
'''simple docstring'''
if len(__UpperCAmelCase ) == 1:
if len(v.shape ) == 3:
# weight
__SCREAMING_SNAKE_CASE = v[:, :, 0]
else:
# bias
__SCREAMING_SNAKE_CASE = v
else:
# qkv matrices
__SCREAMING_SNAKE_CASE = v.shape[0]
__SCREAMING_SNAKE_CASE = trippled_shape // 3
for i in range(3 ):
if len(v.shape ) == 3:
__SCREAMING_SNAKE_CASE = v[i * single_shape : (i + 1) * single_shape, :, 0]
else:
__SCREAMING_SNAKE_CASE = v[i * single_shape : (i + 1) * single_shape]
return new_state_dict
def __magic_name__ ( __UpperCAmelCase ) -> Dict:
'''simple docstring'''
__SCREAMING_SNAKE_CASE = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" )
__SCREAMING_SNAKE_CASE = 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()}"""
__SCREAMING_SNAKE_CASE = download(__UpperCAmelCase )
__SCREAMING_SNAKE_CASE = MODELS_MAP[model_name]["""sample_rate"""]
__SCREAMING_SNAKE_CASE = MODELS_MAP[model_name]["""sample_size"""]
__SCREAMING_SNAKE_CASE = Object()
__SCREAMING_SNAKE_CASE = sample_size
__SCREAMING_SNAKE_CASE = sample_rate
__SCREAMING_SNAKE_CASE = 0
__SCREAMING_SNAKE_CASE = UNetaDModel(sample_size=__UpperCAmelCase , sample_rate=__UpperCAmelCase )
__SCREAMING_SNAKE_CASE = diffusers_model.state_dict()
__SCREAMING_SNAKE_CASE = DiffusionUncond(__UpperCAmelCase )
orig_model.load_state_dict(torch.load(args.model_path , map_location=__UpperCAmelCase )["""state_dict"""] )
__SCREAMING_SNAKE_CASE = orig_model.diffusion_ema.eval()
__SCREAMING_SNAKE_CASE = orig_model.state_dict()
__SCREAMING_SNAKE_CASE = rename_orig_weights(__UpperCAmelCase )
__SCREAMING_SNAKE_CASE = set(renamed_state_dict.keys() ) - set(diffusers_state_dict.keys() )
__SCREAMING_SNAKE_CASE = set(diffusers_state_dict.keys() ) - set(renamed_state_dict.keys() )
assert len(__UpperCAmelCase ) == 0, f"""Problem with {renamed_minus_diffusers}"""
assert all(k.endswith("""kernel""" ) for k in list(__UpperCAmelCase ) ), 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":
__SCREAMING_SNAKE_CASE = value.squeeze()
__SCREAMING_SNAKE_CASE = value
diffusers_model.load_state_dict(__UpperCAmelCase )
__SCREAMING_SNAKE_CASE = 100
__SCREAMING_SNAKE_CASE = 33
__SCREAMING_SNAKE_CASE = IPNDMScheduler(num_train_timesteps=__UpperCAmelCase )
__SCREAMING_SNAKE_CASE = torch.manual_seed(__UpperCAmelCase )
__SCREAMING_SNAKE_CASE = torch.randn([1, 2, config.sample_size] , generator=__UpperCAmelCase ).to(__UpperCAmelCase )
__SCREAMING_SNAKE_CASE = torch.linspace(1 , 0 , steps + 1 , device=__UpperCAmelCase )[:-1]
__SCREAMING_SNAKE_CASE = get_crash_schedule(__UpperCAmelCase )
__SCREAMING_SNAKE_CASE = DanceDiffusionPipeline(unet=__UpperCAmelCase , scheduler=__UpperCAmelCase )
__SCREAMING_SNAKE_CASE = torch.manual_seed(33 )
__SCREAMING_SNAKE_CASE = pipe(num_inference_steps=__UpperCAmelCase , generator=__UpperCAmelCase ).audios
__SCREAMING_SNAKE_CASE = sampling.iplms_sample(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , {} )
__SCREAMING_SNAKE_CASE = generated.clamp(-1 , 1 )
__SCREAMING_SNAKE_CASE = (generated - audio).abs().sum()
__SCREAMING_SNAKE_CASE = (generated - audio).abs().max()
if args.save:
pipe.save_pretrained(args.checkpoint_path )
print("""Diff sum""" , __UpperCAmelCase )
print("""Diff max""" , __UpperCAmelCase )
assert diff_max < 1e-3, f"""Diff max: {diff_max} is too much :-/"""
print(f"""Conversion for {model_name} successful!""" )
if __name__ == "__main__":
a = 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.")
a = parser.parse_args()
main(args)
| 109 | 1 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
a_ : Any = {
'configuration_nezha': ['NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'NezhaConfig'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a_ : Union[str, Any] = [
'NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST',
'NezhaForNextSentencePrediction',
'NezhaForMaskedLM',
'NezhaForPreTraining',
'NezhaForMultipleChoice',
'NezhaForQuestionAnswering',
'NezhaForSequenceClassification',
'NezhaForTokenClassification',
'NezhaModel',
'NezhaPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_nezha import NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP, NezhaConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_nezha import (
NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST,
NezhaForMaskedLM,
NezhaForMultipleChoice,
NezhaForNextSentencePrediction,
NezhaForPreTraining,
NezhaForQuestionAnswering,
NezhaForSequenceClassification,
NezhaForTokenClassification,
NezhaModel,
NezhaPreTrainedModel,
)
else:
import sys
a_ : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__) | 678 |
import re
def _SCREAMING_SNAKE_CASE ( snake_case_ : str ):
__magic_name__ = re.compile(
r'''^(?:0|94|\+94|0{2}94)''' r'''7(0|1|2|4|5|6|7|8)''' r'''(-| |)''' r'''\d{7}$''' )
return bool(re.search(snake_case_ , snake_case_ ) )
if __name__ == "__main__":
a_ : Optional[int] = '0094702343221'
print(is_sri_lankan_phone_number(phone)) | 678 | 1 |
import collections
import json
import os
import re
from typing import TYPE_CHECKING, List, Optional, Tuple
import numpy as np
from ...tokenization_utils_fast import PreTrainedTokenizer
from ...utils import logging
if TYPE_CHECKING:
from transformers.pipelines.conversational import Conversation
A__ : Union[str, Any] = logging.get_logger(__name__)
A__ : str = {"""vocab_file""": """vocab.txt""", """emoji_file""": """emoji.json"""}
A__ : Any = {
"""vocab_file""": {
"""abeja/gpt-neox-japanese-2.7b""": """https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/vocab.txt""",
},
"""emoji_file""": {
"""abeja/gpt-neox-japanese-2.7b""": """https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/emoji.json""",
},
}
A__ : str = {
"""abeja/gpt-neox-japanese-2.7b""": 2_0_4_8,
}
def _a ( __UpperCamelCase : Dict ,__UpperCamelCase : Any ):
with open(__UpperCamelCase ,'''r''' ,encoding='''utf-8''' ) as f:
lowerCAmelCase__ : Tuple = json.loads(f.read() )
lowerCAmelCase__ : List[str] = collections.OrderedDict()
lowerCAmelCase__ : Optional[Any] = collections.OrderedDict()
lowerCAmelCase__ : Optional[int] = collections.OrderedDict()
with open(__UpperCamelCase ,'''r''' ,encoding='''utf-8''' ) as f:
lowerCAmelCase__ : Optional[int] = f.readlines()
lowerCAmelCase__ : List[str] = [[t.rstrip('''\n''' )] if (t == ''',''' or ''',''' not in t) else t.rstrip('''\n''' ).split(''',''' ) for t in token]
for idx, b in enumerate(__UpperCamelCase ):
lowerCAmelCase__ : Tuple = b
lowerCAmelCase__ : str = idx
for wd in b:
lowerCAmelCase__ : Any = idx
return vocab, raw_vocab, ids_to_tokens, emoji
class lowercase ( __UpperCamelCase ):
__a = VOCAB_FILES_NAMES
__a = PRETRAINED_VOCAB_FILES_MAP
__a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__a = ["""input_ids""", """attention_mask"""]
def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__="<|endoftext|>" , SCREAMING_SNAKE_CASE__="<|endoftext|>" , SCREAMING_SNAKE_CASE__="<|startoftext|>" , SCREAMING_SNAKE_CASE__="<|endoftext|>" , SCREAMING_SNAKE_CASE__=False , **SCREAMING_SNAKE_CASE__ , ):
"""simple docstring"""
super().__init__(
unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , do_clean_text=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
if not os.path.isfile(SCREAMING_SNAKE_CASE__ ):
raise ValueError(
f'''Can\'t find a vocabulary file at path \'{vocab_file}\'. To load the vocabulary from a Google pretrained'''
''' model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`''' )
if not os.path.isfile(SCREAMING_SNAKE_CASE__ ):
raise ValueError(
f'''Can\'t find a emoji file at path \'{emoji_file}\'. To load the emoji information from a Google'''
''' pretrained model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`''' )
lowerCAmelCase__ : Optional[Any] = do_clean_text
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ : List[Any] = load_vocab_and_emoji(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ : List[str] = SubWordJapaneseTokenizer(
vocab=self.vocab , ids_to_tokens=self.ids_to_tokens , emoji=self.emoji )
@property
def lowercase_ ( self ):
"""simple docstring"""
return len(self.raw_vocab )
def lowercase_ ( self ):
"""simple docstring"""
return dict(self.raw_vocab , **self.added_tokens_encoder )
def lowercase_ ( self , SCREAMING_SNAKE_CASE__ ):
"""simple docstring"""
return self.subword_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ , clean=self.do_clean_text )
def lowercase_ ( self , SCREAMING_SNAKE_CASE__ ):
"""simple docstring"""
return self.vocab.get(SCREAMING_SNAKE_CASE__ , self.vocab.get(self.unk_token ) )
def lowercase_ ( self , SCREAMING_SNAKE_CASE__ ):
"""simple docstring"""
return self.subword_tokenizer.convert_id_to_token(SCREAMING_SNAKE_CASE__ )
def lowercase_ ( self , SCREAMING_SNAKE_CASE__ ):
"""simple docstring"""
lowerCAmelCase__ : List[str] = ''''''.join(SCREAMING_SNAKE_CASE__ ).strip()
return out_string
def lowercase_ ( self , SCREAMING_SNAKE_CASE__ ):
"""simple docstring"""
lowerCAmelCase__ : List[Any] = []
for is_user, text in conversation.iter_texts():
input_ids.extend(self.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) + [self.eos_token_id] )
if len(SCREAMING_SNAKE_CASE__ ) > self.model_max_length:
lowerCAmelCase__ : Any = input_ids[-self.model_max_length :]
return input_ids
def lowercase_ ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ):
"""simple docstring"""
lowerCAmelCase__ : Any = 0
if os.path.isdir(SCREAMING_SNAKE_CASE__ ):
lowerCAmelCase__ : str = os.path.join(
SCREAMING_SNAKE_CASE__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
lowerCAmelCase__ : Tuple = os.path.join(
SCREAMING_SNAKE_CASE__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''emoji_file'''] )
else:
lowerCAmelCase__ : Tuple = (
(filename_prefix + '''-''' if filename_prefix else '''''') + save_directory + VOCAB_FILES_NAMES['''vocab_file''']
)
lowerCAmelCase__ : Dict = (
(filename_prefix + '''-''' if filename_prefix else '''''') + save_directory + VOCAB_FILES_NAMES['''emoji_file''']
)
with open(SCREAMING_SNAKE_CASE__ , '''w''' , encoding='''utf-8''' ) as writer:
for token_index, token in self.ids_to_tokens.items():
if index != token_index:
logger.warning(
f'''Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.'''
''' Please check that the vocabulary is not corrupted!''' )
lowerCAmelCase__ : Optional[Any] = token_index
writer.write(''','''.join(SCREAMING_SNAKE_CASE__ ) + '''\n''' )
index += 1
with open(SCREAMING_SNAKE_CASE__ , '''w''' , encoding='''utf-8''' ) as writer:
json.dump(self.emoji , SCREAMING_SNAKE_CASE__ )
return vocab_file, emoji_file
class lowercase ( __UpperCamelCase ):
def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
"""simple docstring"""
lowerCAmelCase__ : Optional[int] = vocab # same as swe
lowerCAmelCase__ : Dict = ids_to_tokens # same as bpe
lowerCAmelCase__ : Optional[int] = emoji
lowerCAmelCase__ : int = np.max([len(SCREAMING_SNAKE_CASE__ ) for w in self.vocab.keys()] )
lowerCAmelCase__ : Union[str, Any] = re.compile(R'''(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)''' )
lowerCAmelCase__ : Optional[int] = re.compile(R'''[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*''' )
lowerCAmelCase__ : str = re.compile(R'''[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}''' )
lowerCAmelCase__ : Dict = re.compile(
R'''([12]\d{3}[/\-年])*(0?[1-9]|1[0-2])[/\-月]((0?[1-9]|[12][0-9]|3[01])日?)*(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*''' )
lowerCAmelCase__ : List[Any] = re.compile(
R'''(明治|大正|昭和|平成|令和|㍾|㍽|㍼|㍻|\u32ff)\d{1,2}年(0?[1-9]|1[0-2])月(0?[1-9]|[12][0-9]|3[01])日(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*''' )
lowerCAmelCase__ : Any = re.compile(
R'''((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*億)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*万)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*千)*(0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*(千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+(\(税込\)|\(税抜\)|\+tax)*''' )
lowerCAmelCase__ : Union[str, Any] = '''─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿'''
lowerCAmelCase__ : Tuple = '''▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟'''
lowerCAmelCase__ : int = str.maketrans({k: '''<BLOCK>''' for k in keisen + blocks} )
def __len__( self ):
"""simple docstring"""
return len(self.ids_to_tokens )
def lowercase_ ( self , SCREAMING_SNAKE_CASE__ ):
"""simple docstring"""
lowerCAmelCase__ : Optional[Any] = self.content_repattera.sub('''<URL>''' , SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ : str = self.content_repattera.sub('''<EMAIL>''' , SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ : str = self.content_repattera.sub('''<TEL>''' , SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ : Union[str, Any] = self.content_repattera.sub('''<DATE>''' , SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ : List[str] = self.content_repattera.sub('''<DATE>''' , SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ : Any = self.content_repattera.sub('''<PRICE>''' , SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ : List[str] = content.translate(self.content_transa )
while "<BLOCK><BLOCK>" in content:
lowerCAmelCase__ : Optional[Any] = content.replace('''<BLOCK><BLOCK>''' , '''<BLOCK>''' )
return content
def lowercase_ ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False ):
"""simple docstring"""
lowerCAmelCase__ : Optional[int] = text.replace(''' ''' , '''<SP>''' )
lowerCAmelCase__ : Optional[int] = text.replace(''' ''' , '''<SP>''' )
lowerCAmelCase__ : int = text.replace('''\r\n''' , '''<BR>''' )
lowerCAmelCase__ : Tuple = text.replace('''\n''' , '''<BR>''' )
lowerCAmelCase__ : str = text.replace('''\r''' , '''<BR>''' )
lowerCAmelCase__ : Dict = text.replace('''\t''' , '''<TAB>''' )
lowerCAmelCase__ : Union[str, Any] = text.replace('''—''' , '''ー''' )
lowerCAmelCase__ : Optional[Any] = text.replace('''−''' , '''ー''' )
for k, v in self.emoji["emoji"].items():
if k in text:
lowerCAmelCase__ : List[str] = text.replace(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
if clean:
lowerCAmelCase__ : Tuple = self.clean_text(SCREAMING_SNAKE_CASE__ )
def check_simbol(SCREAMING_SNAKE_CASE__ ):
lowerCAmelCase__ : Any = x.encode()
if len(SCREAMING_SNAKE_CASE__ ) == 1 and len(SCREAMING_SNAKE_CASE__ ) == 2:
lowerCAmelCase__ : Dict = (int(e[0] ) << 8) + int(e[1] )
if (
(c >= 0xc_2_a_1 and c <= 0xc_2_b_f)
or (c >= 0xc_7_8_0 and c <= 0xc_7_8_3)
or (c >= 0xc_a_b_9 and c <= 0xc_b_b_f)
or (c >= 0xc_c_8_0 and c <= 0xc_d_a_2)
):
return True
return False
def checkuae(SCREAMING_SNAKE_CASE__ ):
lowerCAmelCase__ : List[str] = x.encode()
if len(SCREAMING_SNAKE_CASE__ ) == 1 and len(SCREAMING_SNAKE_CASE__ ) == 3:
lowerCAmelCase__ : Dict = (int(e[0] ) << 16) + (int(e[1] ) << 8) + int(e[2] )
if c >= 0xe_2_8_0_8_0 and c <= 0xe_2_b_0_7_f:
return True
return False
lowerCAmelCase__ : Tuple = 0
lowerCAmelCase__ : List[Any] = []
while pos < len(SCREAMING_SNAKE_CASE__ ):
lowerCAmelCase__ : Optional[Any] = min(len(SCREAMING_SNAKE_CASE__ ) , pos + self.maxlen + 1 ) if text[pos] == '''<''' else pos + 3
lowerCAmelCase__ : Optional[Any] = [] # (token_id, token, pos)
for e in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , -1 ):
lowerCAmelCase__ : Tuple = text[pos:e]
if wd in self.vocab:
if wd[0] == "<" and len(SCREAMING_SNAKE_CASE__ ) > 2:
lowerCAmelCase__ : int = [(self.vocab[wd], wd, e)]
break
else:
candidates.append((self.vocab[wd], wd, e) )
if len(SCREAMING_SNAKE_CASE__ ) > 0:
# the smallest token_id is adopted
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ : int = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : x[0] )[0]
result.append(SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ : Union[str, Any] = e
else:
lowerCAmelCase__ : str = pos + 1
lowerCAmelCase__ : Any = text[pos:end]
if check_simbol(SCREAMING_SNAKE_CASE__ ):
result.append('''<KIGOU>''' )
elif checkuae(SCREAMING_SNAKE_CASE__ ):
result.append('''<U2000U2BFF>''' )
else:
for i in wd.encode('''utf-8''' ):
result.append('''<|byte%d|>''' % i )
lowerCAmelCase__ : int = end
return result
def lowercase_ ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__="\n" ):
"""simple docstring"""
lowerCAmelCase__ : List[Any] = []
lowerCAmelCase__ : Union[str, Any] = []
lowerCAmelCase__ : int = self.ids_to_tokens[index][0]
if word[:6] == "<|byte" and word[-2:] == "|>":
byte_tokens.append(int(word[6:-2] ) )
else:
if len(SCREAMING_SNAKE_CASE__ ) > 0:
words.append(bytearray(SCREAMING_SNAKE_CASE__ ).decode('''utf-8''' , errors='''replace''' ) )
lowerCAmelCase__ : Any = []
if word[:7] == "<|emoji" and word[-2:] == "|>":
words.append(self.emoji['''emoji_inv'''][word] )
elif word == "<SP>":
words.append(''' ''' )
elif word == "<BR>":
words.append(SCREAMING_SNAKE_CASE__ )
elif word == "<TAB>":
words.append('''\t''' )
elif word == "<BLOCK>":
words.append('''▀''' )
elif word == "<KIGOU>":
words.append('''ǀ''' )
elif word == "<U2000U2BFF>":
words.append('''‖''' )
else:
words.append(SCREAMING_SNAKE_CASE__ )
if len(SCREAMING_SNAKE_CASE__ ) > 0:
words.append(bytearray(SCREAMING_SNAKE_CASE__ ).decode('''utf-8''' , errors='''replace''' ) )
lowerCAmelCase__ : Any = ''''''.join(SCREAMING_SNAKE_CASE__ )
return text
| 233 |
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
A__ : Dict = logging.get_logger(__name__)
A__ : Optional[Any] = {
"""facebook/xmod-base""": """https://huggingface.co/facebook/xmod-base/resolve/main/config.json""",
"""facebook/xmod-large-prenorm""": """https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json""",
"""facebook/xmod-base-13-125k""": """https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json""",
"""facebook/xmod-base-30-125k""": """https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json""",
"""facebook/xmod-base-30-195k""": """https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json""",
"""facebook/xmod-base-60-125k""": """https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json""",
"""facebook/xmod-base-60-265k""": """https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json""",
"""facebook/xmod-base-75-125k""": """https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json""",
"""facebook/xmod-base-75-269k""": """https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json""",
}
class lowercase ( __UpperCamelCase ):
__a = """xmod"""
def __init__( self , SCREAMING_SNAKE_CASE__=30522 , SCREAMING_SNAKE_CASE__=768 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=3072 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=512 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=1E-12 , SCREAMING_SNAKE_CASE__=1 , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__="absolute" , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=("en_XX",) , SCREAMING_SNAKE_CASE__=None , **SCREAMING_SNAKE_CASE__ , ):
"""simple docstring"""
super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ : Optional[int] = vocab_size
lowerCAmelCase__ : str = hidden_size
lowerCAmelCase__ : str = num_hidden_layers
lowerCAmelCase__ : List[str] = num_attention_heads
lowerCAmelCase__ : Union[str, Any] = hidden_act
lowerCAmelCase__ : str = intermediate_size
lowerCAmelCase__ : List[str] = hidden_dropout_prob
lowerCAmelCase__ : List[Any] = attention_probs_dropout_prob
lowerCAmelCase__ : Tuple = max_position_embeddings
lowerCAmelCase__ : Any = type_vocab_size
lowerCAmelCase__ : Optional[Any] = initializer_range
lowerCAmelCase__ : int = layer_norm_eps
lowerCAmelCase__ : Tuple = position_embedding_type
lowerCAmelCase__ : Any = use_cache
lowerCAmelCase__ : Union[str, Any] = classifier_dropout
lowerCAmelCase__ : List[str] = pre_norm
lowerCAmelCase__ : str = adapter_reduction_factor
lowerCAmelCase__ : Optional[int] = adapter_layer_norm
lowerCAmelCase__ : List[Any] = adapter_reuse_layer_norm
lowerCAmelCase__ : Optional[Any] = ln_before_adapter
lowerCAmelCase__ : Optional[int] = list(SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ : List[str] = default_language
class lowercase ( __UpperCamelCase ):
@property
def lowercase_ ( self ):
"""simple docstring"""
if self.task == "multiple-choice":
lowerCAmelCase__ : str = {0: '''batch''', 1: '''choice''', 2: '''sequence'''}
else:
lowerCAmelCase__ : List[Any] = {0: '''batch''', 1: '''sequence'''}
return OrderedDict(
[
('''input_ids''', dynamic_axis),
('''attention_mask''', dynamic_axis),
] )
| 233 | 1 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available
__lowerCamelCase : Tuple = {"""configuration_speech_encoder_decoder""": ["""SpeechEncoderDecoderConfig"""]}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCamelCase : Tuple = ["""SpeechEncoderDecoderModel"""]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCamelCase : Union[str, Any] = ["""FlaxSpeechEncoderDecoderModel"""]
if TYPE_CHECKING:
from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel
else:
import sys
__lowerCamelCase : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 713 |
import math
from typing import Dict, Iterable, List, Optional, Tuple, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
IMAGENET_STANDARD_MEAN,
IMAGENET_STANDARD_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
get_image_size,
is_torch_available,
is_torch_tensor,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
if is_torch_available():
import torch
if is_vision_available():
import PIL
__lowerCamelCase : Union[str, Any] = logging.get_logger(__name__)
def A__ ( _a : np.ndarray , _a : Union[int, Iterable[int]] , _a : bool , _a : int ):
'''simple docstring'''
def constraint_to_multiple_of(_a : Union[str, Any] , _a : List[str] , _a : str=0 , _a : Any=None ):
snake_case__ : Any =round(val / multiple ) * multiple
if max_val is not None and x > max_val:
snake_case__ : int =math.floor(val / multiple ) * multiple
if x < min_val:
snake_case__ : Dict =math.ceil(val / multiple ) * multiple
return x
snake_case__ : str =(output_size, output_size) if isinstance(_a , _a ) else output_size
snake_case__ , snake_case__ : Dict =get_image_size(_a )
snake_case__ , snake_case__ : int =output_size
# determine new height and width
snake_case__ : Tuple =output_height / input_height
snake_case__ : Optional[Any] =output_width / input_width
if keep_aspect_ratio:
# scale as little as possible
if abs(1 - scale_width ) < abs(1 - scale_height ):
# fit width
snake_case__ : Optional[int] =scale_width
else:
# fit height
snake_case__ : Any =scale_height
snake_case__ : Optional[int] =constraint_to_multiple_of(scale_height * input_height , multiple=_a )
snake_case__ : str =constraint_to_multiple_of(scale_width * input_width , multiple=_a )
return (new_height, new_width)
class _lowercase ( _A ):
_a : List[Any] = ['pixel_values']
def __init__( self , a = True , a = None , a = PILImageResampling.BILINEAR , a = False , a = 1 , a = True , a = 1 / 2_5_5 , a = True , a = None , a = None , **a , ):
super().__init__(**a )
snake_case__ : Any =size if size is not None else {"""height""": 3_8_4, """width""": 3_8_4}
snake_case__ : List[Any] =get_size_dict(a )
snake_case__ : Tuple =do_resize
snake_case__ : Tuple =size
snake_case__ : Any =keep_aspect_ratio
snake_case__ : List[Any] =ensure_multiple_of
snake_case__ : Tuple =resample
snake_case__ : str =do_rescale
snake_case__ : int =rescale_factor
snake_case__ : Tuple =do_normalize
snake_case__ : int =image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
snake_case__ : Any =image_std if image_std is not None else IMAGENET_STANDARD_STD
def lowercase__ ( self , a , a , a = False , a = 1 , a = PILImageResampling.BICUBIC , a = None , **a , ):
snake_case__ : Tuple =get_size_dict(a )
if "height" not in size or "width" not in size:
raise ValueError(F"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}" )
snake_case__ : Optional[int] =get_resize_output_image_size(
a , output_size=(size["""height"""], size["""width"""]) , keep_aspect_ratio=a , multiple=a , )
return resize(a , size=a , resample=a , data_format=a , **a )
def lowercase__ ( self , a , a , a = None , **a , ):
return rescale(a , scale=a , data_format=a , **a )
def lowercase__ ( self , a , a , a , a = None , **a , ):
return normalize(a , mean=a , std=a , data_format=a , **a )
def lowercase__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ):
snake_case__ : Optional[int] =do_resize if do_resize is not None else self.do_resize
snake_case__ : List[Any] =size if size is not None else self.size
snake_case__ : int =get_size_dict(a )
snake_case__ : Optional[int] =keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
snake_case__ : int =ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
snake_case__ : Optional[Any] =resample if resample is not None else self.resample
snake_case__ : Optional[int] =do_rescale if do_rescale is not None else self.do_rescale
snake_case__ : str =rescale_factor if rescale_factor is not None else self.rescale_factor
snake_case__ : Optional[Any] =do_normalize if do_normalize is not None else self.do_normalize
snake_case__ : Tuple =image_mean if image_mean is not None else self.image_mean
snake_case__ : int =image_std if image_std is not None else self.image_std
snake_case__ : int =make_list_of_images(a )
if not valid_images(a ):
raise ValueError(
"""Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
"""torch.Tensor, tf.Tensor or jax.ndarray.""" )
if do_resize and size is None or resample is None:
raise ValueError("""Size and resample must be specified if do_resize is True.""" )
if do_rescale and rescale_factor is None:
raise ValueError("""Rescale factor must be specified if do_rescale is True.""" )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError("""Image mean and std must be specified if do_normalize is True.""" )
# All transformations expect numpy arrays.
snake_case__ : int =[to_numpy_array(a ) for image in images]
if do_resize:
snake_case__ : List[str] =[self.resize(image=a , size=a , resample=a ) for image in images]
if do_rescale:
snake_case__ : List[Any] =[self.rescale(image=a , scale=a ) for image in images]
if do_normalize:
snake_case__ : str =[self.normalize(image=a , mean=a , std=a ) for image in images]
snake_case__ : List[Any] =[to_channel_dimension_format(a , a ) for image in images]
snake_case__ : Union[str, Any] ={"""pixel_values""": images}
return BatchFeature(data=a , tensor_type=a )
def lowercase__ ( self , a , a = None ):
snake_case__ : Optional[Any] =outputs.logits
# Resize logits and compute semantic segmentation maps
if target_sizes is not None:
if len(a ) != len(a ):
raise ValueError(
"""Make sure that you pass in as many target sizes as the batch dimension of the logits""" )
if is_torch_tensor(a ):
snake_case__ : Optional[Any] =target_sizes.numpy()
snake_case__ : Optional[Any] =[]
for idx in range(len(a ) ):
snake_case__ : List[str] =torch.nn.functional.interpolate(
logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=a )
snake_case__ : List[Any] =resized_logits[0].argmax(dim=0 )
semantic_segmentation.append(a )
else:
snake_case__ : List[str] =logits.argmax(dim=1 )
snake_case__ : Optional[int] =[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )]
return semantic_segmentation
| 448 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.