code stringlengths 82 54.1k | code_codestyle int64 0 699 | style_context stringlengths 111 35.6k | style_context_codestyle int64 0 699 | label int64 0 1 |
|---|---|---|---|---|
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_tokenizers_available,
is_torch_available,
)
__A = {"configuration_fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FNetConfig"]}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = ["FNetTokenizer"]
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = ["FNetTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
"FNET_PRETRAINED_MODEL_ARCHIVE_LIST",
"FNetForMaskedLM",
"FNetForMultipleChoice",
"FNetForNextSentencePrediction",
"FNetForPreTraining",
"FNetForQuestionAnswering",
"FNetForSequenceClassification",
"FNetForTokenClassification",
"FNetLayer",
"FNetModel",
"FNetPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_fnet import FNetTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_fnet_fast import FNetTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_fnet import (
FNET_PRETRAINED_MODEL_ARCHIVE_LIST,
FNetForMaskedLM,
FNetForMultipleChoice,
FNetForNextSentencePrediction,
FNetForPreTraining,
FNetForQuestionAnswering,
FNetForSequenceClassification,
FNetForTokenClassification,
FNetLayer,
FNetModel,
FNetPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 59 |
from transformers import BertTokenizerFast
from .custom_tokenization import CustomTokenizer
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = CustomTokenizer
pass
| 59 | 1 |
import unittest
from transformers import DonutProcessor
__A = "naver-clova-ix/donut-base"
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->str:
'''simple docstring'''
lowerCamelCase__: int =DonutProcessor.from_pretrained(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->str:
'''simple docstring'''
lowerCamelCase__: Any ={
"name": "John Doe",
"age": "99",
"city": "Atlanta",
"state": "GA",
"zip": "30301",
"phone": "123-4567",
"nicknames": [{"nickname": "Johnny"}, {"nickname": "JD"}],
}
lowerCamelCase__: Tuple =(
"<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>"
"<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>"
"<s_nicknames><s_nickname>Johnny</s_nickname>"
"<sep/><s_nickname>JD</s_nickname></s_nicknames>"
)
lowerCamelCase__: Optional[int] =self.processor.tokenajson(UpperCAmelCase_)
self.assertDictEqual(UpperCAmelCase_ , UpperCAmelCase_)
| 59 |
import inspect
import os
import unittest
import torch
import accelerate
from accelerate import Accelerator
from accelerate.test_utils import execute_subprocess_async, require_multi_gpu
from accelerate.utils import patch_environment
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: List[Any] =inspect.getfile(accelerate.test_utils)
lowerCamelCase__: List[Any] =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_script.py"])
lowerCamelCase__: Any =os.path.sep.join(
mod_file.split(os.path.sep)[:-1] + ["scripts", "test_distributed_data_loop.py"])
lowerCamelCase__: Tuple =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_ops.py"])
@require_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : str) ->str:
'''simple docstring'''
print(F"""Found {torch.cuda.device_count()} devices.""")
lowerCamelCase__: Union[str, Any] =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path]
with patch_environment(omp_num_threads=1):
execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy())
@require_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[Any]:
'''simple docstring'''
print(F"""Found {torch.cuda.device_count()} devices.""")
lowerCamelCase__: Dict =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path]
print(F"""Command: {cmd}""")
with patch_environment(omp_num_threads=1):
execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy())
@require_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Tuple:
'''simple docstring'''
lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__)]
with patch_environment(omp_num_threads=1):
execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy())
@require_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]:
'''simple docstring'''
print(F"""Found {torch.cuda.device_count()} devices, using 2 devices only""")
lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path]
with patch_environment(omp_num_threads=1 , cuda_visible_devices="0,1"):
execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy())
if __name__ == "__main__":
__A = Accelerator()
__A = (accelerator.state.process_index + 2, 10)
__A = torch.randint(0, 10, shape).to(accelerator.device)
__A = ""
__A = accelerator.pad_across_processes(tensor)
if tensora.shape[0] != accelerator.state.num_processes + 1:
error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0."
if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor):
error_msg += "Tensors have different values."
if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0):
error_msg += "Padding was not done with the right value (0)."
__A = accelerator.pad_across_processes(tensor, pad_first=True)
if tensora.shape[0] != accelerator.state.num_processes + 1:
error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0."
__A = accelerator.state.num_processes - accelerator.state.process_index - 1
if not torch.equal(tensora[index:], tensor):
error_msg += "Tensors have different values."
if not torch.all(tensora[:index] == 0):
error_msg += "Padding was not done with the right value (0)."
# Raise error at the end to make sure we don't stop at the first failure.
if len(error_msg) > 0:
raise ValueError(error_msg)
| 59 | 1 |
import multiprocessing
from typing import TYPE_CHECKING, Optional, Union
from .. import Dataset, Features, config
from ..formatting import query_table
from ..packaged_modules.sql.sql import Sql
from ..utils import logging
from .abc import AbstractDatasetInputStream
if TYPE_CHECKING:
import sqlitea
import sqlalchemy
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__(self : Any , UpperCAmelCase_ : Union[str, "sqlalchemy.sql.Selectable"] , UpperCAmelCase_ : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] , UpperCAmelCase_ : Optional[Features] = None , UpperCAmelCase_ : str = None , UpperCAmelCase_ : bool = False , **UpperCAmelCase_ : str , ) ->List[Any]:
'''simple docstring'''
super().__init__(features=UpperCAmelCase_ , cache_dir=UpperCAmelCase_ , keep_in_memory=UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: Union[str, Any] =Sql(
cache_dir=UpperCAmelCase_ , features=UpperCAmelCase_ , sql=UpperCAmelCase_ , con=UpperCAmelCase_ , **UpperCAmelCase_ , )
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Any:
'''simple docstring'''
lowerCamelCase__: List[Any] =None
lowerCamelCase__: Optional[Any] =None
lowerCamelCase__: Tuple =None
lowerCamelCase__: str =None
self.builder.download_and_prepare(
download_config=UpperCAmelCase_ , download_mode=UpperCAmelCase_ , verification_mode=UpperCAmelCase_ , base_path=UpperCAmelCase_ , )
# Build dataset for splits
lowerCamelCase__: List[str] =self.builder.as_dataset(
split="train" , verification_mode=UpperCAmelCase_ , in_memory=self.keep_in_memory)
return dataset
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__(self : Optional[int] , UpperCAmelCase_ : Dataset , UpperCAmelCase_ : str , UpperCAmelCase_ : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : Optional[int] = None , **UpperCAmelCase_ : Tuple , ) ->str:
'''simple docstring'''
if num_proc is not None and num_proc <= 0:
raise ValueError(F"""num_proc {num_proc} must be an integer > 0.""")
lowerCamelCase__: Any =dataset
lowerCamelCase__: str =name
lowerCamelCase__: List[str] =con
lowerCamelCase__: Optional[Any] =batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
lowerCamelCase__: List[str] =num_proc
lowerCamelCase__: Dict =to_sql_kwargs
def SCREAMING_SNAKE_CASE_ (self : Dict) ->int:
'''simple docstring'''
lowerCamelCase__: Tuple =self.to_sql_kwargs.pop("sql" , UpperCAmelCase_)
lowerCamelCase__: Dict =self.to_sql_kwargs.pop("con" , UpperCAmelCase_)
lowerCamelCase__: List[str] =self.to_sql_kwargs.pop("index" , UpperCAmelCase_)
lowerCamelCase__: Tuple =self._write(index=UpperCAmelCase_ , **self.to_sql_kwargs)
return written
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : Tuple) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[str] =args
lowerCamelCase__: Union[str, Any] ={**to_sql_kwargs, "if_exists": "append"} if offset > 0 else to_sql_kwargs
lowerCamelCase__: Tuple =query_table(
table=self.dataset.data , key=slice(UpperCAmelCase_ , offset + self.batch_size) , indices=self.dataset._indices , )
lowerCamelCase__: Any =batch.to_pandas()
lowerCamelCase__: List[Any] =df.to_sql(self.name , self.con , index=UpperCAmelCase_ , **UpperCAmelCase_)
return num_rows or len(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[int]) ->int:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =0
if self.num_proc is None or self.num_proc == 1:
for offset in logging.tqdm(
range(0 , len(self.dataset) , self.batch_size) , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ):
written += self._batch_sql((offset, index, to_sql_kwargs))
else:
lowerCamelCase__ , lowerCamelCase__: Optional[Any] =len(self.dataset), self.batch_size
with multiprocessing.Pool(self.num_proc) as pool:
for num_rows in logging.tqdm(
pool.imap(
self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , UpperCAmelCase_ , UpperCAmelCase_)] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ):
written += num_rows
return written
| 59 |
from typing import List, Optional, Tuple, Union
import PIL
import torch
from torchvision import transforms
from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
from diffusers.schedulers import DDIMScheduler
from diffusers.utils import randn_tensor
__A = transforms.Compose(
[
transforms.Resize((256, 256)),
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5]),
]
)
def lowerCAmelCase_ ( __a ) -> str:
"""simple docstring"""
if isinstance(__a , torch.Tensor ):
return image
elif isinstance(__a , PIL.Image.Image ):
lowerCamelCase__: Any =[image]
lowerCamelCase__: Optional[Any] =[trans(img.convert("RGB" ) ) for img in image]
lowerCamelCase__: Dict =torch.stack(__a )
return image
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__(self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple) ->int:
'''simple docstring'''
super().__init__()
# make sure scheduler can always be converted to DDIM
lowerCamelCase__: Tuple =DDIMScheduler.from_config(scheduler.config)
self.register_modules(unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Union[str, Any]) ->Dict:
'''simple docstring'''
if strength < 0 or strength > 1:
raise ValueError(F"""The value of strength should in [0.0, 1.0] but is {strength}""")
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple) ->Tuple:
'''simple docstring'''
lowerCamelCase__: int =min(int(num_inference_steps * strength) , UpperCAmelCase_)
lowerCamelCase__: str =max(num_inference_steps - init_timestep , 0)
lowerCamelCase__: int =self.scheduler.timesteps[t_start:]
return timesteps, num_inference_steps - t_start
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int]=None) ->Optional[int]:
'''simple docstring'''
if not isinstance(UpperCAmelCase_ , (torch.Tensor, PIL.Image.Image, list)):
raise ValueError(
F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(UpperCAmelCase_)}""")
lowerCamelCase__: Optional[int] =image.to(device=UpperCAmelCase_ , dtype=UpperCAmelCase_)
if isinstance(UpperCAmelCase_ , UpperCAmelCase_) and len(UpperCAmelCase_) != batch_size:
raise ValueError(
F"""You have passed a list of generators of length {len(UpperCAmelCase_)}, but requested an effective batch"""
F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""")
lowerCamelCase__: Dict =init_latents.shape
lowerCamelCase__: int =randn_tensor(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=UpperCAmelCase_)
# get latents
print("add noise to latents at timestep" , UpperCAmelCase_)
lowerCamelCase__: Union[str, Any] =self.scheduler.add_noise(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: int =init_latents
return latents
@torch.no_grad()
def __call__(self : Tuple , UpperCAmelCase_ : Union[torch.FloatTensor, PIL.Image.Image] = None , UpperCAmelCase_ : float = 0.8 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , ) ->Union[ImagePipelineOutput, Tuple]:
'''simple docstring'''
self.check_inputs(UpperCAmelCase_)
# 2. Preprocess image
lowerCamelCase__: Dict =preprocess(UpperCAmelCase_)
# 3. set timesteps
self.scheduler.set_timesteps(UpperCAmelCase_ , device=self.device)
lowerCamelCase__ , lowerCamelCase__: str =self.get_timesteps(UpperCAmelCase_ , UpperCAmelCase_ , self.device)
lowerCamelCase__: Optional[int] =timesteps[:1].repeat(UpperCAmelCase_)
# 4. Prepare latent variables
lowerCamelCase__: int =self.prepare_latents(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , self.unet.dtype , self.device , UpperCAmelCase_)
lowerCamelCase__: Tuple =latents
# 5. Denoising loop
for t in self.progress_bar(UpperCAmelCase_):
# 1. predict noise model_output
lowerCamelCase__: Dict =self.unet(UpperCAmelCase_ , UpperCAmelCase_).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
lowerCamelCase__: Optional[int] =self.scheduler.step(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , eta=UpperCAmelCase_ , use_clipped_model_output=UpperCAmelCase_ , generator=UpperCAmelCase_ , ).prev_sample
lowerCamelCase__: str =(image / 2 + 0.5).clamp(0 , 1)
lowerCamelCase__: Optional[Any] =image.cpu().permute(0 , 2 , 3 , 1).numpy()
if output_type == "pil":
lowerCamelCase__: Dict =self.numpy_to_pil(UpperCAmelCase_)
if not return_dict:
return (image, latent_timestep.item())
return ImagePipelineOutput(images=UpperCAmelCase_)
| 59 | 1 |
import argparse
import logging
import os
import datasets
import tensorflow as tf
from transformers import AutoTokenizer
__A = logging.getLogger(__name__)
def lowerCAmelCase_ ( ) -> int:
"""simple docstring"""
lowerCamelCase__: str =argparse.ArgumentParser(
description="Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset." )
parser.add_argument(
"--dataset_name" , type=__a , default="wikitext" , help="Name of the training. Explore datasets at: hf.co/datasets." , )
parser.add_argument(
"--dataset_config" , type=__a , default="wikitext-103-raw-v1" , help="Configuration name of the dataset." )
parser.add_argument(
"--tokenizer_name_or_path" , type=__a , default="sayakpaul/unigram-tokenizer-wikitext" , help="Tokenizer identifier. Can be a local filepath or a Hub identifier." , )
parser.add_argument(
"--shard_size" , type=__a , default=1000 , help="Number of entries to go in a single shard." , )
parser.add_argument("--split" , type=__a , default="train" , choices=["train", "test", "validation"] )
parser.add_argument(
"--limit" , default=__a , type=__a , help="Limit the number of shards (used for debugging)." , )
parser.add_argument(
"--max_length" , type=__a , default=512 , 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=__a , 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." , )
lowerCamelCase__: Dict =parser.parse_args()
return args
def lowerCAmelCase_ ( __a ) -> Union[str, Any]:
"""simple docstring"""
def fn(__a ):
return tokenizer(examples["text"] )
return fn
def lowerCAmelCase_ ( __a ) -> Optional[Any]:
"""simple docstring"""
lowerCamelCase__: int =[]
for i in range(len(tokenized_data["input_ids"] ) ):
lowerCamelCase__: 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] ) ),
}
lowerCamelCase__: int =tf.train.Features(feature=__a )
lowerCamelCase__: Any =tf.train.Example(features=__a )
lowerCamelCase__: int =example.SerializeToString()
records.append(__a )
return records
def lowerCAmelCase_ ( __a ) -> Dict:
"""simple docstring"""
lowerCamelCase__: Union[str, Any] =datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split )
if args.limit is not None:
lowerCamelCase__: Any =min(len(__a ) , args.limit )
lowerCamelCase__: str =dataset.select(range(__a ) )
print(F"""Limiting the dataset to {args.limit} entries.""" )
lowerCamelCase__: List[Any] =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 )
lowerCamelCase__: str =os.path.join(args.output_dir , args.split )
if not os.path.exists(__a ):
os.makedirs(__a )
else:
lowerCamelCase__: int =os.path.join(args.output_dir , args.split )
# Tokenize the whole dataset at once.
lowerCamelCase__: Optional[Any] =tokenize_function(__a )
lowerCamelCase__: List[Any] =dataset.map(__a , batched=__a , 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(__a ):
# Concatenate all texts.
lowerCamelCase__: Dict ={k: sum(examples[k] , [] ) for k in examples.keys()}
lowerCamelCase__: 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 🫀
lowerCamelCase__: str =(total_length // args.max_length) * args.max_length
# Split by chunks of max_len.
lowerCamelCase__: Optional[Any] ={
k: [t[i : i + args.max_length] for i in range(0 , __a , args.max_length )]
for k, t in concatenated_examples.items()
}
return result
lowerCamelCase__: int =dataset_tokenized.map(__a , batched=__a , batch_size=1000 , num_proc=4 )
lowerCamelCase__: Union[str, Any] =0
lowerCamelCase__: Optional[int] =0
for shard in range(0 , len(__a ) , args.shard_size ):
lowerCamelCase__: Any =grouped_dataset[shard : shard + args.shard_size]
lowerCamelCase__: Any =len(dataset_snapshot["input_ids"] )
lowerCamelCase__: int =os.path.join(__a , F"""dataset-{shard_count}-{records_containing}.tfrecord""" )
lowerCamelCase__: Union[str, Any] =get_serialized_examples(__a )
with tf.io.TFRecordWriter(__a ) as out_file:
for i in range(len(__a ) ):
lowerCamelCase__: Optional[Any] =serialized_examples[i]
out_file.write(__a )
print("Wrote file {} containing {} records".format(__a , __a ) )
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=__a )
if __name__ == "__main__":
__A = parse_args()
main(args)
| 59 |
import argparse
import os
import pickle
import sys
import torch
from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl
from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils
from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
logging.set_verbosity_info()
# We do this to be able to load python 2 datasets pickles
# See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918
__A = data_utils.TransfoXLTokenizer
__A = data_utils.TransfoXLCorpus
__A = data_utils
__A = data_utils
def lowerCAmelCase_ ( __a , __a , __a , __a ) -> List[str]:
"""simple docstring"""
if transfo_xl_dataset_file:
# Convert a pre-processed corpus (see original TensorFlow repo)
with open(__a , "rb" ) as fp:
lowerCamelCase__: Optional[Any] =pickle.load(__a , encoding="latin1" )
# Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term)
lowerCamelCase__: Union[str, Any] =pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["pretrained_vocab_file"]
print(F"""Save vocabulary to {pytorch_vocab_dump_path}""" )
lowerCamelCase__: Any =corpus.vocab.__dict__
torch.save(__a , __a )
lowerCamelCase__: Dict =corpus.__dict__
corpus_dict_no_vocab.pop("vocab" , __a )
lowerCamelCase__: List[str] =pytorch_dump_folder_path + "/" + CORPUS_NAME
print(F"""Save dataset to {pytorch_dataset_dump_path}""" )
torch.save(__a , __a )
if tf_checkpoint_path:
# Convert a pre-trained TensorFlow model
lowerCamelCase__: Optional[Any] =os.path.abspath(__a )
lowerCamelCase__: Dict =os.path.abspath(__a )
print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" )
# Initialise PyTorch model
if transfo_xl_config_file == "":
lowerCamelCase__: int =TransfoXLConfig()
else:
lowerCamelCase__: Any =TransfoXLConfig.from_json_file(__a )
print(F"""Building PyTorch model from configuration: {config}""" )
lowerCamelCase__: List[Any] =TransfoXLLMHeadModel(__a )
lowerCamelCase__: List[str] =load_tf_weights_in_transfo_xl(__a , __a , __a )
# Save pytorch-model
lowerCamelCase__: List[str] =os.path.join(__a , __a )
lowerCamelCase__: Tuple =os.path.join(__a , __a )
print(F"""Save PyTorch model to {os.path.abspath(__a )}""" )
torch.save(model.state_dict() , __a )
print(F"""Save configuration file to {os.path.abspath(__a )}""" )
with open(__a , "w" , encoding="utf-8" ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
parser.add_argument(
"--pytorch_dump_folder_path",
default=None,
type=str,
required=True,
help="Path to the folder to store the PyTorch model or dataset/vocab.",
)
parser.add_argument(
"--tf_checkpoint_path",
default="",
type=str,
help="An optional path to a TensorFlow checkpoint path to be converted.",
)
parser.add_argument(
"--transfo_xl_config_file",
default="",
type=str,
help=(
"An optional config json file corresponding to the pre-trained BERT model. \n"
"This specifies the model architecture."
),
)
parser.add_argument(
"--transfo_xl_dataset_file",
default="",
type=str,
help="An optional dataset file to be converted in a vocabulary.",
)
__A = parser.parse_args()
convert_transfo_xl_checkpoint_to_pytorch(
args.tf_checkpoint_path,
args.transfo_xl_config_file,
args.pytorch_dump_folder_path,
args.transfo_xl_dataset_file,
)
| 59 | 1 |
import argparse
import tensorflow as tf
import torch
from transformers import BertConfig, BertForMaskedLM
from transformers.models.bert.modeling_bert import (
BertIntermediate,
BertLayer,
BertOutput,
BertPooler,
BertSelfAttention,
BertSelfOutput,
)
from transformers.utils import logging
logging.set_verbosity_info()
def lowerCAmelCase_ ( __a , __a , __a ) -> Dict:
"""simple docstring"""
def get_masked_lm_array(__a ):
lowerCamelCase__: int =F"""masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE"""
lowerCamelCase__: Union[str, Any] =tf.train.load_variable(__a , __a )
if "kernel" in name:
lowerCamelCase__: Any =array.transpose()
return torch.from_numpy(__a )
def get_encoder_array(__a ):
lowerCamelCase__: Dict =F"""encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE"""
lowerCamelCase__: Dict =tf.train.load_variable(__a , __a )
if "kernel" in name:
lowerCamelCase__: List[Any] =array.transpose()
return torch.from_numpy(__a )
def get_encoder_layer_array(__a , __a ):
lowerCamelCase__: List[Any] =F"""encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE"""
lowerCamelCase__: Tuple =tf.train.load_variable(__a , __a )
if "kernel" in name:
lowerCamelCase__: Any =array.transpose()
return torch.from_numpy(__a )
def get_encoder_attention_layer_array(__a , __a , __a ):
lowerCamelCase__: Any =F"""encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE"""
lowerCamelCase__: Union[str, Any] =tf.train.load_variable(__a , __a )
lowerCamelCase__: Any =array.reshape(__a )
if "kernel" in name:
lowerCamelCase__: int =array.transpose()
return torch.from_numpy(__a )
print(F"""Loading model based on config from {config_path}...""" )
lowerCamelCase__: Optional[int] =BertConfig.from_json_file(__a )
lowerCamelCase__: Optional[Any] =BertForMaskedLM(__a )
# Layers
for layer_index in range(0 , config.num_hidden_layers ):
lowerCamelCase__: BertLayer =model.bert.encoder.layer[layer_index]
# Self-attention
lowerCamelCase__: BertSelfAttention =layer.attention.self
lowerCamelCase__: Dict =get_encoder_attention_layer_array(
__a , "_query_dense/kernel" , self_attn.query.weight.data.shape )
lowerCamelCase__: List[Any] =get_encoder_attention_layer_array(
__a , "_query_dense/bias" , self_attn.query.bias.data.shape )
lowerCamelCase__: Dict =get_encoder_attention_layer_array(
__a , "_key_dense/kernel" , self_attn.key.weight.data.shape )
lowerCamelCase__: Union[str, Any] =get_encoder_attention_layer_array(
__a , "_key_dense/bias" , self_attn.key.bias.data.shape )
lowerCamelCase__: str =get_encoder_attention_layer_array(
__a , "_value_dense/kernel" , self_attn.value.weight.data.shape )
lowerCamelCase__: List[Any] =get_encoder_attention_layer_array(
__a , "_value_dense/bias" , self_attn.value.bias.data.shape )
# Self-attention Output
lowerCamelCase__: BertSelfOutput =layer.attention.output
lowerCamelCase__: str =get_encoder_attention_layer_array(
__a , "_output_dense/kernel" , self_output.dense.weight.data.shape )
lowerCamelCase__: Optional[Any] =get_encoder_attention_layer_array(
__a , "_output_dense/bias" , self_output.dense.bias.data.shape )
lowerCamelCase__: Optional[int] =get_encoder_layer_array(__a , "_attention_layer_norm/gamma" )
lowerCamelCase__: Union[str, Any] =get_encoder_layer_array(__a , "_attention_layer_norm/beta" )
# Intermediate
lowerCamelCase__: BertIntermediate =layer.intermediate
lowerCamelCase__: List[str] =get_encoder_layer_array(__a , "_intermediate_dense/kernel" )
lowerCamelCase__: str =get_encoder_layer_array(__a , "_intermediate_dense/bias" )
# Output
lowerCamelCase__: BertOutput =layer.output
lowerCamelCase__: Dict =get_encoder_layer_array(__a , "_output_dense/kernel" )
lowerCamelCase__: Union[str, Any] =get_encoder_layer_array(__a , "_output_dense/bias" )
lowerCamelCase__: Optional[Any] =get_encoder_layer_array(__a , "_output_layer_norm/gamma" )
lowerCamelCase__: int =get_encoder_layer_array(__a , "_output_layer_norm/beta" )
# Embeddings
lowerCamelCase__: Dict =get_encoder_array("_position_embedding_layer/embeddings" )
lowerCamelCase__: Tuple =get_encoder_array("_type_embedding_layer/embeddings" )
lowerCamelCase__: Dict =get_encoder_array("_embedding_norm_layer/gamma" )
lowerCamelCase__: List[str] =get_encoder_array("_embedding_norm_layer/beta" )
# LM Head
lowerCamelCase__: Optional[int] =model.cls.predictions.transform
lowerCamelCase__: str =get_masked_lm_array("dense/kernel" )
lowerCamelCase__: Union[str, Any] =get_masked_lm_array("dense/bias" )
lowerCamelCase__: int =get_masked_lm_array("layer_norm/gamma" )
lowerCamelCase__: Optional[int] =get_masked_lm_array("layer_norm/beta" )
lowerCamelCase__: str =get_masked_lm_array("embedding_table" )
# Pooling
lowerCamelCase__: List[Any] =BertPooler(config=__a )
lowerCamelCase__: BertPooler =get_encoder_array("_pooler_layer/kernel" )
lowerCamelCase__: BertPooler =get_encoder_array("_pooler_layer/bias" )
# Export final model
model.save_pretrained(__a )
# Integration test - should load without any errors ;)
lowerCamelCase__: Tuple =BertForMaskedLM.from_pretrained(__a )
print(new_model.eval() )
print("Model conversion was done sucessfully!" )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
parser.add_argument(
"--tf_checkpoint_path", type=str, required=True, help="Path to the TensorFlow Token Dropping checkpoint path."
)
parser.add_argument(
"--bert_config_file",
type=str,
required=True,
help="The config json file corresponding to the BERT model. This specifies the model architecture.",
)
parser.add_argument(
"--pytorch_dump_path",
type=str,
required=True,
help="Path to the output PyTorch model.",
)
__A = parser.parse_args()
convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
| 59 |
from collections import UserDict
from typing import List, Union
from ..utils import (
add_end_docstrings,
is_tf_available,
is_torch_available,
is_vision_available,
logging,
requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_vision_available():
from PIL import Image
from ..image_utils import load_image
if is_torch_available():
from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
if is_tf_available():
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
from ..tf_utils import stable_softmax
__A = logging.get_logger(__name__)
@add_end_docstrings(__SCREAMING_SNAKE_CASE )
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__(self : Optional[int] , **UpperCAmelCase_ : List[Any]) ->List[str]:
'''simple docstring'''
super().__init__(**UpperCAmelCase_)
requires_backends(self , "vision")
self.check_model_type(
TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
if self.framework == "tf"
else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING)
def __call__(self : List[str] , UpperCAmelCase_ : Union[str, List[str], "Image", List["Image"]] , **UpperCAmelCase_ : List[Any]) ->Tuple:
'''simple docstring'''
return super().__call__(UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[Any] , **UpperCAmelCase_ : Optional[int]) ->Any:
'''simple docstring'''
lowerCamelCase__: Optional[int] ={}
if "candidate_labels" in kwargs:
lowerCamelCase__: Tuple =kwargs["candidate_labels"]
if "hypothesis_template" in kwargs:
lowerCamelCase__: Tuple =kwargs["hypothesis_template"]
return preprocess_params, {}, {}
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Optional[Any]="This is a photo of {}.") ->str:
'''simple docstring'''
lowerCamelCase__: int =load_image(UpperCAmelCase_)
lowerCamelCase__: Any =self.image_processor(images=[image] , return_tensors=self.framework)
lowerCamelCase__: Any =candidate_labels
lowerCamelCase__: List[str] =[hypothesis_template.format(UpperCAmelCase_) for x in candidate_labels]
lowerCamelCase__: int =self.tokenizer(UpperCAmelCase_ , return_tensors=self.framework , padding=UpperCAmelCase_)
lowerCamelCase__: str =[text_inputs]
return inputs
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Any) ->Tuple:
'''simple docstring'''
lowerCamelCase__: int =model_inputs.pop("candidate_labels")
lowerCamelCase__: List[str] =model_inputs.pop("text_inputs")
if isinstance(text_inputs[0] , UpperCAmelCase_):
lowerCamelCase__: List[Any] =text_inputs[0]
else:
# Batching case.
lowerCamelCase__: List[Any] =text_inputs[0][0]
lowerCamelCase__: List[str] =self.model(**UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: str ={
"candidate_labels": candidate_labels,
"logits": outputs.logits_per_image,
}
return model_outputs
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Union[str, Any]) ->int:
'''simple docstring'''
lowerCamelCase__: List[Any] =model_outputs.pop("candidate_labels")
lowerCamelCase__: Optional[int] =model_outputs["logits"][0]
if self.framework == "pt":
lowerCamelCase__: Optional[Any] =logits.softmax(dim=-1).squeeze(-1)
lowerCamelCase__: Optional[Any] =probs.tolist()
if not isinstance(UpperCAmelCase_ , UpperCAmelCase_):
lowerCamelCase__: Optional[int] =[scores]
elif self.framework == "tf":
lowerCamelCase__: List[str] =stable_softmax(UpperCAmelCase_ , axis=-1)
lowerCamelCase__: Optional[int] =probs.numpy().tolist()
else:
raise ValueError(F"""Unsupported framework: {self.framework}""")
lowerCamelCase__: Optional[int] =[
{"score": score, "label": candidate_label}
for score, candidate_label in sorted(zip(UpperCAmelCase_ , UpperCAmelCase_) , key=lambda UpperCAmelCase_: -x[0])
]
return result
| 59 | 1 |
def lowerCAmelCase_ ( __a ) -> int:
"""simple docstring"""
lowerCamelCase__: Optional[Any] =[1]
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =0, 0, 0
lowerCamelCase__: Union[str, Any] =ugly_nums[ia] * 2
lowerCamelCase__: Tuple =ugly_nums[ia] * 3
lowerCamelCase__: List[Any] =ugly_nums[ia] * 5
for _ in range(1 , __a ):
lowerCamelCase__: Tuple =min(__a , __a , __a )
ugly_nums.append(__a )
if next_num == next_a:
ia += 1
lowerCamelCase__: Optional[Any] =ugly_nums[ia] * 2
if next_num == next_a:
ia += 1
lowerCamelCase__: List[Any] =ugly_nums[ia] * 3
if next_num == next_a:
ia += 1
lowerCamelCase__: Union[str, Any] =ugly_nums[ia] * 5
return ugly_nums[-1]
if __name__ == "__main__":
from doctest import testmod
testmod(verbose=True)
print(f'{ugly_numbers(200) = }')
| 59 |
import json
import os
from dataclasses import dataclass
from functools import partial
from typing import Callable
import flax.linen as nn
import jax
import jax.numpy as jnp
import joblib
import optax
import wandb
from flax import jax_utils, struct, traverse_util
from flax.serialization import from_bytes, to_bytes
from flax.training import train_state
from flax.training.common_utils import shard
from tqdm.auto import tqdm
from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering
from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = 42
lowercase_ = jnp.floataa
lowercase_ = True
def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]:
'''simple docstring'''
super().setup()
lowerCamelCase__: int =nn.Dense(5 , dtype=self.dtype)
def __call__(self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Any) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =super().__call__(*UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: int =self.cls(outputs[2])
return outputs[:2] + (cls_out,)
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = FlaxBigBirdForNaturalQuestionsModule
def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a ) -> Tuple:
"""simple docstring"""
def cross_entropy(__a , __a , __a=None ):
lowerCamelCase__: Tuple =logits.shape[-1]
lowerCamelCase__: Tuple =(labels[..., None] == jnp.arange(__a )[None]).astype("f4" )
lowerCamelCase__: str =jax.nn.log_softmax(__a , axis=-1 )
lowerCamelCase__: Optional[Any] =-jnp.sum(labels * logits , axis=-1 )
if reduction is not None:
lowerCamelCase__: Optional[Any] =reduction(__a )
return loss
lowerCamelCase__: str =partial(__a , reduction=jnp.mean )
lowerCamelCase__: str =cross_entropy(__a , __a )
lowerCamelCase__: Optional[int] =cross_entropy(__a , __a )
lowerCamelCase__: Optional[Any] =cross_entropy(__a , __a )
return (start_loss + end_loss + pooled_loss) / 3
@dataclass
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
lowercase_ = "google/bigbird-roberta-base"
lowercase_ = 3000
lowercase_ = 1_0500
lowercase_ = 128
lowercase_ = 3
lowercase_ = 1
lowercase_ = 5
# tx_args
lowercase_ = 3E-5
lowercase_ = 0.0
lowercase_ = 2_0000
lowercase_ = 0.0095
lowercase_ = "bigbird-roberta-natural-questions"
lowercase_ = "training-expt"
lowercase_ = "data/nq-training.jsonl"
lowercase_ = "data/nq-validation.jsonl"
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[str]:
'''simple docstring'''
os.makedirs(self.base_dir , exist_ok=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =os.path.join(self.base_dir , self.save_dir)
lowerCamelCase__: List[str] =self.batch_size_per_device * jax.device_count()
@dataclass
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
lowercase_ = 42
lowercase_ = 4096 # no dynamic padding on TPUs
def __call__(self : List[Any] , UpperCAmelCase_ : Optional[Any]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =self.collate_fn(UpperCAmelCase_)
lowerCamelCase__: List[Any] =jax.tree_util.tree_map(UpperCAmelCase_ , UpperCAmelCase_)
return batch
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List[str]) ->List[Any]:
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: List[Any] =self.fetch_inputs(features["input_ids"])
lowerCamelCase__: Union[str, Any] ={
"input_ids": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa),
"attention_mask": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa),
"start_labels": jnp.array(features["start_token"] , dtype=jnp.intaa),
"end_labels": jnp.array(features["end_token"] , dtype=jnp.intaa),
"pooled_labels": jnp.array(features["category"] , dtype=jnp.intaa),
}
return batch
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : list) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Tuple =[self._fetch_inputs(UpperCAmelCase_) for ids in input_ids]
return zip(*UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : list) ->Any:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =[1 for _ in range(len(UpperCAmelCase_))]
while len(UpperCAmelCase_) < self.max_length:
input_ids.append(self.pad_id)
attention_mask.append(0)
return input_ids, attention_mask
def lowerCAmelCase_ ( __a , __a , __a=None ) -> str:
"""simple docstring"""
if seed is not None:
lowerCamelCase__: Any =dataset.shuffle(seed=__a )
for i in range(len(__a ) // batch_size ):
lowerCamelCase__: Any =dataset[i * batch_size : (i + 1) * batch_size]
yield dict(__a )
@partial(jax.pmap , axis_name="batch" )
def lowerCAmelCase_ ( __a , __a , **__a ) -> List[str]:
"""simple docstring"""
def loss_fn(__a ):
lowerCamelCase__: Optional[int] =model_inputs.pop("start_labels" )
lowerCamelCase__: int =model_inputs.pop("end_labels" )
lowerCamelCase__: List[str] =model_inputs.pop("pooled_labels" )
lowerCamelCase__: Optional[int] =state.apply_fn(**__a , params=__a , dropout_rng=__a , train=__a )
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[Any] =outputs
return state.loss_fn(
__a , __a , __a , __a , __a , __a , )
lowerCamelCase__ , lowerCamelCase__: int =jax.random.split(__a )
lowerCamelCase__: Optional[Any] =jax.value_and_grad(__a )
lowerCamelCase__ , lowerCamelCase__: List[str] =grad_fn(state.params )
lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" )
lowerCamelCase__: List[str] =jax.lax.pmean(__a , "batch" )
lowerCamelCase__: List[str] =state.apply_gradients(grads=__a )
return state, metrics, new_drp_rng
@partial(jax.pmap , axis_name="batch" )
def lowerCAmelCase_ ( __a , **__a ) -> List[Any]:
"""simple docstring"""
lowerCamelCase__: int =model_inputs.pop("start_labels" )
lowerCamelCase__: List[str] =model_inputs.pop("end_labels" )
lowerCamelCase__: int =model_inputs.pop("pooled_labels" )
lowerCamelCase__: Optional[Any] =state.apply_fn(**__a , params=state.params , train=__a )
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[str] =outputs
lowerCamelCase__: Optional[int] =state.loss_fn(__a , __a , __a , __a , __a , __a )
lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" )
return metrics
class _SCREAMING_SNAKE_CASE ( train_state.TrainState ):
'''simple docstring'''
lowercase_ = struct.field(pytree_node=__SCREAMING_SNAKE_CASE )
@dataclass
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = None
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int=None) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Dict =model.params
lowerCamelCase__: Tuple =TrainState.create(
apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , loss_fn=UpperCAmelCase_ , )
if ckpt_dir is not None:
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =restore_checkpoint(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Tuple ={
"lr": args.lr,
"init_lr": args.init_lr,
"warmup_steps": args.warmup_steps,
"num_train_steps": num_train_steps,
"weight_decay": args.weight_decay,
}
lowerCamelCase__ , lowerCamelCase__: List[Any] =build_tx(**UpperCAmelCase_)
lowerCamelCase__: str =train_state.TrainState(
step=UpperCAmelCase_ , apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , opt_state=UpperCAmelCase_ , )
lowerCamelCase__: Tuple =args
lowerCamelCase__: Tuple =data_collator
lowerCamelCase__: str =lr
lowerCamelCase__: Dict =params
lowerCamelCase__: List[str] =jax_utils.replicate(UpperCAmelCase_)
return state
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Tuple =self.args
lowerCamelCase__: Any =len(UpperCAmelCase_) // args.batch_size
lowerCamelCase__: List[str] =jax.random.PRNGKey(0)
lowerCamelCase__: Optional[Any] =jax.random.split(UpperCAmelCase_ , jax.device_count())
for epoch in range(args.max_epochs):
lowerCamelCase__: Union[str, Any] =jnp.array(0 , dtype=jnp.floataa)
lowerCamelCase__: str =get_batched_dataset(UpperCAmelCase_ , args.batch_size , seed=UpperCAmelCase_)
lowerCamelCase__: Dict =0
for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc=F"""Running EPOCH-{epoch}"""):
lowerCamelCase__: List[str] =self.data_collator(UpperCAmelCase_)
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.train_step_fn(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_)
running_loss += jax_utils.unreplicate(metrics["loss"])
i += 1
if i % args.logging_steps == 0:
lowerCamelCase__: Optional[int] =jax_utils.unreplicate(state.step)
lowerCamelCase__: List[Any] =running_loss.item() / i
lowerCamelCase__: Tuple =self.scheduler_fn(state_step - 1)
lowerCamelCase__: Union[str, Any] =self.evaluate(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Dict ={
"step": state_step.item(),
"eval_loss": eval_loss.item(),
"tr_loss": tr_loss,
"lr": lr.item(),
}
tqdm.write(str(UpperCAmelCase_))
self.logger.log(UpperCAmelCase_ , commit=UpperCAmelCase_)
if i % args.save_steps == 0:
self.save_checkpoint(args.save_dir + F"""-e{epoch}-s{i}""" , state=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str) ->Any:
'''simple docstring'''
lowerCamelCase__: List[Any] =get_batched_dataset(UpperCAmelCase_ , self.args.batch_size)
lowerCamelCase__: List[str] =len(UpperCAmelCase_) // self.args.batch_size
lowerCamelCase__: str =jnp.array(0 , dtype=jnp.floataa)
lowerCamelCase__: Optional[Any] =0
for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc="Evaluating ... "):
lowerCamelCase__: int =self.data_collator(UpperCAmelCase_)
lowerCamelCase__: str =self.val_step_fn(UpperCAmelCase_ , **UpperCAmelCase_)
running_loss += jax_utils.unreplicate(metrics["loss"])
i += 1
return running_loss / i
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int]) ->int:
'''simple docstring'''
lowerCamelCase__: Any =jax_utils.unreplicate(UpperCAmelCase_)
print(F"""SAVING CHECKPOINT IN {save_dir}""" , end=" ... ")
self.model_save_fn(UpperCAmelCase_ , params=state.params)
with open(os.path.join(UpperCAmelCase_ , "opt_state.msgpack") , "wb") as f:
f.write(to_bytes(state.opt_state))
joblib.dump(self.args , os.path.join(UpperCAmelCase_ , "args.joblib"))
joblib.dump(self.data_collator , os.path.join(UpperCAmelCase_ , "data_collator.joblib"))
with open(os.path.join(UpperCAmelCase_ , "training_state.json") , "w") as f:
json.dump({"step": state.step.item()} , UpperCAmelCase_)
print("DONE")
def lowerCAmelCase_ ( __a , __a ) -> str:
"""simple docstring"""
print(F"""RESTORING CHECKPOINT FROM {save_dir}""" , end=" ... " )
with open(os.path.join(__a , "flax_model.msgpack" ) , "rb" ) as f:
lowerCamelCase__: Tuple =from_bytes(state.params , f.read() )
with open(os.path.join(__a , "opt_state.msgpack" ) , "rb" ) as f:
lowerCamelCase__: Optional[int] =from_bytes(state.opt_state , f.read() )
lowerCamelCase__: Any =joblib.load(os.path.join(__a , "args.joblib" ) )
lowerCamelCase__: Union[str, Any] =joblib.load(os.path.join(__a , "data_collator.joblib" ) )
with open(os.path.join(__a , "training_state.json" ) , "r" ) as f:
lowerCamelCase__: Optional[Any] =json.load(__a )
lowerCamelCase__: Any =training_state["step"]
print("DONE" )
return params, opt_state, step, args, data_collator
def lowerCAmelCase_ ( __a , __a , __a , __a ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase__: int =num_train_steps - warmup_steps
lowerCamelCase__: str =optax.linear_schedule(init_value=__a , end_value=__a , transition_steps=__a )
lowerCamelCase__: Optional[Any] =optax.linear_schedule(init_value=__a , end_value=1e-7 , transition_steps=__a )
lowerCamelCase__: List[Any] =optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] )
return lr
def lowerCAmelCase_ ( __a , __a , __a , __a , __a ) -> str:
"""simple docstring"""
def weight_decay_mask(__a ):
lowerCamelCase__: List[str] =traverse_util.flatten_dict(__a )
lowerCamelCase__: List[str] ={k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()}
return traverse_util.unflatten_dict(__a )
lowerCamelCase__: Optional[Any] =scheduler_fn(__a , __a , __a , __a )
lowerCamelCase__: Tuple =optax.adamw(learning_rate=__a , weight_decay=__a , mask=__a )
return tx, lr
| 59 | 1 |
import os
import time
import warnings
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Union
import torch
from filelock import FileLock
from torch.utils.data import Dataset
from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures
__A = logging.get_logger(__name__)
@dataclass
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
lowercase_ = field(metadata={"help": "The name of the task to train on: " + ", ".join(glue_processors.keys() )} )
lowercase_ = field(
metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."} )
lowercase_ = 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."
)
} , )
lowercase_ = field(
default=__SCREAMING_SNAKE_CASE , metadata={"help": "Overwrite the cached training and evaluation sets"} )
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Any:
'''simple docstring'''
lowerCamelCase__: int =self.task_name.lower()
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = "train"
lowercase_ = "dev"
lowercase_ = "test"
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
def __init__(self : Union[str, Any] , UpperCAmelCase_ : GlueDataTrainingArguments , UpperCAmelCase_ : PreTrainedTokenizerBase , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : Union[str, Split] = Split.train , UpperCAmelCase_ : Optional[str] = None , ) ->List[str]:
'''simple docstring'''
warnings.warn(
"This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets "
"library. You can have a look at this example script for pointers: "
"https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py" , UpperCAmelCase_ , )
lowerCamelCase__: Tuple =args
lowerCamelCase__: Union[str, Any] =glue_processors[args.task_name]()
lowerCamelCase__: List[str] =glue_output_modes[args.task_name]
if isinstance(UpperCAmelCase_ , UpperCAmelCase_):
try:
lowerCamelCase__: str =Split[mode]
except KeyError:
raise KeyError("mode is not a valid split name")
# Load data features from cache or dataset file
lowerCamelCase__: Tuple =os.path.join(
cache_dir if cache_dir is not None else args.data_dir , F"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}""" , )
lowerCamelCase__: List[Any] =self.processor.get_labels()
if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
"RobertaTokenizer",
"RobertaTokenizerFast",
"XLMRobertaTokenizer",
"BartTokenizer",
"BartTokenizerFast",
):
# HACK(label indices are swapped in RoBERTa pretrained model)
lowerCamelCase__ , lowerCamelCase__: List[str] =label_list[2], label_list[1]
lowerCamelCase__: Dict =label_list
# Make sure only the first process in distributed training processes the dataset,
# and the others will use the cache.
lowerCamelCase__: Any =cached_features_file + ".lock"
with FileLock(UpperCAmelCase_):
if os.path.exists(UpperCAmelCase_) and not args.overwrite_cache:
lowerCamelCase__: Tuple =time.time()
lowerCamelCase__: str =torch.load(UpperCAmelCase_)
logger.info(
F"""Loading features from cached file {cached_features_file} [took %.3f s]""" , time.time() - start)
else:
logger.info(F"""Creating features from dataset file at {args.data_dir}""")
if mode == Split.dev:
lowerCamelCase__: Tuple =self.processor.get_dev_examples(args.data_dir)
elif mode == Split.test:
lowerCamelCase__: Union[str, Any] =self.processor.get_test_examples(args.data_dir)
else:
lowerCamelCase__: List[str] =self.processor.get_train_examples(args.data_dir)
if limit_length is not None:
lowerCamelCase__: List[str] =examples[:limit_length]
lowerCamelCase__: Dict =glue_convert_examples_to_features(
UpperCAmelCase_ , UpperCAmelCase_ , max_length=args.max_seq_length , label_list=UpperCAmelCase_ , output_mode=self.output_mode , )
lowerCamelCase__: List[str] =time.time()
torch.save(self.features , UpperCAmelCase_)
# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
logger.info(
F"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]""")
def __len__(self : Dict) ->Optional[Any]:
'''simple docstring'''
return len(self.features)
def __getitem__(self : List[str] , UpperCAmelCase_ : str) ->InputFeatures:
'''simple docstring'''
return self.features[i]
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->List[str]:
'''simple docstring'''
return self.label_list
| 59 |
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = ["image_processor", "tokenizer"]
lowercase_ = "ChineseCLIPImageProcessor"
lowercase_ = ("BertTokenizer", "BertTokenizerFast")
def __init__(self : Any , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Union[str, Any]=None , **UpperCAmelCase_ : str) ->Dict:
'''simple docstring'''
lowerCamelCase__: str =None
if "feature_extractor" in kwargs:
warnings.warn(
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
" instead." , UpperCAmelCase_ , )
lowerCamelCase__: Tuple =kwargs.pop("feature_extractor")
lowerCamelCase__: Optional[int] =image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError("You need to specify an `image_processor`.")
if tokenizer is None:
raise ValueError("You need to specify a `tokenizer`.")
super().__init__(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Optional[int] =self.image_processor
def __call__(self : int , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[int]:
'''simple docstring'''
if text is None and images is None:
raise ValueError("You have to specify either text or images. Both cannot be none.")
if text is not None:
lowerCamelCase__: Dict =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if images is not None:
lowerCamelCase__: List[str] =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if text is not None and images is not None:
lowerCamelCase__: Union[str, Any] =image_features.pixel_values
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int) ->str:
'''simple docstring'''
return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any]) ->Dict:
'''simple docstring'''
return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_)
@property
def SCREAMING_SNAKE_CASE_ (self : int) ->List[str]:
'''simple docstring'''
lowerCamelCase__: str =self.tokenizer.model_input_names
lowerCamelCase__: Union[str, Any] =self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
@property
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str:
'''simple docstring'''
warnings.warn(
"`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , UpperCAmelCase_ , )
return self.image_processor_class
| 59 | 1 |
import re
from filelock import FileLock
try:
import nltk
__A = True
except (ImportError, ModuleNotFoundError):
__A = False
if NLTK_AVAILABLE:
with FileLock(".lock") as lock:
nltk.download("punkt", quiet=True)
def lowerCAmelCase_ ( __a ) -> str:
"""simple docstring"""
re.sub("<n>" , "" , __a ) # remove pegasus newline char
assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)"
return "\n".join(nltk.sent_tokenize(__a ) )
| 59 |
from math import ceil, sqrt
def lowerCAmelCase_ ( __a = 1000000 ) -> int:
"""simple docstring"""
lowerCamelCase__: Any =0
for outer_width in range(3 , (limit // 4) + 2 ):
if outer_width**2 > limit:
lowerCamelCase__: Optional[int] =max(ceil(sqrt(outer_width**2 - limit ) ) , 1 )
else:
lowerCamelCase__: Tuple =1
if (outer_width - hole_width_lower_bound) % 2:
hole_width_lower_bound += 1
answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1
return answer
if __name__ == "__main__":
print(f'{solution() = }')
| 59 | 1 |
__A = {
"A": ["B", "C", "E"],
"B": ["A", "D", "E"],
"C": ["A", "F", "G"],
"D": ["B"],
"E": ["A", "B", "D"],
"F": ["C"],
"G": ["C"],
}
def lowerCAmelCase_ ( __a , __a , __a ) -> list[str]:
"""simple docstring"""
lowerCamelCase__: Optional[int] =set()
# keep track of all the paths to be checked
lowerCamelCase__: Tuple =[[start]]
# return path if start is goal
if start == goal:
return [start]
# keeps looping until all possible paths have been checked
while queue:
# pop the first path from the queue
lowerCamelCase__: Optional[Any] =queue.pop(0 )
# get the last node from the path
lowerCamelCase__: Any =path[-1]
if node not in explored:
lowerCamelCase__: Tuple =graph[node]
# go through all neighbour nodes, construct a new path and
# push it into the queue
for neighbour in neighbours:
lowerCamelCase__: Any =list(__a )
new_path.append(__a )
queue.append(__a )
# return path if neighbour is goal
if neighbour == goal:
return new_path
# mark node as explored
explored.add(__a )
# in case there's no path between the 2 nodes
return []
def lowerCAmelCase_ ( __a , __a , __a ) -> int:
"""simple docstring"""
if not graph or start not in graph or target not in graph:
return -1
if start == target:
return 0
lowerCamelCase__: Tuple =[start]
lowerCamelCase__: str =set(__a )
# Keep tab on distances from `start` node.
lowerCamelCase__: Any ={start: 0, target: -1}
while queue:
lowerCamelCase__: List[Any] =queue.pop(0 )
if node == target:
lowerCamelCase__: List[str] =(
dist[node] if dist[target] == -1 else min(dist[target] , dist[node] )
)
for adjacent in graph[node]:
if adjacent not in visited:
visited.add(__a )
queue.append(__a )
lowerCamelCase__: Optional[int] =dist[node] + 1
return dist[target]
if __name__ == "__main__":
print(bfs_shortest_path(demo_graph, "G", "D")) # returns ['G', 'C', 'A', 'B', 'D']
print(bfs_shortest_path_distance(demo_graph, "G", "D")) # returns 4
| 59 |
def lowerCAmelCase_ ( __a = 50000000 ) -> int:
"""simple docstring"""
lowerCamelCase__: Any =set()
lowerCamelCase__: int =int((limit - 24) ** (1 / 2) )
lowerCamelCase__: Tuple =set(range(3 , prime_square_limit + 1 , 2 ) )
primes.add(2 )
for p in range(3 , prime_square_limit + 1 , 2 ):
if p not in primes:
continue
primes.difference_update(set(range(p * p , prime_square_limit + 1 , __a ) ) )
for primea in primes:
lowerCamelCase__: Optional[int] =primea * primea
for primea in primes:
lowerCamelCase__: List[str] =primea * primea * primea
if square + cube >= limit - 16:
break
for primea in primes:
lowerCamelCase__: int =primea * primea * primea * primea
lowerCamelCase__: Optional[Any] =square + cube + tetr
if total >= limit:
break
ret.add(__a )
return len(__a )
if __name__ == "__main__":
print(f'{solution() = }')
| 59 | 1 |
def lowerCAmelCase_ ( __a ) -> bool:
"""simple docstring"""
lowerCamelCase__: set[int] =set()
# To detect a back edge, keep track of vertices currently in the recursion stack
lowerCamelCase__: set[int] =set()
return any(
node not in visited and depth_first_search(__a , __a , __a , __a )
for node in graph )
def lowerCAmelCase_ ( __a , __a , __a , __a ) -> bool:
"""simple docstring"""
visited.add(__a )
rec_stk.add(__a )
for node in graph[vertex]:
if node not in visited:
if depth_first_search(__a , __a , __a , __a ):
return True
elif node in rec_stk:
return True
# The node needs to be removed from recursion stack before function ends
rec_stk.remove(__a )
return False
if __name__ == "__main__":
from doctest import testmod
testmod()
| 59 |
from __future__ import annotations
from decimal import Decimal
from math import * # noqa: F403
from sympy import diff
def lowerCAmelCase_ ( __a , __a , __a = 10**-10 ) -> float:
"""simple docstring"""
lowerCamelCase__: List[str] =a
while True:
lowerCamelCase__: Optional[Any] =Decimal(__a ) - (
Decimal(eval(__a ) ) / Decimal(eval(str(diff(__a ) ) ) ) # noqa: S307
)
# This number dictates the accuracy of the answer
if abs(eval(__a ) ) < precision: # noqa: S307
return float(__a )
# Let's Execute
if __name__ == "__main__":
# Find root of trigonometric function
# Find value of pi
print(f'The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}')
# Find root of polynomial
print(f'The root of x**2 - 5*x + 2 = 0 is {newton_raphson("x**2 - 5*x + 2", 0.4)}')
# Find Square Root of 5
print(f'The root of log(x) - 1 = 0 is {newton_raphson("log(x) - 1", 2)}')
# Exponential Roots
print(f'The root of exp(x) - 1 = 0 is {newton_raphson("exp(x) - 1", 0)}')
| 59 | 1 |
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer
from .base import PipelineTool
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = "facebook/bart-large-mnli"
lowercase_ = (
"This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which "
"should be the text to classify, and `labels`, which should be the list of labels to use for classification. "
"It returns the most likely label in the list of provided `labels` for the input text."
)
lowercase_ = "text_classifier"
lowercase_ = AutoTokenizer
lowercase_ = AutoModelForSequenceClassification
lowercase_ = ["text", ["text"]]
lowercase_ = ["text"]
def SCREAMING_SNAKE_CASE_ (self : Any) ->Union[str, Any]:
'''simple docstring'''
super().setup()
lowerCamelCase__: Optional[int] =self.model.config
lowerCamelCase__: Any =-1
for idx, label in config.idalabel.items():
if label.lower().startswith("entail"):
lowerCamelCase__: Union[str, Any] =int(UpperCAmelCase_)
if self.entailment_id == -1:
raise ValueError("Could not determine the entailment ID from the model config, please pass it at init.")
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Union[str, Any]) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Dict =labels
return self.pre_processor(
[text] * len(UpperCAmelCase_) , [F"""This example is {label}""" for label in labels] , return_tensors="pt" , padding="max_length" , )
def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : str) ->Any:
'''simple docstring'''
lowerCamelCase__: List[Any] =outputs.logits
lowerCamelCase__: Optional[Any] =torch.argmax(logits[:, 2]).item()
return self._labels[label_id]
| 59 |
import numpy as np
from numpy import ndarray
from scipy.optimize import Bounds, LinearConstraint, minimize
def lowerCAmelCase_ ( __a ) -> float:
"""simple docstring"""
return np.dot(__a , __a )
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__(self : List[str] , *,
UpperCAmelCase_ : float = np.inf , UpperCAmelCase_ : str = "linear" , UpperCAmelCase_ : float = 0.0 , ) ->None:
'''simple docstring'''
lowerCamelCase__: Dict =regularization
lowerCamelCase__: Any =gamma
if kernel == "linear":
lowerCamelCase__: Dict =self.__linear
elif kernel == "rbf":
if self.gamma == 0:
raise ValueError("rbf kernel requires gamma")
if not isinstance(self.gamma , (float, int)):
raise ValueError("gamma must be float or int")
if not self.gamma > 0:
raise ValueError("gamma must be > 0")
lowerCamelCase__: Tuple =self.__rbf
# in the future, there could be a default value like in sklearn
# sklear: def_gamma = 1/(n_features * X.var()) (wiki)
# previously it was 1/(n_features)
else:
lowerCamelCase__: Optional[Any] =F"""Unknown kernel: {kernel}"""
raise ValueError(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float:
'''simple docstring'''
return np.dot(UpperCAmelCase_ , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float:
'''simple docstring'''
return np.exp(-(self.gamma * norm_squared(vectora - vectora)))
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : list[ndarray] , UpperCAmelCase_ : ndarray) ->None:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =observations
lowerCamelCase__: Optional[int] =classes
# using Wolfe's Dual to calculate w.
# Primal problem: minimize 1/2*norm_squared(w)
# constraint: yn(w . xn + b) >= 1
#
# With l a vector
# Dual problem: maximize sum_n(ln) -
# 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm))
# constraint: self.C >= ln >= 0
# and sum_n(ln*yn) = 0
# Then we get w using w = sum_n(ln*yn*xn)
# At the end we can get b ~= mean(yn - w . xn)
#
# Since we use kernels, we only need l_star to calculate b
# and to classify observations
((lowerCamelCase__) , ): List[str] =np.shape(UpperCAmelCase_)
def to_minimize(UpperCAmelCase_ : ndarray) -> float:
lowerCamelCase__: int =0
((lowerCamelCase__) , ): Optional[Any] =np.shape(UpperCAmelCase_)
for i in range(UpperCAmelCase_):
for j in range(UpperCAmelCase_):
s += (
candidate[i]
* candidate[j]
* classes[i]
* classes[j]
* self.kernel(observations[i] , observations[j])
)
return 1 / 2 * s - sum(UpperCAmelCase_)
lowerCamelCase__: List[Any] =LinearConstraint(UpperCAmelCase_ , 0 , 0)
lowerCamelCase__: str =Bounds(0 , self.regularization)
lowerCamelCase__: Union[str, Any] =minimize(
UpperCAmelCase_ , np.ones(UpperCAmelCase_) , bounds=UpperCAmelCase_ , constraints=[ly_contraint]).x
lowerCamelCase__: str =l_star
# calculating mean offset of separation plane to points
lowerCamelCase__: Tuple =0
for i in range(UpperCAmelCase_):
for j in range(UpperCAmelCase_):
s += classes[i] - classes[i] * self.optimum[i] * self.kernel(
observations[i] , observations[j])
lowerCamelCase__: int =s / n
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : ndarray) ->int:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =sum(
self.optimum[n]
* self.classes[n]
* self.kernel(self.observations[n] , UpperCAmelCase_)
for n in range(len(self.classes)))
return 1 if s + self.offset >= 0 else -1
if __name__ == "__main__":
import doctest
doctest.testmod()
| 59 | 1 |
import functools
import logging
import os
import sys
import threading
from logging import (
CRITICAL, # NOQA
DEBUG, # NOQA
ERROR, # NOQA
FATAL, # NOQA
INFO, # NOQA
NOTSET, # NOQA
WARN, # NOQA
WARNING, # NOQA
)
from typing import Optional
import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib
__A = threading.Lock()
__A = None
__A = {
"debug": logging.DEBUG,
"info": logging.INFO,
"warning": logging.WARNING,
"error": logging.ERROR,
"critical": logging.CRITICAL,
}
__A = logging.WARNING
__A = True
def lowerCAmelCase_ ( ) -> List[str]:
"""simple docstring"""
lowerCamelCase__: Optional[Any] =os.getenv("TRANSFORMERS_VERBOSITY" , __a )
if env_level_str:
if env_level_str in log_levels:
return log_levels[env_level_str]
else:
logging.getLogger().warning(
F"""Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, """
F"""has to be one of: { ", ".join(log_levels.keys() ) }""" )
return _default_log_level
def lowerCAmelCase_ ( ) -> str:
"""simple docstring"""
return __name__.split("." )[0]
def lowerCAmelCase_ ( ) -> logging.Logger:
"""simple docstring"""
return logging.getLogger(_get_library_name() )
def lowerCAmelCase_ ( ) -> None:
"""simple docstring"""
global _default_handler
with _lock:
if _default_handler:
# This library has already configured the library root logger.
return
lowerCamelCase__: Dict =logging.StreamHandler() # Set sys.stderr as stream.
lowerCamelCase__: str =sys.stderr.flush
# Apply our default configuration to the library root logger.
lowerCamelCase__: List[str] =_get_library_root_logger()
library_root_logger.addHandler(_default_handler )
library_root_logger.setLevel(_get_default_logging_level() )
lowerCamelCase__: List[str] =False
def lowerCAmelCase_ ( ) -> None:
"""simple docstring"""
global _default_handler
with _lock:
if not _default_handler:
return
lowerCamelCase__: Optional[Any] =_get_library_root_logger()
library_root_logger.removeHandler(_default_handler )
library_root_logger.setLevel(logging.NOTSET )
lowerCamelCase__: Dict =None
def lowerCAmelCase_ ( ) -> List[Any]:
"""simple docstring"""
return log_levels
def lowerCAmelCase_ ( __a = None ) -> logging.Logger:
"""simple docstring"""
if name is None:
lowerCamelCase__: Any =_get_library_name()
_configure_library_root_logger()
return logging.getLogger(__a )
def lowerCAmelCase_ ( ) -> int:
"""simple docstring"""
_configure_library_root_logger()
return _get_library_root_logger().getEffectiveLevel()
def lowerCAmelCase_ ( __a ) -> None:
"""simple docstring"""
_configure_library_root_logger()
_get_library_root_logger().setLevel(__a )
def lowerCAmelCase_ ( ) -> Optional[int]:
"""simple docstring"""
return set_verbosity(__a )
def lowerCAmelCase_ ( ) -> Dict:
"""simple docstring"""
return set_verbosity(__a )
def lowerCAmelCase_ ( ) -> Optional[Any]:
"""simple docstring"""
return set_verbosity(__a )
def lowerCAmelCase_ ( ) -> Any:
"""simple docstring"""
return set_verbosity(__a )
def lowerCAmelCase_ ( ) -> None:
"""simple docstring"""
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().removeHandler(_default_handler )
def lowerCAmelCase_ ( ) -> None:
"""simple docstring"""
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().addHandler(_default_handler )
def lowerCAmelCase_ ( __a ) -> None:
"""simple docstring"""
_configure_library_root_logger()
assert handler is not None
_get_library_root_logger().addHandler(__a )
def lowerCAmelCase_ ( __a ) -> None:
"""simple docstring"""
_configure_library_root_logger()
assert handler is not None and handler not in _get_library_root_logger().handlers
_get_library_root_logger().removeHandler(__a )
def lowerCAmelCase_ ( ) -> None:
"""simple docstring"""
_configure_library_root_logger()
lowerCamelCase__: Union[str, Any] =False
def lowerCAmelCase_ ( ) -> None:
"""simple docstring"""
_configure_library_root_logger()
lowerCamelCase__: Optional[Any] =True
def lowerCAmelCase_ ( ) -> None:
"""simple docstring"""
lowerCamelCase__: str =_get_library_root_logger().handlers
for handler in handlers:
lowerCamelCase__: Union[str, Any] =logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s" )
handler.setFormatter(__a )
def lowerCAmelCase_ ( ) -> None:
"""simple docstring"""
lowerCamelCase__: Optional[int] =_get_library_root_logger().handlers
for handler in handlers:
handler.setFormatter(__a )
def lowerCAmelCase_ ( self , *__a , **__a ) -> int:
"""simple docstring"""
lowerCamelCase__: List[Any] =os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS" , __a )
if no_advisory_warnings:
return
self.warning(*__a , **__a )
__A = warning_advice
@functools.lru_cache(__a )
def lowerCAmelCase_ ( self , *__a , **__a ) -> str:
"""simple docstring"""
self.warning(*__a , **__a )
__A = warning_once
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__(self : Dict , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Union[str, Any]) ->Any: # pylint: disable=unused-argument
'''simple docstring'''
lowerCamelCase__: Tuple =args[0] if args else None
def __iter__(self : Any) ->List[str]:
'''simple docstring'''
return iter(self._iterator)
def __getattr__(self : Optional[Any] , UpperCAmelCase_ : List[str]) ->Dict:
'''simple docstring'''
def empty_fn(*UpperCAmelCase_ : Any , **UpperCAmelCase_ : List[Any]): # pylint: disable=unused-argument
return
return empty_fn
def __enter__(self : Union[str, Any]) ->List[Any]:
'''simple docstring'''
return self
def __exit__(self : List[str] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Any) ->Dict:
'''simple docstring'''
return
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __call__(self : Dict , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : List[Any]) ->List[str]:
'''simple docstring'''
if _tqdm_active:
return tqdm_lib.tqdm(*UpperCAmelCase_ , **UpperCAmelCase_)
else:
return EmptyTqdm(*UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : int) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Tuple =None
if _tqdm_active:
return tqdm_lib.tqdm.set_lock(*UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Tuple:
'''simple docstring'''
if _tqdm_active:
return tqdm_lib.tqdm.get_lock()
__A = _tqdm_cls()
def lowerCAmelCase_ ( ) -> bool:
"""simple docstring"""
global _tqdm_active
return bool(_tqdm_active )
def lowerCAmelCase_ ( ) -> List[Any]:
"""simple docstring"""
global _tqdm_active
lowerCamelCase__: str =True
hf_hub_utils.enable_progress_bars()
def lowerCAmelCase_ ( ) -> Optional[int]:
"""simple docstring"""
global _tqdm_active
lowerCamelCase__: Dict =False
hf_hub_utils.disable_progress_bars()
| 59 |
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
__A = logging.getLogger(__name__)
def lowerCAmelCase_ ( __a , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = False , ) -> str:
"""simple docstring"""
lowerCamelCase__: int =bnb_quantization_config.load_in_abit
lowerCamelCase__: Any =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." )
lowerCamelCase__: List[Any] =[]
# custom device map
if isinstance(__a , __a ) and len(device_map.keys() ) > 1:
lowerCamelCase__: Optional[int] =[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:
lowerCamelCase__: Any =get_keys_to_not_convert(__a )
# add cpu modules to skip modules only for 4-bit modules
if load_in_abit:
bnb_quantization_config.skip_modules.extend(__a )
lowerCamelCase__: List[str] =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:
lowerCamelCase__: List[Any] =[]
lowerCamelCase__: int =bnb_quantization_config.keep_in_fpaa_modules
modules_to_not_convert.extend(__a )
# compatibility with peft
lowerCamelCase__: List[str] =load_in_abit
lowerCamelCase__: int =load_in_abit
lowerCamelCase__: Tuple =get_parameter_device(__a )
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." )
lowerCamelCase__: Tuple =replace_with_bnb_layers(__a , __a , modules_to_not_convert=__a )
# convert param to the right dtype
lowerCamelCase__: Dict =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:
lowerCamelCase__: str =name.replace(".weight" , "" ).replace(".bias" , "" )
lowerCamelCase__: Optional[Any] =getattr(__a , __a , __a )
if param is not None:
param.to(torch.floataa )
elif torch.is_floating_point(__a ):
param.to(__a )
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():
lowerCamelCase__: str =replace_with_bnb_layers(
__a , __a , modules_to_not_convert=__a )
lowerCamelCase__: Optional[Any] =get_quantized_model_device_map(
__a , __a , __a , max_memory=__a , no_split_module_classes=__a , )
if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
lowerCamelCase__: Any =True
lowerCamelCase__: List[str] =any(x in list(device_map.values() ) for x in ["cpu", "disk"] )
load_checkpoint_in_model(
__a , __a , __a , dtype=bnb_quantization_config.torch_dtype , offload_folder=__a , offload_state_dict=__a , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , )
return dispatch_model(__a , device_map=__a , offload_dir=__a )
def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , __a=None ) -> str:
"""simple docstring"""
if device_map is None:
if torch.cuda.is_available():
lowerCamelCase__: str ={"": 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(__a , __a ):
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'." )
lowerCamelCase__: Optional[int] ={}
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 )
} )
lowerCamelCase__: Optional[Any] ={}
lowerCamelCase__: str =special_dtypes
lowerCamelCase__: List[str] =no_split_module_classes
lowerCamelCase__: Dict =bnb_quantization_config.target_dtype
# get max_memory for each device.
if device_map != "sequential":
lowerCamelCase__: Optional[Any] =get_balanced_memory(
__a , low_zero=(device_map == "balanced_low_0") , max_memory=__a , **__a , )
lowerCamelCase__: Union[str, Any] =max_memory
lowerCamelCase__: Dict =infer_auto_device_map(__a , **__a )
if isinstance(__a , __a ):
# check if don't have any quantized module on the cpu
lowerCamelCase__: Union[str, Any] =bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules
lowerCamelCase__: List[Any] ={
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(
"\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n " )
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 lowerCAmelCase_ ( __a , __a , __a=None , __a=None ) -> Optional[Any]:
"""simple docstring"""
if modules_to_not_convert is None:
lowerCamelCase__: List[Any] =[]
lowerCamelCase__ , lowerCamelCase__: Any =_replace_with_bnb_layers(
__a , __a , __a , __a )
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 lowerCAmelCase_ ( __a , __a , __a=None , __a=None , ) -> List[Any]:
"""simple docstring"""
lowerCamelCase__: Optional[int] =False
for name, module in model.named_children():
if current_key_name is None:
lowerCamelCase__: Optional[Any] =[]
current_key_name.append(__a )
if isinstance(__a , nn.Linear ) and name not in modules_to_not_convert:
# Check if the current key is not in the `modules_to_not_convert`
lowerCamelCase__: List[str] =".".join(__a )
lowerCamelCase__: Optional[Any] =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:
lowerCamelCase__: int =False
break
if proceed:
# Load bnb module with empty weight and replace ``nn.Linear` module
if bnb_quantization_config.load_in_abit:
lowerCamelCase__: Optional[int] =bnb.nn.LinearabitLt(
module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=__a , threshold=bnb_quantization_config.llm_inta_threshold , )
elif bnb_quantization_config.load_in_abit:
lowerCamelCase__: Dict =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" )
lowerCamelCase__: Dict =module.weight.data
if module.bias is not None:
lowerCamelCase__: List[Any] =module.bias.data
bnb_module.requires_grad_(__a )
setattr(__a , __a , __a )
lowerCamelCase__: int =True
if len(list(module.children() ) ) > 0:
lowerCamelCase__ , lowerCamelCase__: List[str] =_replace_with_bnb_layers(
__a , __a , __a , __a )
lowerCamelCase__: Union[str, Any] =has_been_replaced | _has_been_replaced
# Remove the last key for recursion
current_key_name.pop(-1 )
return model, has_been_replaced
def lowerCAmelCase_ ( __a ) -> List[Any]:
"""simple docstring"""
with init_empty_weights():
lowerCamelCase__: Any =deepcopy(__a ) # this has 0 cost since it is done inside `init_empty_weights` context manager`
lowerCamelCase__: str =find_tied_parameters(__a )
# For compatibility with Accelerate < 0.18
if isinstance(__a , __a ):
lowerCamelCase__: int =sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() )
else:
lowerCamelCase__: str =sum(__a , [] )
lowerCamelCase__: str =len(__a ) > 0
# Check if it is a base model
lowerCamelCase__: Optional[Any] =False
if hasattr(__a , "base_model_prefix" ):
lowerCamelCase__: Union[str, Any] =not hasattr(__a , 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
lowerCamelCase__: Optional[int] =list(model.named_children() )
lowerCamelCase__: Optional[int] =[list_modules[-1][0]]
# add last module together with tied weights
lowerCamelCase__: Union[str, Any] =set(__a ) - set(__a )
lowerCamelCase__: List[str] =list(set(__a ) ) + list(__a )
# remove ".weight" from the keys
lowerCamelCase__: List[Any] =[".weight", ".bias"]
lowerCamelCase__: Tuple =[]
for name in list_untouched:
for name_to_remove in names_to_remove:
if name_to_remove in name:
lowerCamelCase__: Optional[Any] =name.replace(__a , "" )
filtered_module_names.append(__a )
return filtered_module_names
def lowerCAmelCase_ ( __a ) -> Tuple:
"""simple docstring"""
for m in model.modules():
if isinstance(__a , bnb.nn.Linearabit ):
return True
return False
def lowerCAmelCase_ ( __a ) -> List[str]:
"""simple docstring"""
return next(parameter.parameters() ).device
def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a , __a ) -> Any:
"""simple docstring"""
if fpaa_statistics is None:
set_module_tensor_to_device(__a , __a , 0 , dtype=__a , value=__a )
lowerCamelCase__: Dict =param_name
lowerCamelCase__: Tuple =model
if "." in tensor_name:
lowerCamelCase__: Any =tensor_name.split("." )
for split in splits[:-1]:
lowerCamelCase__: Any =getattr(__a , __a )
if new_module is None:
raise ValueError(F"""{module} has no attribute {split}.""" )
lowerCamelCase__: str =new_module
lowerCamelCase__: int =splits[-1]
# offload weights
lowerCamelCase__: str =False
offload_weight(module._parameters[tensor_name] , __a , __a , index=__a )
if hasattr(module._parameters[tensor_name] , "SCB" ):
offload_weight(
module._parameters[tensor_name].SCB , param_name.replace("weight" , "SCB" ) , __a , index=__a , )
else:
offload_weight(__a , __a , __a , index=__a )
offload_weight(__a , param_name.replace("weight" , "SCB" ) , __a , index=__a )
set_module_tensor_to_device(__a , __a , "meta" , dtype=__a , value=torch.empty(*param.size() ) )
| 59 | 1 |
import inspect
import unittest
from transformers import MobileNetVaConfig
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 transformers import MobileNetVaForImageClassification, MobileNetVaModel
from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import MobileNetVaImageProcessor
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[str]:
'''simple docstring'''
lowerCamelCase__: Dict =self.config_class(**self.inputs_dict)
self.parent.assertTrue(hasattr(UpperCAmelCase_ , "tf_padding"))
self.parent.assertTrue(hasattr(UpperCAmelCase_ , "depth_multiplier"))
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__(self : Optional[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict=13 , UpperCAmelCase_ : List[str]=3 , UpperCAmelCase_ : List[Any]=32 , UpperCAmelCase_ : Optional[Any]=0.25 , UpperCAmelCase_ : Tuple=8 , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : Tuple=1_024 , UpperCAmelCase_ : Optional[int]=32 , UpperCAmelCase_ : Union[str, Any]="relu6" , UpperCAmelCase_ : Tuple=0.1 , UpperCAmelCase_ : Optional[int]=0.02 , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Any=10 , UpperCAmelCase_ : Tuple=None , ) ->Any:
'''simple docstring'''
lowerCamelCase__: Any =parent
lowerCamelCase__: List[str] =batch_size
lowerCamelCase__: List[str] =num_channels
lowerCamelCase__: Optional[Any] =image_size
lowerCamelCase__: str =depth_multiplier
lowerCamelCase__: Union[str, Any] =min_depth
lowerCamelCase__: Any =tf_padding
lowerCamelCase__: List[Any] =int(last_hidden_size * depth_multiplier)
lowerCamelCase__: Any =output_stride
lowerCamelCase__: Optional[int] =hidden_act
lowerCamelCase__: Union[str, Any] =classifier_dropout_prob
lowerCamelCase__: List[Any] =use_labels
lowerCamelCase__: int =is_training
lowerCamelCase__: Optional[int] =num_labels
lowerCamelCase__: Optional[Any] =initializer_range
lowerCamelCase__: Any =scope
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: List[Any] =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
lowerCamelCase__: Tuple =None
lowerCamelCase__: Tuple =None
if self.use_labels:
lowerCamelCase__: str =ids_tensor([self.batch_size] , self.num_labels)
lowerCamelCase__: Dict =ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels)
lowerCamelCase__: Union[str, Any] =self.get_config()
return config, pixel_values, labels, pixel_labels
def SCREAMING_SNAKE_CASE_ (self : str) ->Dict:
'''simple docstring'''
return MobileNetVaConfig(
num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , min_depth=self.min_depth , tf_padding=self.tf_padding , hidden_act=self.hidden_act , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , )
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : int , UpperCAmelCase_ : int) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Optional[int] =MobileNetVaModel(config=UpperCAmelCase_)
model.to(UpperCAmelCase_)
model.eval()
lowerCamelCase__: Optional[int] =model(UpperCAmelCase_)
self.parent.assertEqual(
result.last_hidden_state.shape , (
self.batch_size,
self.last_hidden_size,
self.image_size // self.output_stride,
self.image_size // self.output_stride,
) , )
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Union[str, Any]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Tuple =self.num_labels
lowerCamelCase__: Union[str, Any] =MobileNetVaForImageClassification(UpperCAmelCase_)
model.to(UpperCAmelCase_)
model.eval()
lowerCamelCase__: Optional[Any] =model(UpperCAmelCase_ , labels=UpperCAmelCase_)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels))
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Tuple:
'''simple docstring'''
lowerCamelCase__: int =self.prepare_config_and_inputs()
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Dict =config_and_inputs
lowerCamelCase__: int ={"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ):
'''simple docstring'''
lowercase_ = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
lowercase_ = (
{"feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification}
if is_torch_available()
else {}
)
lowercase_ = False
lowercase_ = False
lowercase_ = False
lowercase_ = False
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__: Any =MobileNetVaModelTester(self)
lowerCamelCase__: Any =MobileNetVaConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Union[str, Any]:
'''simple docstring'''
self.config_tester.run_common_tests()
@unittest.skip(reason="MobileNetV1 does not use inputs_embeds")
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->int:
'''simple docstring'''
pass
@unittest.skip(reason="MobileNetV1 does not support input and output embeddings")
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Tuple:
'''simple docstring'''
pass
@unittest.skip(reason="MobileNetV1 does not output attentions")
def SCREAMING_SNAKE_CASE_ (self : str) ->str:
'''simple docstring'''
pass
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->int:
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowerCamelCase__: Tuple =model_class(UpperCAmelCase_)
lowerCamelCase__: int =inspect.signature(model.forward)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
lowerCamelCase__: Union[str, Any] =[*signature.parameters.keys()]
lowerCamelCase__: Union[str, Any] =["pixel_values"]
self.assertListEqual(arg_names[:1] , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->List[Any]:
'''simple docstring'''
lowerCamelCase__: List[str] =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any) ->Any:
'''simple docstring'''
def check_hidden_states_output(UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple):
lowerCamelCase__: int =model_class(UpperCAmelCase_)
model.to(UpperCAmelCase_)
model.eval()
with torch.no_grad():
lowerCamelCase__: int =model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_))
lowerCamelCase__: Optional[Any] =outputs.hidden_states
lowerCamelCase__: List[str] =26
self.assertEqual(len(UpperCAmelCase_) , UpperCAmelCase_)
lowerCamelCase__ , lowerCamelCase__: Optional[Any] =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowerCamelCase__: List[str] =True
check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
lowerCamelCase__: str =True
check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__: Any =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_)
@slow
def SCREAMING_SNAKE_CASE_ (self : Any) ->List[Any]:
'''simple docstring'''
for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowerCamelCase__: Any =MobileNetVaModel.from_pretrained(UpperCAmelCase_)
self.assertIsNotNone(UpperCAmelCase_)
def lowerCAmelCase_ ( ) -> int:
"""simple docstring"""
lowerCamelCase__: Tuple =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_torch
@require_vision
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
@cached_property
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Dict:
'''simple docstring'''
return (
MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v1_1.0_224") if is_vision_available() else None
)
@slow
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Any:
'''simple docstring'''
lowerCamelCase__: Any =MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224").to(UpperCAmelCase_)
lowerCamelCase__: List[str] =self.default_image_processor
lowerCamelCase__: str =prepare_img()
lowerCamelCase__: str =image_processor(images=UpperCAmelCase_ , return_tensors="pt").to(UpperCAmelCase_)
# forward pass
with torch.no_grad():
lowerCamelCase__: List[str] =model(**UpperCAmelCase_)
# verify the logits
lowerCamelCase__: Tuple =torch.Size((1, 1_001))
self.assertEqual(outputs.logits.shape , UpperCAmelCase_)
lowerCamelCase__: Tuple =torch.tensor([-4.1739, -1.1233, 3.1205]).to(UpperCAmelCase_)
self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4))
| 59 |
from __future__ import annotations
from math import pi
def lowerCAmelCase_ ( __a , __a , __a ) -> dict[str, float]:
"""simple docstring"""
if (inductance, frequency, reactance).count(0 ) != 1:
raise ValueError("One and only one argument must be 0" )
if inductance < 0:
raise ValueError("Inductance cannot be negative" )
if frequency < 0:
raise ValueError("Frequency cannot be negative" )
if reactance < 0:
raise ValueError("Inductive reactance cannot be negative" )
if inductance == 0:
return {"inductance": reactance / (2 * pi * frequency)}
elif frequency == 0:
return {"frequency": reactance / (2 * pi * inductance)}
elif reactance == 0:
return {"reactance": 2 * pi * frequency * inductance}
else:
raise ValueError("Exactly one argument must be 0" )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 59 | 1 |
import os
from pathlib import Path
from unittest.mock import patch
import pytest
import zstandard as zstd
from datasets.download.download_config import DownloadConfig
from datasets.utils.file_utils import (
OfflineModeIsEnabled,
cached_path,
fsspec_get,
fsspec_head,
ftp_get,
ftp_head,
get_from_cache,
http_get,
http_head,
)
__A = "\\n Text data.\n Second line of data."
__A = "file"
@pytest.fixture(scope="session" )
def lowerCAmelCase_ ( __a ) -> Union[str, Any]:
"""simple docstring"""
lowerCamelCase__: Any =tmp_path_factory.mktemp("data" ) / (FILE_PATH + ".zstd")
lowerCamelCase__: Optional[Any] =bytes(__a , "utf-8" )
with zstd.open(__a , "wb" ) as f:
f.write(__a )
return path
@pytest.fixture
def lowerCAmelCase_ ( __a ) -> Union[str, Any]:
"""simple docstring"""
with open(os.path.join(tmpfs.local_root_dir , __a ) , "w" ) as f:
f.write(__a )
return FILE_PATH
@pytest.mark.parametrize("compression_format" , ["gzip", "xz", "zstd"] )
def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a ) -> List[str]:
"""simple docstring"""
lowerCamelCase__: Tuple ={"gzip": gz_file, "xz": xz_file, "zstd": zstd_path}
lowerCamelCase__: Dict =input_paths[compression_format]
lowerCamelCase__: Dict =tmp_path / "cache"
lowerCamelCase__: Optional[Any] =DownloadConfig(cache_dir=__a , extract_compressed_file=__a )
lowerCamelCase__: Tuple =cached_path(__a , download_config=__a )
with open(__a ) as f:
lowerCamelCase__: int =f.read()
with open(__a ) as f:
lowerCamelCase__: Optional[int] =f.read()
assert extracted_file_content == expected_file_content
@pytest.mark.parametrize("default_extracted" , [True, False] )
@pytest.mark.parametrize("default_cache_dir" , [True, False] )
def lowerCAmelCase_ ( __a , __a , __a , __a , __a ) -> Tuple:
"""simple docstring"""
lowerCamelCase__: Optional[int] ="custom_cache"
lowerCamelCase__: List[str] ="custom_extracted_dir"
lowerCamelCase__: List[str] =tmp_path / "custom_extracted_path"
if default_extracted:
lowerCamelCase__: Optional[int] =("downloads" if default_cache_dir else custom_cache_dir, "extracted")
else:
monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_DIR" , __a )
monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_PATH" , str(__a ) )
lowerCamelCase__: Optional[int] =custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir)
lowerCamelCase__: List[str] =xz_file
lowerCamelCase__: Optional[int] =(
DownloadConfig(extract_compressed_file=__a )
if default_cache_dir
else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=__a )
)
lowerCamelCase__: int =cached_path(__a , download_config=__a )
assert Path(__a ).parent.parts[-2:] == expected
def lowerCAmelCase_ ( __a ) -> List[str]:
"""simple docstring"""
lowerCamelCase__: Any =str(Path(__a ).resolve() )
assert cached_path(__a ) == text_file
# relative path
lowerCamelCase__: Optional[Any] =str(Path(__a ).resolve().relative_to(Path(os.getcwd() ) ) )
assert cached_path(__a ) == text_file
def lowerCAmelCase_ ( __a ) -> str:
"""simple docstring"""
lowerCamelCase__: Tuple =str(tmp_path.resolve() / "__missing_file__.txt" )
with pytest.raises(__a ):
cached_path(__a )
# relative path
lowerCamelCase__: int ="./__missing_file__.txt"
with pytest.raises(__a ):
cached_path(__a )
def lowerCAmelCase_ ( __a ) -> str:
"""simple docstring"""
lowerCamelCase__: int =get_from_cache(F"""tmp://{tmpfs_file}""" )
with open(__a ) as f:
lowerCamelCase__: Dict =f.read()
assert output_file_content == FILE_CONTENT
@patch("datasets.config.HF_DATASETS_OFFLINE" , __a )
def lowerCAmelCase_ ( ) -> Union[str, Any]:
"""simple docstring"""
with pytest.raises(__a ):
cached_path("https://huggingface.co" )
@patch("datasets.config.HF_DATASETS_OFFLINE" , __a )
def lowerCAmelCase_ ( __a ) -> Optional[Any]:
"""simple docstring"""
lowerCamelCase__: Dict =tmp_path_factory.mktemp("data" ) / "file.html"
with pytest.raises(__a ):
http_get("https://huggingface.co" , temp_file=__a )
with pytest.raises(__a ):
http_head("https://huggingface.co" )
@patch("datasets.config.HF_DATASETS_OFFLINE" , __a )
def lowerCAmelCase_ ( __a ) -> Tuple:
"""simple docstring"""
lowerCamelCase__: Optional[int] =tmp_path_factory.mktemp("data" ) / "file.html"
with pytest.raises(__a ):
ftp_get("ftp://huggingface.co" , temp_file=__a )
with pytest.raises(__a ):
ftp_head("ftp://huggingface.co" )
@patch("datasets.config.HF_DATASETS_OFFLINE" , __a )
def lowerCAmelCase_ ( __a ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase__: Optional[Any] =tmp_path_factory.mktemp("data" ) / "file.html"
with pytest.raises(__a ):
fsspec_get("s3://huggingface.co" , temp_file=__a )
with pytest.raises(__a ):
fsspec_head("s3://huggingface.co" )
| 59 |
import pyarrow.parquet as pq
import pytest
from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config
from datasets.features.image import Image
from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size
from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases
def lowerCAmelCase_ ( __a , __a ) -> List[Any]:
"""simple docstring"""
assert isinstance(__a , __a )
assert dataset.num_rows == 4
assert dataset.num_columns == 3
assert dataset.column_names == ["col_1", "col_2", "col_3"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("keep_in_memory" , [False, True] )
def lowerCAmelCase_ ( __a , __a , __a ) -> Any:
"""simple docstring"""
lowerCamelCase__: Any =tmp_path / "cache"
lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
lowerCamelCase__: Tuple =ParquetDatasetReader(__a , cache_dir=__a , keep_in_memory=__a ).read()
_check_parquet_dataset(__a , __a )
@pytest.mark.parametrize(
"features" , [
None,
{"col_1": "string", "col_2": "int64", "col_3": "float64"},
{"col_1": "string", "col_2": "string", "col_3": "string"},
{"col_1": "int32", "col_2": "int32", "col_3": "int32"},
{"col_1": "float32", "col_2": "float32", "col_3": "float32"},
] , )
def lowerCAmelCase_ ( __a , __a , __a ) -> List[str]:
"""simple docstring"""
lowerCamelCase__: int =tmp_path / "cache"
lowerCamelCase__: Tuple ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
lowerCamelCase__: Union[str, Any] =features.copy() if features else default_expected_features
lowerCamelCase__: Optional[int] =(
Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None
)
lowerCamelCase__: int =ParquetDatasetReader(__a , features=__a , cache_dir=__a ).read()
_check_parquet_dataset(__a , __a )
@pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] )
def lowerCAmelCase_ ( __a , __a , __a ) -> Any:
"""simple docstring"""
lowerCamelCase__: Any =tmp_path / "cache"
lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
lowerCamelCase__: Optional[Any] =ParquetDatasetReader(__a , cache_dir=__a , split=__a ).read()
_check_parquet_dataset(__a , __a )
assert dataset.split == split if split else "train"
@pytest.mark.parametrize("path_type" , [str, list] )
def lowerCAmelCase_ ( __a , __a , __a ) -> int:
"""simple docstring"""
if issubclass(__a , __a ):
lowerCamelCase__: List[Any] =parquet_path
elif issubclass(__a , __a ):
lowerCamelCase__: str =[parquet_path]
lowerCamelCase__: Tuple =tmp_path / "cache"
lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read()
_check_parquet_dataset(__a , __a )
def lowerCAmelCase_ ( __a , __a , __a=("train",) ) -> Dict:
"""simple docstring"""
assert isinstance(__a , __a )
for split in splits:
lowerCamelCase__: Tuple =dataset_dict[split]
assert dataset.num_rows == 4
assert dataset.num_columns == 3
assert dataset.column_names == ["col_1", "col_2", "col_3"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("keep_in_memory" , [False, True] )
def lowerCAmelCase_ ( __a , __a , __a ) -> Any:
"""simple docstring"""
lowerCamelCase__: List[Any] =tmp_path / "cache"
lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
lowerCamelCase__: Tuple =ParquetDatasetReader(
{"train": parquet_path} , cache_dir=__a , keep_in_memory=__a ).read()
_check_parquet_datasetdict(__a , __a )
@pytest.mark.parametrize(
"features" , [
None,
{"col_1": "string", "col_2": "int64", "col_3": "float64"},
{"col_1": "string", "col_2": "string", "col_3": "string"},
{"col_1": "int32", "col_2": "int32", "col_3": "int32"},
{"col_1": "float32", "col_2": "float32", "col_3": "float32"},
] , )
def lowerCAmelCase_ ( __a , __a , __a ) -> Optional[Any]:
"""simple docstring"""
lowerCamelCase__: Tuple =tmp_path / "cache"
lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
lowerCamelCase__: List[Any] =features.copy() if features else default_expected_features
lowerCamelCase__: int =(
Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None
)
lowerCamelCase__: Optional[Any] =ParquetDatasetReader({"train": parquet_path} , features=__a , cache_dir=__a ).read()
_check_parquet_datasetdict(__a , __a )
@pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] )
def lowerCAmelCase_ ( __a , __a , __a ) -> Union[str, Any]:
"""simple docstring"""
if split:
lowerCamelCase__: Any ={split: parquet_path}
else:
lowerCamelCase__: int ="train"
lowerCamelCase__: Any ={"train": parquet_path, "test": parquet_path}
lowerCamelCase__: str =tmp_path / "cache"
lowerCamelCase__: Any ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read()
_check_parquet_datasetdict(__a , __a , splits=list(path.keys() ) )
assert all(dataset[split].split == split for split in path.keys() )
def lowerCAmelCase_ ( __a , __a ) -> int:
"""simple docstring"""
lowerCamelCase__: List[str] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" )
assert writer.write() > 0
lowerCamelCase__: List[str] =pq.ParquetFile(tmp_path / "foo.parquet" )
lowerCamelCase__: List[str] =pf.read()
assert dataset.data.table == output_table
def lowerCAmelCase_ ( __a , __a ) -> List[str]:
"""simple docstring"""
lowerCamelCase__: List[str] =str(shared_datadir / "test_image_rgb.jpg" )
lowerCamelCase__: Union[str, Any] ={"image": [image_path]}
lowerCamelCase__: Optional[Any] =Features({"image": Image()} )
lowerCamelCase__: Optional[int] =Dataset.from_dict(__a , features=__a )
lowerCamelCase__: Optional[int] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" )
assert writer.write() > 0
lowerCamelCase__: Dict =Dataset.from_parquet(str(tmp_path / "foo.parquet" ) )
assert dataset.features == reloaded_dataset.features
lowerCamelCase__: Optional[Any] =ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=__a ).read()
assert dataset.features == reloaded_iterable_dataset.features
@pytest.mark.parametrize(
"feature, expected" , [
(Features({"foo": Value("int32" )} ), None),
(Features({"image": Image(), "foo": Value("int32" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS),
(Features({"nested": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS),
] , )
def lowerCAmelCase_ ( __a , __a ) -> Optional[Any]:
"""simple docstring"""
assert get_writer_batch_size(__a ) == expected
| 59 | 1 |
def lowerCAmelCase_ ( __a , __a ) -> list[int]:
"""simple docstring"""
lowerCamelCase__: Optional[int] =int(__a )
# Initialize Result
lowerCamelCase__: Any =[]
# Traverse through all denomination
for denomination in reversed(__a ):
# Find denominations
while int(__a ) >= int(__a ):
total_value -= int(__a )
answer.append(__a ) # Append the "answers" array
return answer
# Driver Code
if __name__ == "__main__":
__A = []
__A = "0"
if (
input("Do you want to enter your denominations ? (yY/n): ").strip().lower()
== "y"
):
__A = int(input("Enter the number of denominations you want to add: ").strip())
for i in range(0, n):
denominations.append(int(input(f'Denomination {i}: ').strip()))
__A = input("Enter the change you want to make in Indian Currency: ").strip()
else:
# All denominations of Indian Currency if user does not enter
__A = [1, 2, 5, 10, 20, 50, 100, 500, 2000]
__A = input("Enter the change you want to make: ").strip()
if int(value) == 0 or int(value) < 0:
print("The total value cannot be zero or negative.")
else:
print(f'Following is minimal change for {value}: ')
__A = find_minimum_change(denominations, value)
# Print result
for i in range(len(answer)):
print(answer[i], end=" ")
| 59 |
import unittest
from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin
__A = get_tests_dir("fixtures/test_sentencepiece.model")
@require_sentencepiece
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ):
'''simple docstring'''
lowercase_ = XLMProphetNetTokenizer
lowercase_ = False
lowercase_ = True
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[Any]:
'''simple docstring'''
super().setUp()
# We have a SentencePiece fixture for testing
lowerCamelCase__: Any =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_)
tokenizer.save_pretrained(self.tmpdirname)
def SCREAMING_SNAKE_CASE_ (self : str) ->str:
'''simple docstring'''
lowerCamelCase__: List[Any] ="[PAD]"
lowerCamelCase__: Tuple =0
self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_) , UpperCAmelCase_)
self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_) , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Dict) ->int:
'''simple docstring'''
lowerCamelCase__: List[Any] =list(self.get_tokenizer().get_vocab().keys())
self.assertEqual(vocab_keys[0] , "[PAD]")
self.assertEqual(vocab_keys[1] , "[CLS]")
self.assertEqual(vocab_keys[-1] , "j")
self.assertEqual(len(UpperCAmelCase_) , 1_012)
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]:
'''simple docstring'''
self.assertEqual(self.get_tokenizer().vocab_size , 1_012)
def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_)
lowerCamelCase__: Tuple =tokenizer.tokenize("This is a test")
self.assertListEqual(UpperCAmelCase_ , ["▁This", "▁is", "▁a", "▁t", "est"])
self.assertListEqual(
tokenizer.convert_tokens_to_ids(UpperCAmelCase_) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , )
lowerCamelCase__: Optional[Any] =tokenizer.tokenize("I was born in 92000, and this is falsé.")
self.assertListEqual(
UpperCAmelCase_ , [
SPIECE_UNDERLINE + "I",
SPIECE_UNDERLINE + "was",
SPIECE_UNDERLINE + "b",
"or",
"n",
SPIECE_UNDERLINE + "in",
SPIECE_UNDERLINE + "",
"9",
"2",
"0",
"0",
"0",
",",
SPIECE_UNDERLINE + "and",
SPIECE_UNDERLINE + "this",
SPIECE_UNDERLINE + "is",
SPIECE_UNDERLINE + "f",
"al",
"s",
"é",
".",
] , )
lowerCamelCase__: Any =tokenizer.convert_tokens_to_ids(UpperCAmelCase_)
self.assertListEqual(
UpperCAmelCase_ , [
value + tokenizer.fairseq_offset
for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4]
] , )
lowerCamelCase__: Any =tokenizer.convert_ids_to_tokens(UpperCAmelCase_)
self.assertListEqual(
UpperCAmelCase_ , [
SPIECE_UNDERLINE + "I",
SPIECE_UNDERLINE + "was",
SPIECE_UNDERLINE + "b",
"or",
"n",
SPIECE_UNDERLINE + "in",
SPIECE_UNDERLINE + "",
"[UNK]",
"2",
"0",
"0",
"0",
",",
SPIECE_UNDERLINE + "and",
SPIECE_UNDERLINE + "this",
SPIECE_UNDERLINE + "is",
SPIECE_UNDERLINE + "f",
"al",
"s",
"[UNK]",
".",
] , )
@cached_property
def SCREAMING_SNAKE_CASE_ (self : Any) ->int:
'''simple docstring'''
return XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased")
@slow
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[str]:
'''simple docstring'''
lowerCamelCase__: Optional[int] ="Hello World!"
lowerCamelCase__: Dict =[35_389, 6_672, 49, 2]
self.assertListEqual(UpperCAmelCase_ , self.big_tokenizer.encode(UpperCAmelCase_))
@slow
def SCREAMING_SNAKE_CASE_ (self : int) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__: Any ={"input_ids": [[11_073, 82_783, 18, 26, 82_783, 549, 51_540, 248, 17_209, 1_301, 217, 20, 215_186, 1_325, 147, 17_209, 1_301, 217, 20, 56_370, 53, 122_020, 20, 16_477, 27, 87_355, 4_548, 20, 4_728, 78_392, 17, 159_969, 18, 26, 24_491, 629, 15, 538, 22_704, 5_439, 15, 2_788, 24_491, 9_885, 15, 43_534, 605, 15, 814, 18_403, 33_200, 29, 15, 43_534, 24_458, 12_410, 111, 24_966, 83_669, 9_637, 144_068, 26, 850, 22_346, 27, 147, 24_966, 83_669, 83_490, 26, 39_113, 735, 27, 689, 656, 2_800, 1_339, 4_600, 53, 122_020, 115_785, 34, 816, 1_339, 46_887, 18, 147, 53_905, 1_951, 42_238, 41_170, 17_732, 834, 436, 15, 27_523, 98_733, 217, 147, 5_542, 4_981, 930, 17_347, 16, 2], [20_091, 629, 94, 82_786, 58, 490, 20, 1_528, 84, 53_905, 344, 80_592, 110_128, 18_822, 5_267, 1_306, 62, 152_537, 308, 7_997, 401, 124_427, 549, 35_442, 225, 109, 15_055, 25_748, 147, 7_119, 43_712, 34, 767, 135_366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63_784, 119_466, 17, 147_808, 88_214, 18, 656, 81, 32, 3_296, 10_280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=UpperCAmelCase_ , model_name="microsoft/xprophetnet-large-wiki100-cased" , revision="1acad1643ddd54a44df6a1b797ada8373685d90e" , )
| 59 | 1 |
import gc
import unittest
import torch
from parameterized import parameterized
from diffusers import AutoencoderKL
from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism
from .test_modeling_common import ModelTesterMixin, UNetTesterMixin
enable_full_determinism()
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ):
'''simple docstring'''
lowercase_ = AutoencoderKL
lowercase_ = "sample"
lowercase_ = 1E-2
@property
def SCREAMING_SNAKE_CASE_ (self : int) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Optional[int] =4
lowerCamelCase__: Union[str, Any] =3
lowerCamelCase__: Tuple =(32, 32)
lowerCamelCase__: Optional[Any] =floats_tensor((batch_size, num_channels) + sizes).to(UpperCAmelCase_)
return {"sample": image}
@property
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Optional[int]:
'''simple docstring'''
return (3, 32, 32)
@property
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->List[str]:
'''simple docstring'''
return (3, 32, 32)
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Any:
'''simple docstring'''
lowerCamelCase__: Optional[int] ={
"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__: Optional[int] =self.dummy_input
return init_dict, inputs_dict
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->List[Any]:
'''simple docstring'''
pass
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->str:
'''simple docstring'''
pass
@unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS")
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Any:
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: str =self.prepare_init_args_and_inputs_for_common()
lowerCamelCase__: Union[str, Any] =self.model_class(**UpperCAmelCase_)
model.to(UpperCAmelCase_)
assert not model.is_gradient_checkpointing and model.training
lowerCamelCase__: Tuple =model(**UpperCAmelCase_).sample
# run the backwards pass on the model. For backwards pass, for simplicity purpose,
# we won't calculate the loss and rather backprop on out.sum()
model.zero_grad()
lowerCamelCase__: List[str] =torch.randn_like(UpperCAmelCase_)
lowerCamelCase__: Dict =(out - labels).mean()
loss.backward()
# re-instantiate the model now enabling gradient checkpointing
lowerCamelCase__: List[Any] =self.model_class(**UpperCAmelCase_)
# clone model
model_a.load_state_dict(model.state_dict())
model_a.to(UpperCAmelCase_)
model_a.enable_gradient_checkpointing()
assert model_a.is_gradient_checkpointing and model_a.training
lowerCamelCase__: Optional[int] =model_a(**UpperCAmelCase_).sample
# run the backwards pass on the model. For backwards pass, for simplicity purpose,
# we won't calculate the loss and rather backprop on out.sum()
model_a.zero_grad()
lowerCamelCase__: Optional[int] =(out_a - labels).mean()
loss_a.backward()
# compare the output and parameters gradients
self.assertTrue((loss - loss_a).abs() < 1E-5)
lowerCamelCase__: str =dict(model.named_parameters())
lowerCamelCase__: Any =dict(model_a.named_parameters())
for name, param in named_params.items():
self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5))
def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: int =AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=UpperCAmelCase_)
self.assertIsNotNone(UpperCAmelCase_)
self.assertEqual(len(loading_info["missing_keys"]) , 0)
model.to(UpperCAmelCase_)
lowerCamelCase__: List[Any] =model(**self.dummy_input)
assert image is not None, "Make sure output is not None"
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->int:
'''simple docstring'''
lowerCamelCase__: Any =AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy")
lowerCamelCase__: str =model.to(UpperCAmelCase_)
model.eval()
if torch_device == "mps":
lowerCamelCase__: Optional[int] =torch.manual_seed(0)
else:
lowerCamelCase__: Optional[Any] =torch.Generator(device=UpperCAmelCase_).manual_seed(0)
lowerCamelCase__: int =torch.randn(
1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0) , )
lowerCamelCase__: Tuple =image.to(UpperCAmelCase_)
with torch.no_grad():
lowerCamelCase__: Dict =model(UpperCAmelCase_ , sample_posterior=UpperCAmelCase_ , generator=UpperCAmelCase_).sample
lowerCamelCase__: str =output[0, -1, -3:, -3:].flatten().cpu()
# Since the VAE Gaussian prior's generator is seeded on the appropriate device,
# the expected output slices are not the same for CPU and GPU.
if torch_device == "mps":
lowerCamelCase__: List[str] =torch.tensor(
[
-4.0_0_7_8E-0_1,
-3.8_3_2_3E-0_4,
-1.2_6_8_1E-0_1,
-1.1_4_6_2E-0_1,
2.0_0_9_5E-0_1,
1.0_8_9_3E-0_1,
-8.8_2_4_7E-0_2,
-3.0_3_6_1E-0_1,
-9.8_6_4_4E-0_3,
])
elif torch_device == "cpu":
lowerCamelCase__: str =torch.tensor(
[-0.1352, 0.0878, 0.0419, -0.0818, -0.1069, 0.0688, -0.1458, -0.4446, -0.0026])
else:
lowerCamelCase__: Optional[int] =torch.tensor(
[-0.2421, 0.4642, 0.2507, -0.0438, 0.0682, 0.3160, -0.2018, -0.0727, 0.2485])
self.assertTrue(torch_all_close(UpperCAmelCase_ , UpperCAmelCase_ , rtol=1E-2))
@slow
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[int]) ->Union[str, Any]:
'''simple docstring'''
return F"""gaussian_noise_s={seed}_shape={"_".join([str(UpperCAmelCase_) for s in shape])}.npy"""
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->List[Any]:
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Optional[int]=0 , UpperCAmelCase_ : Any=(4, 3, 512, 512) , UpperCAmelCase_ : int=False) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =torch.floataa if fpaa else torch.floataa
lowerCamelCase__: Optional[Any] =torch.from_numpy(load_hf_numpy(self.get_file_format(UpperCAmelCase_ , UpperCAmelCase_))).to(UpperCAmelCase_).to(UpperCAmelCase_)
return image
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : List[Any]="CompVis/stable-diffusion-v1-4" , UpperCAmelCase_ : Any=False) ->List[Any]:
'''simple docstring'''
lowerCamelCase__: List[Any] ="fp16" if fpaa else None
lowerCamelCase__: Optional[Any] =torch.floataa if fpaa else torch.floataa
lowerCamelCase__: str =AutoencoderKL.from_pretrained(
UpperCAmelCase_ , subfolder="vae" , torch_dtype=UpperCAmelCase_ , revision=UpperCAmelCase_ , )
model.to(UpperCAmelCase_).eval()
return model
def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Optional[int]=0) ->List[str]:
'''simple docstring'''
if torch_device == "mps":
return torch.manual_seed(UpperCAmelCase_)
return torch.Generator(device=UpperCAmelCase_).manual_seed(UpperCAmelCase_)
@parameterized.expand(
[
# fmt: off
[33, [-0.1603, 0.9878, -0.0495, -0.0790, -0.2709, 0.8375, -0.2060, -0.0824], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]],
[47, [-0.2376, 0.1168, 0.1332, -0.4840, -0.2508, -0.0791, -0.0493, -0.4089], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]],
# fmt: on
])
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : int) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: str =self.get_sd_vae_model()
lowerCamelCase__: str =self.get_sd_image(UpperCAmelCase_)
lowerCamelCase__: Optional[int] =self.get_generator(UpperCAmelCase_)
with torch.no_grad():
lowerCamelCase__: Tuple =model(UpperCAmelCase_ , generator=UpperCAmelCase_ , sample_posterior=UpperCAmelCase_).sample
assert sample.shape == image.shape
lowerCamelCase__: List[Any] =sample[-1, -2:, -2:, :2].flatten().float().cpu()
lowerCamelCase__: Tuple =torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice)
assert torch_all_close(UpperCAmelCase_ , UpperCAmelCase_ , atol=3E-3)
@parameterized.expand(
[
# fmt: off
[33, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]],
[47, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]],
# fmt: on
])
@require_torch_gpu
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[int]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: List[Any] =self.get_sd_vae_model(fpaa=UpperCAmelCase_)
lowerCamelCase__: List[str] =self.get_sd_image(UpperCAmelCase_ , fpaa=UpperCAmelCase_)
lowerCamelCase__: List[str] =self.get_generator(UpperCAmelCase_)
with torch.no_grad():
lowerCamelCase__: Union[str, Any] =model(UpperCAmelCase_ , generator=UpperCAmelCase_ , sample_posterior=UpperCAmelCase_).sample
assert sample.shape == image.shape
lowerCamelCase__: Any =sample[-1, -2:, :2, -2:].flatten().float().cpu()
lowerCamelCase__: str =torch.tensor(UpperCAmelCase_)
assert torch_all_close(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-2)
@parameterized.expand(
[
# fmt: off
[33, [-0.1609, 0.9866, -0.0487, -0.0777, -0.2716, 0.8368, -0.2055, -0.0814], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]],
[47, [-0.2377, 0.1147, 0.1333, -0.4841, -0.2506, -0.0805, -0.0491, -0.4085], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]],
# fmt: on
])
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Any) ->Tuple:
'''simple docstring'''
lowerCamelCase__: List[Any] =self.get_sd_vae_model()
lowerCamelCase__: Optional[Any] =self.get_sd_image(UpperCAmelCase_)
with torch.no_grad():
lowerCamelCase__: Any =model(UpperCAmelCase_).sample
assert sample.shape == image.shape
lowerCamelCase__: Dict =sample[-1, -2:, -2:, :2].flatten().float().cpu()
lowerCamelCase__: Dict =torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice)
assert torch_all_close(UpperCAmelCase_ , UpperCAmelCase_ , atol=3E-3)
@parameterized.expand(
[
# fmt: off
[13, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]],
[37, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]],
# fmt: on
])
@require_torch_gpu
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Tuple) ->List[Any]:
'''simple docstring'''
lowerCamelCase__: Any =self.get_sd_vae_model()
lowerCamelCase__: List[str] =self.get_sd_image(UpperCAmelCase_ , shape=(3, 4, 64, 64))
with torch.no_grad():
lowerCamelCase__: Optional[Any] =model.decode(UpperCAmelCase_).sample
assert list(sample.shape) == [3, 3, 512, 512]
lowerCamelCase__: str =sample[-1, -2:, :2, -2:].flatten().cpu()
lowerCamelCase__: str =torch.tensor(UpperCAmelCase_)
assert torch_all_close(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-3)
@parameterized.expand(
[
# fmt: off
[27, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]],
[16, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]],
# fmt: on
])
@require_torch_gpu
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple) ->List[Any]:
'''simple docstring'''
lowerCamelCase__: List[Any] =self.get_sd_vae_model(fpaa=UpperCAmelCase_)
lowerCamelCase__: List[Any] =self.get_sd_image(UpperCAmelCase_ , shape=(3, 4, 64, 64) , fpaa=UpperCAmelCase_)
with torch.no_grad():
lowerCamelCase__: Optional[Any] =model.decode(UpperCAmelCase_).sample
assert list(sample.shape) == [3, 3, 512, 512]
lowerCamelCase__: Optional[Any] =sample[-1, -2:, :2, -2:].flatten().float().cpu()
lowerCamelCase__: List[str] =torch.tensor(UpperCAmelCase_)
assert torch_all_close(UpperCAmelCase_ , UpperCAmelCase_ , atol=5E-3)
@parameterized.expand([(13,), (16,), (27,)])
@require_torch_gpu
@unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0.")
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : str) ->List[Any]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =self.get_sd_vae_model(fpaa=UpperCAmelCase_)
lowerCamelCase__: Tuple =self.get_sd_image(UpperCAmelCase_ , shape=(3, 4, 64, 64) , fpaa=UpperCAmelCase_)
with torch.no_grad():
lowerCamelCase__: str =model.decode(UpperCAmelCase_).sample
model.enable_xformers_memory_efficient_attention()
with torch.no_grad():
lowerCamelCase__: Union[str, Any] =model.decode(UpperCAmelCase_).sample
assert list(sample.shape) == [3, 3, 512, 512]
assert torch_all_close(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-1)
@parameterized.expand([(13,), (16,), (37,)])
@require_torch_gpu
@unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0.")
def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : Dict) ->Tuple:
'''simple docstring'''
lowerCamelCase__: str =self.get_sd_vae_model()
lowerCamelCase__: str =self.get_sd_image(UpperCAmelCase_ , shape=(3, 4, 64, 64))
with torch.no_grad():
lowerCamelCase__: Union[str, Any] =model.decode(UpperCAmelCase_).sample
model.enable_xformers_memory_efficient_attention()
with torch.no_grad():
lowerCamelCase__: str =model.decode(UpperCAmelCase_).sample
assert list(sample.shape) == [3, 3, 512, 512]
assert torch_all_close(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-2)
@parameterized.expand(
[
# fmt: off
[33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]],
[47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]],
# fmt: on
])
def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[int]) ->Any:
'''simple docstring'''
lowerCamelCase__: Tuple =self.get_sd_vae_model()
lowerCamelCase__: List[Any] =self.get_sd_image(UpperCAmelCase_)
lowerCamelCase__: Union[str, Any] =self.get_generator(UpperCAmelCase_)
with torch.no_grad():
lowerCamelCase__: Any =model.encode(UpperCAmelCase_).latent_dist
lowerCamelCase__: Optional[Any] =dist.sample(generator=UpperCAmelCase_)
assert list(sample.shape) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]]
lowerCamelCase__: Optional[int] =sample[0, -1, -3:, -3:].flatten().cpu()
lowerCamelCase__: Any =torch.tensor(UpperCAmelCase_)
lowerCamelCase__: Tuple =3E-3 if torch_device != "mps" else 1E-2
assert torch_all_close(UpperCAmelCase_ , UpperCAmelCase_ , atol=UpperCAmelCase_)
| 59 |
import os
import shutil
import tempfile
import unittest
import numpy as np
from transformers import AutoTokenizer, BarkProcessor
from transformers.testing_utils import require_torch, slow
@require_torch
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->str:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] ="ylacombe/bark-small"
lowerCamelCase__: Tuple =tempfile.mkdtemp()
lowerCamelCase__: Tuple ="en_speaker_1"
lowerCamelCase__: Optional[int] ="This is a test string"
lowerCamelCase__: List[str] ="speaker_embeddings_path.json"
lowerCamelCase__: int ="speaker_embeddings"
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , **UpperCAmelCase_ : Any) ->Tuple:
'''simple docstring'''
return AutoTokenizer.from_pretrained(self.checkpoint , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Union[str, Any]:
'''simple docstring'''
shutil.rmtree(self.tmpdirname)
def SCREAMING_SNAKE_CASE_ (self : int) ->Any:
'''simple docstring'''
lowerCamelCase__: List[Any] =self.get_tokenizer()
lowerCamelCase__: List[str] =BarkProcessor(tokenizer=UpperCAmelCase_)
processor.save_pretrained(self.tmpdirname)
lowerCamelCase__: Dict =BarkProcessor.from_pretrained(self.tmpdirname)
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab())
@slow
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Tuple =BarkProcessor.from_pretrained(
pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , )
processor.save_pretrained(
self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , )
lowerCamelCase__: Dict =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)")
lowerCamelCase__: Any =BarkProcessor.from_pretrained(
self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="(BOS)" , eos_token="(EOS)" , )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab())
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->int:
'''simple docstring'''
lowerCamelCase__: Any =BarkProcessor.from_pretrained(
pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , )
lowerCamelCase__: List[str] =35
lowerCamelCase__: Optional[Any] =2
lowerCamelCase__: Optional[Any] =8
lowerCamelCase__: Optional[int] ={
"semantic_prompt": np.ones(UpperCAmelCase_),
"coarse_prompt": np.ones((nb_codebooks_coarse, seq_len)),
"fine_prompt": np.ones((nb_codebooks_total, seq_len)),
}
# test providing already loaded voice_preset
lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=UpperCAmelCase_)
lowerCamelCase__: int =inputs["history_prompt"]
for key in voice_preset:
self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist())
# test loading voice preset from npz file
lowerCamelCase__: Union[str, Any] =os.path.join(self.tmpdirname , "file.npz")
np.savez(UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: Tuple =processor(text=self.input_string , voice_preset=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =inputs["history_prompt"]
for key in voice_preset:
self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist())
# test loading voice preset from the hub
lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=self.voice_preset)
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__: str =self.get_tokenizer()
lowerCamelCase__: Dict =BarkProcessor(tokenizer=UpperCAmelCase_)
lowerCamelCase__: List[Any] =processor(text=self.input_string)
lowerCamelCase__: Optional[int] =tokenizer(
self.input_string , padding="max_length" , max_length=256 , add_special_tokens=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist())
| 59 | 1 |
# 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 _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = "Salesforce/blip-image-captioning-base"
lowercase_ = (
"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."
)
lowercase_ = "image_captioner"
lowercase_ = AutoModelForVisionaSeq
lowercase_ = ["image"]
lowercase_ = ["text"]
def __init__(self : str , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : int) ->int:
'''simple docstring'''
requires_backends(self , ["vision"])
super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : "Image") ->Optional[Any]:
'''simple docstring'''
return self.pre_processor(images=UpperCAmelCase_ , return_tensors="pt")
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Any) ->int:
'''simple docstring'''
return self.model.generate(**UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : Dict) ->List[Any]:
'''simple docstring'''
return self.pre_processor.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_)[0].strip()
| 59 |
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = ["image_processor", "tokenizer"]
lowercase_ = "CLIPImageProcessor"
lowercase_ = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast")
def __init__(self : List[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : List[str]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =None
if "feature_extractor" in kwargs:
warnings.warn(
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
" instead." , UpperCAmelCase_ , )
lowerCamelCase__: int =kwargs.pop("feature_extractor")
lowerCamelCase__: int =image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError("You need to specify an `image_processor`.")
if tokenizer is None:
raise ValueError("You need to specify a `tokenizer`.")
super().__init__(UpperCAmelCase_ , UpperCAmelCase_)
def __call__(self : List[Any] , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : int=None , **UpperCAmelCase_ : Any) ->Union[str, Any]:
'''simple docstring'''
if text is None and images is None:
raise ValueError("You have to specify either text or images. Both cannot be none.")
if text is not None:
lowerCamelCase__: List[Any] =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if images is not None:
lowerCamelCase__: int =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if text is not None and images is not None:
lowerCamelCase__: str =image_features.pixel_values
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[Any]) ->Dict:
'''simple docstring'''
return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Any) ->Optional[Any]:
'''simple docstring'''
return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_)
@property
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =self.tokenizer.model_input_names
lowerCamelCase__: str =self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
| 59 | 1 |
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
"facebook/deit-base-distilled-patch16-224": (
"https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json"
),
# See all DeiT models at https://huggingface.co/models?filter=deit
}
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = "deit"
def __init__(self : str , UpperCAmelCase_ : str=768 , UpperCAmelCase_ : Dict=12 , UpperCAmelCase_ : List[str]=12 , UpperCAmelCase_ : List[str]=3_072 , UpperCAmelCase_ : int="gelu" , UpperCAmelCase_ : Optional[Any]=0.0 , UpperCAmelCase_ : Dict=0.0 , UpperCAmelCase_ : List[Any]=0.02 , UpperCAmelCase_ : int=1E-1_2 , UpperCAmelCase_ : Union[str, Any]=224 , UpperCAmelCase_ : Dict=16 , UpperCAmelCase_ : int=3 , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : List[Any]=16 , **UpperCAmelCase_ : List[Any] , ) ->Optional[Any]:
'''simple docstring'''
super().__init__(**UpperCAmelCase_)
lowerCamelCase__: Optional[int] =hidden_size
lowerCamelCase__: Any =num_hidden_layers
lowerCamelCase__: str =num_attention_heads
lowerCamelCase__: Tuple =intermediate_size
lowerCamelCase__: Tuple =hidden_act
lowerCamelCase__: Optional[int] =hidden_dropout_prob
lowerCamelCase__: Dict =attention_probs_dropout_prob
lowerCamelCase__: Optional[Any] =initializer_range
lowerCamelCase__: Tuple =layer_norm_eps
lowerCamelCase__: List[str] =image_size
lowerCamelCase__: Union[str, Any] =patch_size
lowerCamelCase__: Optional[int] =num_channels
lowerCamelCase__: Optional[Any] =qkv_bias
lowerCamelCase__: Tuple =encoder_stride
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = version.parse("1.11" )
@property
def SCREAMING_SNAKE_CASE_ (self : int) ->Mapping[str, Mapping[int, str]]:
'''simple docstring'''
return OrderedDict(
[
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
])
@property
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->float:
'''simple docstring'''
return 1E-4
| 59 |
from datetime import datetime
import matplotlib.pyplot as plt
import torch
def lowerCAmelCase_ ( __a ) -> Any:
"""simple docstring"""
for param in module.parameters():
lowerCamelCase__: Tuple =False
def lowerCAmelCase_ ( ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase__: List[str] ="cuda" if torch.cuda.is_available() else "cpu"
if torch.backends.mps.is_available() and torch.backends.mps.is_built():
lowerCamelCase__: str ="mps"
if device == "mps":
print(
"WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch"
" errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues"
" with generations." )
return device
def lowerCAmelCase_ ( __a ) -> List[str]:
"""simple docstring"""
lowerCamelCase__: Union[str, Any] =plt.imshow(__a )
fig.axes.get_xaxis().set_visible(__a )
fig.axes.get_yaxis().set_visible(__a )
plt.show()
def lowerCAmelCase_ ( ) -> Optional[Any]:
"""simple docstring"""
lowerCamelCase__: List[str] =datetime.now()
lowerCamelCase__: str =current_time.strftime("%H:%M:%S" )
return timestamp
| 59 | 1 |
import numpy as np
from transformers import Pipeline
def lowerCAmelCase_ ( __a ) -> List[str]:
"""simple docstring"""
lowerCamelCase__: Optional[Any] =np.max(__a , axis=-1 , keepdims=__a )
lowerCamelCase__: int =np.exp(outputs - maxes )
return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=__a )
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , **UpperCAmelCase_ : Union[str, Any]) ->str:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] ={}
if "second_text" in kwargs:
lowerCamelCase__: Optional[int] =kwargs["second_text"]
return preprocess_kwargs, {}, {}
def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any]=None) ->int:
'''simple docstring'''
return self.tokenizer(UpperCAmelCase_ , text_pair=UpperCAmelCase_ , return_tensors=self.framework)
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : int) ->int:
'''simple docstring'''
return self.model(**UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : Optional[int]) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Tuple =model_outputs.logits[0].numpy()
lowerCamelCase__: Any =softmax(UpperCAmelCase_)
lowerCamelCase__: List[str] =np.argmax(UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =self.model.config.idalabel[best_class]
lowerCamelCase__: str =probabilities[best_class].item()
lowerCamelCase__: List[str] =logits.tolist()
return {"label": label, "score": score, "logits": logits}
| 59 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
__A = {
"configuration_pix2struct": [
"PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP",
"Pix2StructConfig",
"Pix2StructTextConfig",
"Pix2StructVisionConfig",
],
"processing_pix2struct": ["Pix2StructProcessor"],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = ["Pix2StructImageProcessor"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
"PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST",
"Pix2StructPreTrainedModel",
"Pix2StructForConditionalGeneration",
"Pix2StructVisionModel",
"Pix2StructTextModel",
]
if TYPE_CHECKING:
from .configuration_pixastruct import (
PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP,
PixaStructConfig,
PixaStructTextConfig,
PixaStructVisionConfig,
)
from .processing_pixastruct import PixaStructProcessor
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .image_processing_pixastruct import PixaStructImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_pixastruct import (
PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST,
PixaStructForConditionalGeneration,
PixaStructPreTrainedModel,
PixaStructTextModel,
PixaStructVisionModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 59 | 1 |
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError
from transformers import AutoImageProcessor, ViTImageProcessor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test
sys.path.append(str(Path(__file__).parent.parent / "utils"))
from test_module.custom_image_processing import CustomImageProcessor # noqa E402
__A = get_tests_dir("fixtures")
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Tuple:
'''simple docstring'''
lowerCamelCase__: str =mock.Mock()
lowerCamelCase__: Union[str, Any] =500
lowerCamelCase__: Optional[Any] ={}
lowerCamelCase__: Any =HTTPError
lowerCamelCase__: Union[str, Any] ={}
# Download this model to make sure it's in the cache.
lowerCamelCase__: str =ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit")
# Under the mock environment we get a 500 error when trying to reach the model.
with mock.patch("requests.Session.request" , return_value=UpperCAmelCase_) as mock_head:
lowerCamelCase__: Dict =ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit")
# This check we did call the fake head request
mock_head.assert_called()
def SCREAMING_SNAKE_CASE_ (self : str) ->Any:
'''simple docstring'''
lowerCamelCase__: Optional[int] =ViTImageProcessor.from_pretrained(
"https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json")
def SCREAMING_SNAKE_CASE_ (self : Dict) ->str:
'''simple docstring'''
with self.assertRaises(UpperCAmelCase_):
# config is in subfolder, the following should not work without specifying the subfolder
lowerCamelCase__: int =AutoImageProcessor.from_pretrained("hf-internal-testing/stable-diffusion-all-variants")
lowerCamelCase__: Any =AutoImageProcessor.from_pretrained(
"hf-internal-testing/stable-diffusion-all-variants" , subfolder="feature_extractor")
self.assertIsNotNone(UpperCAmelCase_)
@is_staging_test
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
@classmethod
def SCREAMING_SNAKE_CASE_ (cls : Dict) ->List[Any]:
'''simple docstring'''
lowerCamelCase__: str =TOKEN
HfFolder.save_token(UpperCAmelCase_)
@classmethod
def SCREAMING_SNAKE_CASE_ (cls : Optional[Any]) ->Optional[int]:
'''simple docstring'''
try:
delete_repo(token=cls._token , repo_id="test-image-processor")
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="valid_org/test-image-processor-org")
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="test-dynamic-image-processor")
except HTTPError:
pass
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Dict:
'''simple docstring'''
lowerCamelCase__: Tuple =ViTImageProcessor.from_pretrained(UpperCAmelCase_)
image_processor.push_to_hub("test-image-processor" , use_auth_token=self._token)
lowerCamelCase__: str =ViTImageProcessor.from_pretrained(F"""{USER}/test-image-processor""")
for k, v in image_processor.__dict__.items():
self.assertEqual(UpperCAmelCase_ , getattr(UpperCAmelCase_ , UpperCAmelCase_))
# Reset repo
delete_repo(token=self._token , repo_id="test-image-processor")
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(
UpperCAmelCase_ , repo_id="test-image-processor" , push_to_hub=UpperCAmelCase_ , use_auth_token=self._token)
lowerCamelCase__: int =ViTImageProcessor.from_pretrained(F"""{USER}/test-image-processor""")
for k, v in image_processor.__dict__.items():
self.assertEqual(UpperCAmelCase_ , getattr(UpperCAmelCase_ , UpperCAmelCase_))
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Any =ViTImageProcessor.from_pretrained(UpperCAmelCase_)
image_processor.push_to_hub("valid_org/test-image-processor" , use_auth_token=self._token)
lowerCamelCase__: int =ViTImageProcessor.from_pretrained("valid_org/test-image-processor")
for k, v in image_processor.__dict__.items():
self.assertEqual(UpperCAmelCase_ , getattr(UpperCAmelCase_ , UpperCAmelCase_))
# Reset repo
delete_repo(token=self._token , repo_id="valid_org/test-image-processor")
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(
UpperCAmelCase_ , repo_id="valid_org/test-image-processor-org" , push_to_hub=UpperCAmelCase_ , use_auth_token=self._token)
lowerCamelCase__: Tuple =ViTImageProcessor.from_pretrained("valid_org/test-image-processor-org")
for k, v in image_processor.__dict__.items():
self.assertEqual(UpperCAmelCase_ , getattr(UpperCAmelCase_ , UpperCAmelCase_))
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->List[Any]:
'''simple docstring'''
CustomImageProcessor.register_for_auto_class()
lowerCamelCase__: Any =CustomImageProcessor.from_pretrained(UpperCAmelCase_)
image_processor.push_to_hub("test-dynamic-image-processor" , use_auth_token=self._token)
# This has added the proper auto_map field to the config
self.assertDictEqual(
image_processor.auto_map , {"AutoImageProcessor": "custom_image_processing.CustomImageProcessor"} , )
lowerCamelCase__: str =AutoImageProcessor.from_pretrained(
F"""{USER}/test-dynamic-image-processor""" , trust_remote_code=UpperCAmelCase_)
# Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module
self.assertEqual(new_image_processor.__class__.__name__ , "CustomImageProcessor")
| 59 |
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_distilbert import DistilBertTokenizer
__A = logging.get_logger(__name__)
__A = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
__A = {
"vocab_file": {
"distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt",
"distilbert-base-uncased-distilled-squad": (
"https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt"
),
"distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt",
"distilbert-base-cased-distilled-squad": (
"https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt"
),
"distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt",
"distilbert-base-multilingual-cased": (
"https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt"
),
},
"tokenizer_file": {
"distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json",
"distilbert-base-uncased-distilled-squad": (
"https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json"
),
"distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json",
"distilbert-base-cased-distilled-squad": (
"https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json"
),
"distilbert-base-german-cased": (
"https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json"
),
"distilbert-base-multilingual-cased": (
"https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json"
),
},
}
__A = {
"distilbert-base-uncased": 512,
"distilbert-base-uncased-distilled-squad": 512,
"distilbert-base-cased": 512,
"distilbert-base-cased-distilled-squad": 512,
"distilbert-base-german-cased": 512,
"distilbert-base-multilingual-cased": 512,
}
__A = {
"distilbert-base-uncased": {"do_lower_case": True},
"distilbert-base-uncased-distilled-squad": {"do_lower_case": True},
"distilbert-base-cased": {"do_lower_case": False},
"distilbert-base-cased-distilled-squad": {"do_lower_case": False},
"distilbert-base-german-cased": {"do_lower_case": False},
"distilbert-base-multilingual-cased": {"do_lower_case": False},
}
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = VOCAB_FILES_NAMES
lowercase_ = PRETRAINED_VOCAB_FILES_MAP
lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowercase_ = PRETRAINED_INIT_CONFIGURATION
lowercase_ = ["input_ids", "attention_mask"]
lowercase_ = DistilBertTokenizer
def __init__(self : Tuple , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[Any]="[UNK]" , UpperCAmelCase_ : Dict="[SEP]" , UpperCAmelCase_ : Dict="[PAD]" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[str]=None , **UpperCAmelCase_ : List[str] , ) ->str:
'''simple docstring'''
super().__init__(
UpperCAmelCase_ , tokenizer_file=UpperCAmelCase_ , do_lower_case=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , tokenize_chinese_chars=UpperCAmelCase_ , strip_accents=UpperCAmelCase_ , **UpperCAmelCase_ , )
lowerCamelCase__: Union[str, Any] =json.loads(self.backend_tokenizer.normalizer.__getstate__())
if (
normalizer_state.get("lowercase" , UpperCAmelCase_) != do_lower_case
or normalizer_state.get("strip_accents" , UpperCAmelCase_) != strip_accents
or normalizer_state.get("handle_chinese_chars" , UpperCAmelCase_) != tokenize_chinese_chars
):
lowerCamelCase__: List[str] =getattr(UpperCAmelCase_ , normalizer_state.pop("type"))
lowerCamelCase__: Optional[int] =do_lower_case
lowerCamelCase__: int =strip_accents
lowerCamelCase__: Any =tokenize_chinese_chars
lowerCamelCase__: Any =normalizer_class(**UpperCAmelCase_)
lowerCamelCase__: str =do_lower_case
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any]=None) ->Dict:
'''simple docstring'''
lowerCamelCase__: str =[self.cls_token_id] + token_ids_a + [self.sep_token_id]
if token_ids_a:
output += token_ids_a + [self.sep_token_id]
return output
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None) ->List[int]:
'''simple docstring'''
lowerCamelCase__: str =[self.sep_token_id]
lowerCamelCase__: str =[self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep) * [0]
return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1]
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None) ->Tuple[str]:
'''simple docstring'''
lowerCamelCase__: str =self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_)
return tuple(UpperCAmelCase_)
| 59 | 1 |
def lowerCAmelCase_ ( __a , __a ) -> Union[str, Any]:
"""simple docstring"""
return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2
def lowerCAmelCase_ ( __a , __a=0 ) -> Union[str, Any]:
"""simple docstring"""
return sorted(__a , key=lambda __a : x[column] )
def lowerCAmelCase_ ( __a , __a , __a=float("inf" ) ) -> Dict:
"""simple docstring"""
for i in range(points_counts - 1 ):
for j in range(i + 1 , __a ):
lowerCamelCase__: List[str] =euclidean_distance_sqr(points[i] , points[j] )
if current_dis < min_dis:
lowerCamelCase__: List[Any] =current_dis
return min_dis
def lowerCAmelCase_ ( __a , __a , __a=float("inf" ) ) -> List[str]:
"""simple docstring"""
for i in range(min(6 , points_counts - 1 ) , __a ):
for j in range(max(0 , i - 6 ) , __a ):
lowerCamelCase__: Union[str, Any] =euclidean_distance_sqr(points[i] , points[j] )
if current_dis < min_dis:
lowerCamelCase__: List[Any] =current_dis
return min_dis
def lowerCAmelCase_ ( __a , __a , __a ) -> Optional[Any]:
"""simple docstring"""
if points_counts <= 3:
return dis_between_closest_pair(__a , __a )
# recursion
lowerCamelCase__: Tuple =points_counts // 2
lowerCamelCase__: Optional[int] =closest_pair_of_points_sqr(
__a , points_sorted_on_y[:mid] , __a )
lowerCamelCase__: Optional[int] =closest_pair_of_points_sqr(
__a , points_sorted_on_y[mid:] , points_counts - mid )
lowerCamelCase__: str =min(__a , __a )
lowerCamelCase__: Any =[]
for point in points_sorted_on_x:
if abs(point[0] - points_sorted_on_x[mid][0] ) < closest_pair_dis:
cross_strip.append(__a )
lowerCamelCase__: int =dis_between_closest_in_strip(
__a , len(__a ) , __a )
return min(__a , __a )
def lowerCAmelCase_ ( __a , __a ) -> List[str]:
"""simple docstring"""
lowerCamelCase__: Any =column_based_sort(__a , column=0 )
lowerCamelCase__: List[Any] =column_based_sort(__a , column=1 )
return (
closest_pair_of_points_sqr(
__a , __a , __a )
) ** 0.5
if __name__ == "__main__":
__A = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]
print("Distance:", closest_pair_of_points(points, len(points)))
| 59 |
import operator as op
def lowerCAmelCase_ ( __a ) -> Tuple:
"""simple docstring"""
lowerCamelCase__: Optional[Any] =[]
lowerCamelCase__: Tuple =lambda __a , __a : int(x / y ) # noqa: E731 integer division operation
lowerCamelCase__: Tuple ={
"^": op.pow,
"*": op.mul,
"/": div,
"+": op.add,
"-": op.sub,
} # operators & their respective operation
# print table header
print("Symbol".center(8 ) , "Action".center(12 ) , "Stack" , sep=" | " )
print("-" * (30 + len(__a )) )
for x in post_fix:
if x.isdigit(): # if x in digit
stack.append(__a ) # append x to stack
# output in tabular format
print(x.rjust(8 ) , ("push(" + x + ")").ljust(12 ) , ",".join(__a ) , sep=" | " )
else:
lowerCamelCase__: List[Any] =stack.pop() # pop stack
# output in tabular format
print("".rjust(8 ) , ("pop(" + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " )
lowerCamelCase__: Optional[Any] =stack.pop() # pop stack
# output in tabular format
print("".rjust(8 ) , ("pop(" + a + ")").ljust(12 ) , ",".join(__a ) , sep=" | " )
stack.append(
str(opr[x](int(__a ) , int(__a ) ) ) ) # evaluate the 2 values popped from stack & push result to stack
# output in tabular format
print(
x.rjust(8 ) , ("push(" + a + x + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " , )
return int(stack[0] )
if __name__ == "__main__":
__A = input("\n\nEnter a Postfix Equation (space separated) = ").split(" ")
print("\n\tResult = ", solve(Postfix))
| 59 | 1 |
from .configuration_bert_masked import MaskedBertConfig
from .modeling_bert_masked import (
MaskedBertForMultipleChoice,
MaskedBertForQuestionAnswering,
MaskedBertForSequenceClassification,
MaskedBertForTokenClassification,
MaskedBertModel,
)
from .modules import *
| 59 |
from collections import defaultdict
from typing import Optional
from ..image_utils import load_image
from ..utils import (
add_end_docstrings,
is_torch_available,
logging,
requires_backends,
)
from .base import PIPELINE_INIT_ARGS, ChunkPipeline
if is_torch_available():
import torch
from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING
__A = logging.get_logger(__name__)
@add_end_docstrings(__SCREAMING_SNAKE_CASE )
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__(self : List[Any] , **UpperCAmelCase_ : Any) ->Any:
'''simple docstring'''
super().__init__(**UpperCAmelCase_)
requires_backends(self , "vision")
requires_backends(self , "torch")
if self.framework != "pt":
raise ValueError(F"""The {self.__class__} is only available in PyTorch.""")
self.check_model_type(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Tuple , **UpperCAmelCase_ : List[Any]) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Optional[int] ={}
lowerCamelCase__: Tuple ={}
lowerCamelCase__: str ={}
# preprocess args
if "points_per_batch" in kwargs:
lowerCamelCase__: Optional[Any] =kwargs["points_per_batch"]
if "points_per_crop" in kwargs:
lowerCamelCase__: int =kwargs["points_per_crop"]
if "crops_n_layers" in kwargs:
lowerCamelCase__: Any =kwargs["crops_n_layers"]
if "crop_overlap_ratio" in kwargs:
lowerCamelCase__: Tuple =kwargs["crop_overlap_ratio"]
if "crop_n_points_downscale_factor" in kwargs:
lowerCamelCase__: List[Any] =kwargs["crop_n_points_downscale_factor"]
# postprocess args
if "pred_iou_thresh" in kwargs:
lowerCamelCase__: List[str] =kwargs["pred_iou_thresh"]
if "stability_score_offset" in kwargs:
lowerCamelCase__: int =kwargs["stability_score_offset"]
if "mask_threshold" in kwargs:
lowerCamelCase__: Optional[int] =kwargs["mask_threshold"]
if "stability_score_thresh" in kwargs:
lowerCamelCase__: str =kwargs["stability_score_thresh"]
if "crops_nms_thresh" in kwargs:
lowerCamelCase__: Any =kwargs["crops_nms_thresh"]
if "output_rle_mask" in kwargs:
lowerCamelCase__: List[Any] =kwargs["output_rle_mask"]
if "output_bboxes_mask" in kwargs:
lowerCamelCase__: List[str] =kwargs["output_bboxes_mask"]
return preprocess_kwargs, forward_params, postprocess_kwargs
def __call__(self : int , UpperCAmelCase_ : Dict , *UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[Any]:
'''simple docstring'''
return super().__call__(UpperCAmelCase_ , *UpperCAmelCase_ , num_workers=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any]=64 , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : float = 512 / 1_500 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 1 , ) ->Dict:
'''simple docstring'''
lowerCamelCase__: Dict =load_image(UpperCAmelCase_)
lowerCamelCase__: List[str] =self.image_processor.size["longest_edge"]
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =self.image_processor.generate_crop_boxes(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: str =self.image_processor(images=UpperCAmelCase_ , return_tensors="pt")
with self.device_placement():
if self.framework == "pt":
lowerCamelCase__: str =self.get_inference_context()
with inference_context():
lowerCamelCase__: Union[str, Any] =self._ensure_tensor_on_device(UpperCAmelCase_ , device=self.device)
lowerCamelCase__: Optional[Any] =self.model.get_image_embeddings(model_inputs.pop("pixel_values"))
lowerCamelCase__: str =image_embeddings
lowerCamelCase__: int =grid_points.shape[1]
lowerCamelCase__: int =points_per_batch if points_per_batch is not None else n_points
if points_per_batch <= 0:
raise ValueError(
"Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. "
"To return all points at once, set points_per_batch to None")
for i in range(0 , UpperCAmelCase_ , UpperCAmelCase_):
lowerCamelCase__: int =grid_points[:, i : i + points_per_batch, :, :]
lowerCamelCase__: Optional[Any] =input_labels[:, i : i + points_per_batch]
lowerCamelCase__: Dict =i == n_points - points_per_batch
yield {
"input_points": batched_points,
"input_labels": labels,
"input_boxes": crop_boxes,
"is_last": is_last,
**model_inputs,
}
def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=0.88 , UpperCAmelCase_ : Optional[Any]=0.95 , UpperCAmelCase_ : Tuple=0 , UpperCAmelCase_ : Any=1 , ) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Any =model_inputs.pop("input_boxes")
lowerCamelCase__: Dict =model_inputs.pop("is_last")
lowerCamelCase__: int =model_inputs.pop("original_sizes").tolist()
lowerCamelCase__: Union[str, Any] =model_inputs.pop("reshaped_input_sizes").tolist()
lowerCamelCase__: Union[str, Any] =self.model(**UpperCAmelCase_)
# post processing happens here in order to avoid CPU GPU copies of ALL the masks
lowerCamelCase__: Optional[int] =model_outputs["pred_masks"]
lowerCamelCase__: Union[str, Any] =self.image_processor.post_process_masks(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , binarize=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =model_outputs["iou_scores"]
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =self.image_processor.filter_masks(
masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , )
return {
"masks": masks,
"is_last": is_last,
"boxes": boxes,
"iou_scores": iou_scores,
}
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Optional[int]=0.7 , ) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Any =[]
lowerCamelCase__: Optional[int] =[]
lowerCamelCase__: List[str] =[]
for model_output in model_outputs:
all_scores.append(model_output.pop("iou_scores"))
all_masks.extend(model_output.pop("masks"))
all_boxes.append(model_output.pop("boxes"))
lowerCamelCase__: str =torch.cat(UpperCAmelCase_)
lowerCamelCase__: List[str] =torch.cat(UpperCAmelCase_)
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Dict =self.image_processor.post_process_for_mask_generation(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: List[str] =defaultdict(UpperCAmelCase_)
for output in model_outputs:
for k, v in output.items():
extra[k].append(UpperCAmelCase_)
lowerCamelCase__: Any ={}
if output_rle_mask:
lowerCamelCase__: Union[str, Any] =rle_mask
if output_bboxes_mask:
lowerCamelCase__: int =bounding_boxes
return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
| 59 | 1 |
import argparse
import json
from collections import OrderedDict
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor
from transformers.utils import logging
logging.set_verbosity_info()
__A = logging.get_logger(__name__)
def lowerCAmelCase_ ( __a , __a , __a , __a ) -> Dict:
"""simple docstring"""
lowerCamelCase__: Optional[Any] =original_name.split("." )[0]
lowerCamelCase__: Any =key.split("." )
lowerCamelCase__: Optional[Any] =int(key_list[key_list.index(__a ) - 2] )
lowerCamelCase__: List[str] =int(key_list[key_list.index(__a ) - 1] )
lowerCamelCase__: Union[str, Any] =orig_block_num - offset
lowerCamelCase__: List[str] =key.replace(F"""{orig_block_num}.{layer_num}.{original_name}""" , F"""block.{new_block_num}.{layer_num}.{new_name}""" )
return key
def lowerCAmelCase_ ( __a ) -> List[str]:
"""simple docstring"""
lowerCamelCase__: Union[str, Any] =OrderedDict()
lowerCamelCase__ , lowerCamelCase__: int =0, 0
for key, value in state_dict.items():
if key.startswith("network" ):
lowerCamelCase__: Union[str, Any] =key.replace("network" , "poolformer.encoder" )
if "proj" in key:
# Works for the first embedding as well as the internal embedding layers
if key.endswith("bias" ) and "patch_embed" not in key:
patch_emb_offset += 1
lowerCamelCase__: List[Any] =key[: key.find("proj" )]
lowerCamelCase__: Optional[Any] =key.replace(__a , F"""patch_embeddings.{total_embed_found}.""" )
lowerCamelCase__: List[str] =key.replace("proj" , "projection" )
if key.endswith("bias" ):
total_embed_found += 1
if "patch_embeddings" in key:
lowerCamelCase__: Tuple ="poolformer.encoder." + key
if "mlp.fc1" in key:
lowerCamelCase__: Union[str, Any] =replace_key_with_offset(__a , __a , "mlp.fc1" , "output.conv1" )
if "mlp.fc2" in key:
lowerCamelCase__: Optional[int] =replace_key_with_offset(__a , __a , "mlp.fc2" , "output.conv2" )
if "norm1" in key:
lowerCamelCase__: Union[str, Any] =replace_key_with_offset(__a , __a , "norm1" , "before_norm" )
if "norm2" in key:
lowerCamelCase__: List[str] =replace_key_with_offset(__a , __a , "norm2" , "after_norm" )
if "layer_scale_1" in key:
lowerCamelCase__: str =replace_key_with_offset(__a , __a , "layer_scale_1" , "layer_scale_1" )
if "layer_scale_2" in key:
lowerCamelCase__: Any =replace_key_with_offset(__a , __a , "layer_scale_2" , "layer_scale_2" )
if "head" in key:
lowerCamelCase__: int =key.replace("head" , "classifier" )
lowerCamelCase__: List[str] =value
return new_state_dict
def lowerCAmelCase_ ( ) -> List[Any]:
"""simple docstring"""
lowerCamelCase__: Optional[int] ="http://images.cocodataset.org/val2017/000000039769.jpg"
lowerCamelCase__: Optional[int] =Image.open(requests.get(__a , stream=__a ).raw )
return image
@torch.no_grad()
def lowerCAmelCase_ ( __a , __a , __a ) -> Any:
"""simple docstring"""
lowerCamelCase__: Any =PoolFormerConfig()
# set attributes based on model_name
lowerCamelCase__: int ="huggingface/label-files"
lowerCamelCase__: Any =model_name[-3:]
lowerCamelCase__: int =1000
lowerCamelCase__: List[Any] ="imagenet-1k-id2label.json"
lowerCamelCase__: Any =(1, 1000)
# set config attributes
lowerCamelCase__: Optional[Any] =json.load(open(hf_hub_download(__a , __a , repo_type="dataset" ) , "r" ) )
lowerCamelCase__: Dict ={int(__a ): v for k, v in idalabel.items()}
lowerCamelCase__: Optional[int] =idalabel
lowerCamelCase__: int ={v: k for k, v in idalabel.items()}
if size == "s12":
lowerCamelCase__: Optional[int] =[2, 2, 6, 2]
lowerCamelCase__: List[Any] =[64, 128, 320, 512]
lowerCamelCase__: Optional[Any] =4.0
lowerCamelCase__: int =0.9
elif size == "s24":
lowerCamelCase__: List[str] =[4, 4, 12, 4]
lowerCamelCase__: str =[64, 128, 320, 512]
lowerCamelCase__: Any =4.0
lowerCamelCase__: str =0.9
elif size == "s36":
lowerCamelCase__: Any =[6, 6, 18, 6]
lowerCamelCase__: Optional[int] =[64, 128, 320, 512]
lowerCamelCase__: int =4.0
lowerCamelCase__: Dict =1e-6
lowerCamelCase__: Any =0.9
elif size == "m36":
lowerCamelCase__: Union[str, Any] =[6, 6, 18, 6]
lowerCamelCase__: Optional[Any] =[96, 192, 384, 768]
lowerCamelCase__: Tuple =4.0
lowerCamelCase__: Union[str, Any] =1e-6
lowerCamelCase__: Optional[int] =0.9_5
elif size == "m48":
lowerCamelCase__: Optional[Any] =[8, 8, 24, 8]
lowerCamelCase__: str =[96, 192, 384, 768]
lowerCamelCase__: Optional[int] =4.0
lowerCamelCase__: Dict =1e-6
lowerCamelCase__: Any =0.9_5
else:
raise ValueError(F"""Size {size} not supported""" )
# load image processor
lowerCamelCase__: str =PoolFormerImageProcessor(crop_pct=__a )
# Prepare image
lowerCamelCase__: Optional[int] =prepare_img()
lowerCamelCase__: Optional[int] =image_processor(images=__a , return_tensors="pt" ).pixel_values
logger.info(F"""Converting model {model_name}...""" )
# load original state dict
lowerCamelCase__: List[str] =torch.load(__a , map_location=torch.device("cpu" ) )
# rename keys
lowerCamelCase__: List[Any] =rename_keys(__a )
# create HuggingFace model and load state dict
lowerCamelCase__: List[str] =PoolFormerForImageClassification(__a )
model.load_state_dict(__a )
model.eval()
# Define image processor
lowerCamelCase__: Optional[int] =PoolFormerImageProcessor(crop_pct=__a )
lowerCamelCase__: Optional[int] =image_processor(images=prepare_img() , return_tensors="pt" ).pixel_values
# forward pass
lowerCamelCase__: List[Any] =model(__a )
lowerCamelCase__: Any =outputs.logits
# define expected logit slices for different models
if size == "s12":
lowerCamelCase__: Optional[int] =torch.tensor([-0.3_0_4_5, -0.6_7_5_8, -0.4_8_6_9] )
elif size == "s24":
lowerCamelCase__: Union[str, Any] =torch.tensor([0.4_4_0_2, -0.1_3_7_4, -0.8_0_4_5] )
elif size == "s36":
lowerCamelCase__: Dict =torch.tensor([-0.6_0_8_0, -0.5_1_3_3, -0.5_8_9_8] )
elif size == "m36":
lowerCamelCase__: Tuple =torch.tensor([0.3_9_5_2, 0.2_2_6_3, -1.2_6_6_8] )
elif size == "m48":
lowerCamelCase__: Dict =torch.tensor([0.1_1_6_7, -0.0_6_5_6, -0.3_4_2_3] )
else:
raise ValueError(F"""Size {size} not supported""" )
# verify logits
assert logits.shape == expected_shape
assert torch.allclose(logits[0, :3] , __a , atol=1e-2 )
# finally, save model and image processor
logger.info(F"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""" )
Path(__a ).mkdir(exist_ok=__a )
model.save_pretrained(__a )
print(F"""Saving image processor to {pytorch_dump_folder_path}""" )
image_processor.save_pretrained(__a )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
parser.add_argument(
"--model_name",
default="poolformer_s12",
type=str,
help="Name of the model you'd like to convert.",
)
parser.add_argument(
"--checkpoint_path", default=None, type=str, help="Path to the original PyTorch checkpoint (.pth file)."
)
parser.add_argument(
"--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model."
)
__A = parser.parse_args()
convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
| 59 |
from transformers import BertTokenizerFast
from .custom_tokenization import CustomTokenizer
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = CustomTokenizer
pass
| 59 | 1 |
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 lowerCAmelCase_ ( __a ) -> List[Any]:
"""simple docstring"""
warnings.warn(
"The preprocess method is deprecated and will be removed in a future version. Please"
" use VaeImageProcessor.preprocess instead" , __a , )
if isinstance(__a , torch.Tensor ):
return image
elif isinstance(__a , PIL.Image.Image ):
lowerCamelCase__: Dict =[image]
if isinstance(image[0] , PIL.Image.Image ):
lowerCamelCase__ , lowerCamelCase__: Tuple =image[0].size
lowerCamelCase__ , lowerCamelCase__: Optional[Any] =(x - x % 8 for x in (w, h)) # resize to integer multiple of 8
lowerCamelCase__: Optional[int] =[np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["lanczos"] ) )[None, :] for i in image]
lowerCamelCase__: Tuple =np.concatenate(__a , axis=0 )
lowerCamelCase__: int =np.array(__a ).astype(np.floataa ) / 2_5_5.0
lowerCamelCase__: int =image.transpose(0 , 3 , 1 , 2 )
lowerCamelCase__: Optional[int] =2.0 * image - 1.0
lowerCamelCase__: Tuple =torch.from_numpy(__a )
elif isinstance(image[0] , torch.Tensor ):
lowerCamelCase__: List[str] =torch.cat(__a , dim=0 )
return image
def lowerCAmelCase_ ( __a ) -> Any:
"""simple docstring"""
if isinstance(__a , torch.Tensor ):
return mask
elif isinstance(__a , PIL.Image.Image ):
lowerCamelCase__: Dict =[mask]
if isinstance(mask[0] , PIL.Image.Image ):
lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =mask[0].size
lowerCamelCase__ , lowerCamelCase__: Optional[int] =(x - x % 32 for x in (w, h)) # resize to integer multiple of 32
lowerCamelCase__: Union[str, Any] =[np.array(m.convert("L" ).resize((w, h) , resample=PIL_INTERPOLATION["nearest"] ) )[None, :] for m in mask]
lowerCamelCase__: int =np.concatenate(__a , axis=0 )
lowerCamelCase__: str =mask.astype(np.floataa ) / 2_5_5.0
lowerCamelCase__: int =0
lowerCamelCase__: Optional[Any] =1
lowerCamelCase__: Tuple =torch.from_numpy(__a )
elif isinstance(mask[0] , torch.Tensor ):
lowerCamelCase__: Dict =torch.cat(__a , dim=0 )
return mask
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = 42
lowercase_ = 42
def __init__(self : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str) ->int:
'''simple docstring'''
super().__init__()
self.register_modules(unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_)
@torch.no_grad()
def __call__(self : Union[str, Any] , UpperCAmelCase_ : Union[torch.Tensor, PIL.Image.Image] , UpperCAmelCase_ : Union[torch.Tensor, PIL.Image.Image] , UpperCAmelCase_ : int = 250 , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , ) ->Union[ImagePipelineOutput, Tuple]:
'''simple docstring'''
lowerCamelCase__: Tuple =image
lowerCamelCase__: List[str] =_preprocess_image(UpperCAmelCase_)
lowerCamelCase__: Union[str, Any] =original_image.to(device=self.device , dtype=self.unet.dtype)
lowerCamelCase__: Optional[int] =_preprocess_mask(UpperCAmelCase_)
lowerCamelCase__: str =mask_image.to(device=self.device , dtype=self.unet.dtype)
lowerCamelCase__: Optional[Any] =original_image.shape[0]
# sample gaussian noise to begin the loop
if isinstance(UpperCAmelCase_ , UpperCAmelCase_) and len(UpperCAmelCase_) != batch_size:
raise ValueError(
F"""You have passed a list of generators of length {len(UpperCAmelCase_)}, but requested an effective batch"""
F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""")
lowerCamelCase__: int =original_image.shape
lowerCamelCase__: Tuple =randn_tensor(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=self.device , dtype=self.unet.dtype)
# set step values
self.scheduler.set_timesteps(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , self.device)
lowerCamelCase__: List[str] =eta
lowerCamelCase__: Optional[int] =self.scheduler.timesteps[0] + 1
lowerCamelCase__: Union[str, Any] =generator[0] if isinstance(UpperCAmelCase_ , UpperCAmelCase_) else generator
for i, t in enumerate(self.progress_bar(self.scheduler.timesteps)):
if t < t_last:
# predict the noise residual
lowerCamelCase__: Union[str, Any] =self.unet(UpperCAmelCase_ , UpperCAmelCase_).sample
# compute previous image: x_t -> x_t-1
lowerCamelCase__: Optional[Any] =self.scheduler.step(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_).prev_sample
else:
# compute the reverse: x_t-1 -> x_t
lowerCamelCase__: Optional[Any] =self.scheduler.undo_step(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: List[Any] =t
lowerCamelCase__: Any =(image / 2 + 0.5).clamp(0 , 1)
lowerCamelCase__: Optional[Any] =image.cpu().permute(0 , 2 , 3 , 1).numpy()
if output_type == "pil":
lowerCamelCase__: int =self.numpy_to_pil(UpperCAmelCase_)
if not return_dict:
return (image,)
return ImagePipelineOutput(images=UpperCAmelCase_)
| 59 |
import inspect
import os
import unittest
import torch
import accelerate
from accelerate import Accelerator
from accelerate.test_utils import execute_subprocess_async, require_multi_gpu
from accelerate.utils import patch_environment
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: List[Any] =inspect.getfile(accelerate.test_utils)
lowerCamelCase__: List[Any] =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_script.py"])
lowerCamelCase__: Any =os.path.sep.join(
mod_file.split(os.path.sep)[:-1] + ["scripts", "test_distributed_data_loop.py"])
lowerCamelCase__: Tuple =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_ops.py"])
@require_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : str) ->str:
'''simple docstring'''
print(F"""Found {torch.cuda.device_count()} devices.""")
lowerCamelCase__: Union[str, Any] =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path]
with patch_environment(omp_num_threads=1):
execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy())
@require_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[Any]:
'''simple docstring'''
print(F"""Found {torch.cuda.device_count()} devices.""")
lowerCamelCase__: Dict =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path]
print(F"""Command: {cmd}""")
with patch_environment(omp_num_threads=1):
execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy())
@require_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Tuple:
'''simple docstring'''
lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__)]
with patch_environment(omp_num_threads=1):
execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy())
@require_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]:
'''simple docstring'''
print(F"""Found {torch.cuda.device_count()} devices, using 2 devices only""")
lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path]
with patch_environment(omp_num_threads=1 , cuda_visible_devices="0,1"):
execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy())
if __name__ == "__main__":
__A = Accelerator()
__A = (accelerator.state.process_index + 2, 10)
__A = torch.randint(0, 10, shape).to(accelerator.device)
__A = ""
__A = accelerator.pad_across_processes(tensor)
if tensora.shape[0] != accelerator.state.num_processes + 1:
error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0."
if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor):
error_msg += "Tensors have different values."
if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0):
error_msg += "Padding was not done with the right value (0)."
__A = accelerator.pad_across_processes(tensor, pad_first=True)
if tensora.shape[0] != accelerator.state.num_processes + 1:
error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0."
__A = accelerator.state.num_processes - accelerator.state.process_index - 1
if not torch.equal(tensora[index:], tensor):
error_msg += "Tensors have different values."
if not torch.all(tensora[:index] == 0):
error_msg += "Padding was not done with the right value (0)."
# Raise error at the end to make sure we don't stop at the first failure.
if len(error_msg) > 0:
raise ValueError(error_msg)
| 59 | 1 |
import inspect
import unittest
from transformers import SegformerConfig, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
MODEL_MAPPING,
SegformerForImageClassification,
SegformerForSemanticSegmentation,
SegformerModel,
)
from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import SegformerImageProcessor
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Any:
'''simple docstring'''
lowerCamelCase__: Dict =self.config_class(**self.inputs_dict)
self.parent.assertTrue(hasattr(UpperCAmelCase_ , "hidden_sizes"))
self.parent.assertTrue(hasattr(UpperCAmelCase_ , "num_attention_heads"))
self.parent.assertTrue(hasattr(UpperCAmelCase_ , "num_encoder_blocks"))
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__(self : Any , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[Any]=13 , UpperCAmelCase_ : Tuple=64 , UpperCAmelCase_ : str=3 , UpperCAmelCase_ : str=4 , UpperCAmelCase_ : Dict=[2, 2, 2, 2] , UpperCAmelCase_ : Dict=[8, 4, 2, 1] , UpperCAmelCase_ : Optional[Any]=[16, 32, 64, 128] , UpperCAmelCase_ : str=[1, 4, 8, 16] , UpperCAmelCase_ : Optional[int]=[1, 2, 4, 8] , UpperCAmelCase_ : str=True , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : List[str]="gelu" , UpperCAmelCase_ : str=0.1 , UpperCAmelCase_ : Any=0.1 , UpperCAmelCase_ : List[str]=0.02 , UpperCAmelCase_ : Dict=3 , UpperCAmelCase_ : List[Any]=None , ) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__: Optional[int] =parent
lowerCamelCase__: int =batch_size
lowerCamelCase__: Tuple =image_size
lowerCamelCase__: List[Any] =num_channels
lowerCamelCase__: Dict =num_encoder_blocks
lowerCamelCase__: Dict =sr_ratios
lowerCamelCase__: Union[str, Any] =depths
lowerCamelCase__: Tuple =hidden_sizes
lowerCamelCase__: Any =downsampling_rates
lowerCamelCase__: int =num_attention_heads
lowerCamelCase__: Tuple =is_training
lowerCamelCase__: Any =use_labels
lowerCamelCase__: str =hidden_act
lowerCamelCase__: Tuple =hidden_dropout_prob
lowerCamelCase__: Union[str, Any] =attention_probs_dropout_prob
lowerCamelCase__: int =initializer_range
lowerCamelCase__: int =num_labels
lowerCamelCase__: List[Any] =scope
def SCREAMING_SNAKE_CASE_ (self : str) ->Dict:
'''simple docstring'''
lowerCamelCase__: List[Any] =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
lowerCamelCase__: Union[str, Any] =None
if self.use_labels:
lowerCamelCase__: List[Any] =ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels)
lowerCamelCase__: List[str] =self.get_config()
return config, pixel_values, labels
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[str]:
'''simple docstring'''
return SegformerConfig(
image_size=self.image_size , num_channels=self.num_channels , num_encoder_blocks=self.num_encoder_blocks , depths=self.depths , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , )
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: str =SegformerModel(config=UpperCAmelCase_)
model.to(UpperCAmelCase_)
model.eval()
lowerCamelCase__: Union[str, Any] =model(UpperCAmelCase_)
lowerCamelCase__: List[str] =self.image_size // (self.downsampling_rates[-1] * 2)
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width))
def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[Any]) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Tuple =self.num_labels
lowerCamelCase__: Any =SegformerForSemanticSegmentation(UpperCAmelCase_)
model.to(UpperCAmelCase_)
model.eval()
lowerCamelCase__: Any =model(UpperCAmelCase_)
self.parent.assertEqual(
result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4))
lowerCamelCase__: Union[str, Any] =model(UpperCAmelCase_ , labels=UpperCAmelCase_)
self.parent.assertEqual(
result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4))
self.parent.assertGreater(result.loss , 0.0)
def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Union[str, Any]) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =1
lowerCamelCase__: Union[str, Any] =SegformerForSemanticSegmentation(config=UpperCAmelCase_)
model.to(UpperCAmelCase_)
model.eval()
lowerCamelCase__: str =torch.randint(0 , 1 , (self.batch_size, self.image_size, self.image_size)).to(UpperCAmelCase_)
lowerCamelCase__: Tuple =model(UpperCAmelCase_ , labels=UpperCAmelCase_)
self.parent.assertGreater(result.loss , 0.0)
def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =self.prepare_config_and_inputs()
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =config_and_inputs
lowerCamelCase__: List[str] ={"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ):
'''simple docstring'''
lowercase_ = (
(
SegformerModel,
SegformerForSemanticSegmentation,
SegformerForImageClassification,
)
if is_torch_available()
else ()
)
lowercase_ = (
{
"feature-extraction": SegformerModel,
"image-classification": SegformerForImageClassification,
"image-segmentation": SegformerForSemanticSegmentation,
}
if is_torch_available()
else {}
)
lowercase_ = True
lowercase_ = False
lowercase_ = False
lowercase_ = False
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Any:
'''simple docstring'''
lowerCamelCase__: Tuple =SegformerModelTester(self)
lowerCamelCase__: str =SegformerConfigTester(self , config_class=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Dict) ->List[str]:
'''simple docstring'''
self.config_tester.run_common_tests()
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: str =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any) ->str:
'''simple docstring'''
lowerCamelCase__: List[str] =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_binary_image_segmentation(*UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : int) ->int:
'''simple docstring'''
lowerCamelCase__: Any =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_segmentation(*UpperCAmelCase_)
@unittest.skip("SegFormer does not use inputs_embeds")
def SCREAMING_SNAKE_CASE_ (self : str) ->Tuple:
'''simple docstring'''
pass
@unittest.skip("SegFormer does not have get_input_embeddings method and get_output_embeddings methods")
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Optional[Any]:
'''simple docstring'''
pass
def SCREAMING_SNAKE_CASE_ (self : Any) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowerCamelCase__: Union[str, Any] =model_class(UpperCAmelCase_)
lowerCamelCase__: Dict =inspect.signature(model.forward)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
lowerCamelCase__: int =[*signature.parameters.keys()]
lowerCamelCase__: str =["pixel_values"]
self.assertListEqual(arg_names[:1] , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Tuple:
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.model_tester.prepare_config_and_inputs_for_common()
lowerCamelCase__: List[Any] =True
for model_class in self.all_model_classes:
lowerCamelCase__: Optional[int] =True
lowerCamelCase__: Dict =False
lowerCamelCase__: Any =True
lowerCamelCase__: str =model_class(UpperCAmelCase_)
model.to(UpperCAmelCase_)
model.eval()
with torch.no_grad():
lowerCamelCase__: Optional[int] =model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_))
lowerCamelCase__: Tuple =outputs.attentions
lowerCamelCase__: List[Any] =sum(self.model_tester.depths)
self.assertEqual(len(UpperCAmelCase_) , UpperCAmelCase_)
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
lowerCamelCase__: Optional[Any] =True
lowerCamelCase__: List[str] =model_class(UpperCAmelCase_)
model.to(UpperCAmelCase_)
model.eval()
with torch.no_grad():
lowerCamelCase__: Optional[Any] =model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_))
lowerCamelCase__: List[Any] =outputs.attentions
self.assertEqual(len(UpperCAmelCase_) , UpperCAmelCase_)
# verify the first attentions (first block, first layer)
lowerCamelCase__: Dict =(self.model_tester.image_size // 4) ** 2
lowerCamelCase__: int =(self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
self.assertListEqual(
list(attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , )
# verify the last attentions (last block, last layer)
lowerCamelCase__: Any =(self.model_tester.image_size // 32) ** 2
lowerCamelCase__: str =(self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2
self.assertListEqual(
list(attentions[-1].shape[-3:]) , [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len] , )
lowerCamelCase__: int =len(UpperCAmelCase_)
# Check attention is always last and order is fine
lowerCamelCase__: Union[str, Any] =True
lowerCamelCase__: List[Any] =True
lowerCamelCase__: Dict =model_class(UpperCAmelCase_)
model.to(UpperCAmelCase_)
model.eval()
with torch.no_grad():
lowerCamelCase__: Union[str, Any] =model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_))
self.assertEqual(out_len + 1 , len(UpperCAmelCase_))
lowerCamelCase__: Any =outputs.attentions
self.assertEqual(len(UpperCAmelCase_) , UpperCAmelCase_)
# verify the first attentions (first block, first layer)
lowerCamelCase__: Union[str, Any] =(self.model_tester.image_size // 4) ** 2
lowerCamelCase__: Any =(self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
self.assertListEqual(
list(self_attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , )
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Dict:
'''simple docstring'''
def check_hidden_states_output(UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any]):
lowerCamelCase__: List[str] =model_class(UpperCAmelCase_)
model.to(UpperCAmelCase_)
model.eval()
with torch.no_grad():
lowerCamelCase__: str =model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_))
lowerCamelCase__: Any =outputs.hidden_states
lowerCamelCase__: Any =self.model_tester.num_encoder_blocks
self.assertEqual(len(UpperCAmelCase_) , UpperCAmelCase_)
# verify the first hidden states (first block)
self.assertListEqual(
list(hidden_states[0].shape[-3:]) , [
self.model_tester.hidden_sizes[0],
self.model_tester.image_size // 4,
self.model_tester.image_size // 4,
] , )
lowerCamelCase__ , lowerCamelCase__: str =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowerCamelCase__: Tuple =True
check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
lowerCamelCase__: Any =True
check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Optional[int]:
'''simple docstring'''
if not self.model_tester.is_training:
return
lowerCamelCase__ , lowerCamelCase__: List[str] =self.model_tester.prepare_config_and_inputs_for_common()
lowerCamelCase__: Tuple =True
for model_class in self.all_model_classes:
if model_class in get_values(UpperCAmelCase_):
continue
lowerCamelCase__: List[str] =model_class(UpperCAmelCase_)
model.to(UpperCAmelCase_)
model.train()
lowerCamelCase__: Tuple =self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =model(**UpperCAmelCase_).loss
loss.backward()
@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests.")
def SCREAMING_SNAKE_CASE_ (self : str) ->Tuple:
'''simple docstring'''
pass
@slow
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Optional[int]:
'''simple docstring'''
for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowerCamelCase__: Union[str, Any] =SegformerModel.from_pretrained(UpperCAmelCase_)
self.assertIsNotNone(UpperCAmelCase_)
def lowerCAmelCase_ ( ) -> Dict:
"""simple docstring"""
lowerCamelCase__: Any =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_torch
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
@slow
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->List[Any]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =SegformerImageProcessor(
image_scale=(512, 512) , keep_ratio=UpperCAmelCase_ , align=UpperCAmelCase_ , do_random_crop=UpperCAmelCase_)
lowerCamelCase__: Tuple =SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512").to(
UpperCAmelCase_)
lowerCamelCase__: Tuple =prepare_img()
lowerCamelCase__: Union[str, Any] =image_processor(images=UpperCAmelCase_ , return_tensors="pt")
lowerCamelCase__: List[str] =encoded_inputs.pixel_values.to(UpperCAmelCase_)
with torch.no_grad():
lowerCamelCase__: Dict =model(UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =torch.Size((1, model.config.num_labels, 128, 128))
self.assertEqual(outputs.logits.shape , UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =torch.tensor(
[
[[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]],
[[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]],
[[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]],
]).to(UpperCAmelCase_)
self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , UpperCAmelCase_ , atol=1E-4))
@slow
def SCREAMING_SNAKE_CASE_ (self : Any) ->str:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =SegformerImageProcessor(
image_scale=(512, 512) , keep_ratio=UpperCAmelCase_ , align=UpperCAmelCase_ , do_random_crop=UpperCAmelCase_)
lowerCamelCase__: str =SegformerForSemanticSegmentation.from_pretrained(
"nvidia/segformer-b1-finetuned-cityscapes-1024-1024").to(UpperCAmelCase_)
lowerCamelCase__: Tuple =prepare_img()
lowerCamelCase__: Optional[Any] =image_processor(images=UpperCAmelCase_ , return_tensors="pt")
lowerCamelCase__: Tuple =encoded_inputs.pixel_values.to(UpperCAmelCase_)
with torch.no_grad():
lowerCamelCase__: List[Any] =model(UpperCAmelCase_)
lowerCamelCase__: Any =torch.Size((1, model.config.num_labels, 128, 128))
self.assertEqual(outputs.logits.shape , UpperCAmelCase_)
lowerCamelCase__: Optional[int] =torch.tensor(
[
[[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]],
[[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]],
[[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]],
]).to(UpperCAmelCase_)
self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , UpperCAmelCase_ , atol=1E-1))
@slow
def SCREAMING_SNAKE_CASE_ (self : str) ->Dict:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =SegformerImageProcessor(
image_scale=(512, 512) , keep_ratio=UpperCAmelCase_ , align=UpperCAmelCase_ , do_random_crop=UpperCAmelCase_)
lowerCamelCase__: str =SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512").to(
UpperCAmelCase_)
lowerCamelCase__: int =prepare_img()
lowerCamelCase__: Tuple =image_processor(images=UpperCAmelCase_ , return_tensors="pt")
lowerCamelCase__: Any =encoded_inputs.pixel_values.to(UpperCAmelCase_)
with torch.no_grad():
lowerCamelCase__: Union[str, Any] =model(UpperCAmelCase_)
lowerCamelCase__: Dict =outputs.logits.detach().cpu()
lowerCamelCase__: Any =image_processor.post_process_semantic_segmentation(outputs=UpperCAmelCase_ , target_sizes=[(500, 300)])
lowerCamelCase__: List[str] =torch.Size((500, 300))
self.assertEqual(segmentation[0].shape , UpperCAmelCase_)
lowerCamelCase__: Tuple =image_processor.post_process_semantic_segmentation(outputs=UpperCAmelCase_)
lowerCamelCase__: Dict =torch.Size((128, 128))
self.assertEqual(segmentation[0].shape , UpperCAmelCase_)
| 59 |
from typing import List, Optional, Tuple, Union
import PIL
import torch
from torchvision import transforms
from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
from diffusers.schedulers import DDIMScheduler
from diffusers.utils import randn_tensor
__A = transforms.Compose(
[
transforms.Resize((256, 256)),
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5]),
]
)
def lowerCAmelCase_ ( __a ) -> str:
"""simple docstring"""
if isinstance(__a , torch.Tensor ):
return image
elif isinstance(__a , PIL.Image.Image ):
lowerCamelCase__: Any =[image]
lowerCamelCase__: Optional[Any] =[trans(img.convert("RGB" ) ) for img in image]
lowerCamelCase__: Dict =torch.stack(__a )
return image
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__(self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple) ->int:
'''simple docstring'''
super().__init__()
# make sure scheduler can always be converted to DDIM
lowerCamelCase__: Tuple =DDIMScheduler.from_config(scheduler.config)
self.register_modules(unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Union[str, Any]) ->Dict:
'''simple docstring'''
if strength < 0 or strength > 1:
raise ValueError(F"""The value of strength should in [0.0, 1.0] but is {strength}""")
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple) ->Tuple:
'''simple docstring'''
lowerCamelCase__: int =min(int(num_inference_steps * strength) , UpperCAmelCase_)
lowerCamelCase__: str =max(num_inference_steps - init_timestep , 0)
lowerCamelCase__: int =self.scheduler.timesteps[t_start:]
return timesteps, num_inference_steps - t_start
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int]=None) ->Optional[int]:
'''simple docstring'''
if not isinstance(UpperCAmelCase_ , (torch.Tensor, PIL.Image.Image, list)):
raise ValueError(
F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(UpperCAmelCase_)}""")
lowerCamelCase__: Optional[int] =image.to(device=UpperCAmelCase_ , dtype=UpperCAmelCase_)
if isinstance(UpperCAmelCase_ , UpperCAmelCase_) and len(UpperCAmelCase_) != batch_size:
raise ValueError(
F"""You have passed a list of generators of length {len(UpperCAmelCase_)}, but requested an effective batch"""
F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""")
lowerCamelCase__: Dict =init_latents.shape
lowerCamelCase__: int =randn_tensor(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=UpperCAmelCase_)
# get latents
print("add noise to latents at timestep" , UpperCAmelCase_)
lowerCamelCase__: Union[str, Any] =self.scheduler.add_noise(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: int =init_latents
return latents
@torch.no_grad()
def __call__(self : Tuple , UpperCAmelCase_ : Union[torch.FloatTensor, PIL.Image.Image] = None , UpperCAmelCase_ : float = 0.8 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , ) ->Union[ImagePipelineOutput, Tuple]:
'''simple docstring'''
self.check_inputs(UpperCAmelCase_)
# 2. Preprocess image
lowerCamelCase__: Dict =preprocess(UpperCAmelCase_)
# 3. set timesteps
self.scheduler.set_timesteps(UpperCAmelCase_ , device=self.device)
lowerCamelCase__ , lowerCamelCase__: str =self.get_timesteps(UpperCAmelCase_ , UpperCAmelCase_ , self.device)
lowerCamelCase__: Optional[int] =timesteps[:1].repeat(UpperCAmelCase_)
# 4. Prepare latent variables
lowerCamelCase__: int =self.prepare_latents(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , self.unet.dtype , self.device , UpperCAmelCase_)
lowerCamelCase__: Tuple =latents
# 5. Denoising loop
for t in self.progress_bar(UpperCAmelCase_):
# 1. predict noise model_output
lowerCamelCase__: Dict =self.unet(UpperCAmelCase_ , UpperCAmelCase_).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
lowerCamelCase__: Optional[int] =self.scheduler.step(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , eta=UpperCAmelCase_ , use_clipped_model_output=UpperCAmelCase_ , generator=UpperCAmelCase_ , ).prev_sample
lowerCamelCase__: str =(image / 2 + 0.5).clamp(0 , 1)
lowerCamelCase__: Optional[Any] =image.cpu().permute(0 , 2 , 3 , 1).numpy()
if output_type == "pil":
lowerCamelCase__: Dict =self.numpy_to_pil(UpperCAmelCase_)
if not return_dict:
return (image, latent_timestep.item())
return ImagePipelineOutput(images=UpperCAmelCase_)
| 59 | 1 |
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_distilbert import DistilBertTokenizer
__A = logging.get_logger(__name__)
__A = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
__A = {
"vocab_file": {
"distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt",
"distilbert-base-uncased-distilled-squad": (
"https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt"
),
"distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt",
"distilbert-base-cased-distilled-squad": (
"https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt"
),
"distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt",
"distilbert-base-multilingual-cased": (
"https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt"
),
},
"tokenizer_file": {
"distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json",
"distilbert-base-uncased-distilled-squad": (
"https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json"
),
"distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json",
"distilbert-base-cased-distilled-squad": (
"https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json"
),
"distilbert-base-german-cased": (
"https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json"
),
"distilbert-base-multilingual-cased": (
"https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json"
),
},
}
__A = {
"distilbert-base-uncased": 512,
"distilbert-base-uncased-distilled-squad": 512,
"distilbert-base-cased": 512,
"distilbert-base-cased-distilled-squad": 512,
"distilbert-base-german-cased": 512,
"distilbert-base-multilingual-cased": 512,
}
__A = {
"distilbert-base-uncased": {"do_lower_case": True},
"distilbert-base-uncased-distilled-squad": {"do_lower_case": True},
"distilbert-base-cased": {"do_lower_case": False},
"distilbert-base-cased-distilled-squad": {"do_lower_case": False},
"distilbert-base-german-cased": {"do_lower_case": False},
"distilbert-base-multilingual-cased": {"do_lower_case": False},
}
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = VOCAB_FILES_NAMES
lowercase_ = PRETRAINED_VOCAB_FILES_MAP
lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowercase_ = PRETRAINED_INIT_CONFIGURATION
lowercase_ = ["input_ids", "attention_mask"]
lowercase_ = DistilBertTokenizer
def __init__(self : Tuple , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[Any]="[UNK]" , UpperCAmelCase_ : Dict="[SEP]" , UpperCAmelCase_ : Dict="[PAD]" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[str]=None , **UpperCAmelCase_ : List[str] , ) ->str:
'''simple docstring'''
super().__init__(
UpperCAmelCase_ , tokenizer_file=UpperCAmelCase_ , do_lower_case=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , tokenize_chinese_chars=UpperCAmelCase_ , strip_accents=UpperCAmelCase_ , **UpperCAmelCase_ , )
lowerCamelCase__: Union[str, Any] =json.loads(self.backend_tokenizer.normalizer.__getstate__())
if (
normalizer_state.get("lowercase" , UpperCAmelCase_) != do_lower_case
or normalizer_state.get("strip_accents" , UpperCAmelCase_) != strip_accents
or normalizer_state.get("handle_chinese_chars" , UpperCAmelCase_) != tokenize_chinese_chars
):
lowerCamelCase__: List[str] =getattr(UpperCAmelCase_ , normalizer_state.pop("type"))
lowerCamelCase__: Optional[int] =do_lower_case
lowerCamelCase__: int =strip_accents
lowerCamelCase__: Any =tokenize_chinese_chars
lowerCamelCase__: Any =normalizer_class(**UpperCAmelCase_)
lowerCamelCase__: str =do_lower_case
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any]=None) ->Dict:
'''simple docstring'''
lowerCamelCase__: str =[self.cls_token_id] + token_ids_a + [self.sep_token_id]
if token_ids_a:
output += token_ids_a + [self.sep_token_id]
return output
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None) ->List[int]:
'''simple docstring'''
lowerCamelCase__: str =[self.sep_token_id]
lowerCamelCase__: str =[self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep) * [0]
return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1]
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None) ->Tuple[str]:
'''simple docstring'''
lowerCamelCase__: str =self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_)
return tuple(UpperCAmelCase_)
| 59 |
import argparse
import os
import pickle
import sys
import torch
from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl
from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils
from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
logging.set_verbosity_info()
# We do this to be able to load python 2 datasets pickles
# See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918
__A = data_utils.TransfoXLTokenizer
__A = data_utils.TransfoXLCorpus
__A = data_utils
__A = data_utils
def lowerCAmelCase_ ( __a , __a , __a , __a ) -> List[str]:
"""simple docstring"""
if transfo_xl_dataset_file:
# Convert a pre-processed corpus (see original TensorFlow repo)
with open(__a , "rb" ) as fp:
lowerCamelCase__: Optional[Any] =pickle.load(__a , encoding="latin1" )
# Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term)
lowerCamelCase__: Union[str, Any] =pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["pretrained_vocab_file"]
print(F"""Save vocabulary to {pytorch_vocab_dump_path}""" )
lowerCamelCase__: Any =corpus.vocab.__dict__
torch.save(__a , __a )
lowerCamelCase__: Dict =corpus.__dict__
corpus_dict_no_vocab.pop("vocab" , __a )
lowerCamelCase__: List[str] =pytorch_dump_folder_path + "/" + CORPUS_NAME
print(F"""Save dataset to {pytorch_dataset_dump_path}""" )
torch.save(__a , __a )
if tf_checkpoint_path:
# Convert a pre-trained TensorFlow model
lowerCamelCase__: Optional[Any] =os.path.abspath(__a )
lowerCamelCase__: Dict =os.path.abspath(__a )
print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" )
# Initialise PyTorch model
if transfo_xl_config_file == "":
lowerCamelCase__: int =TransfoXLConfig()
else:
lowerCamelCase__: Any =TransfoXLConfig.from_json_file(__a )
print(F"""Building PyTorch model from configuration: {config}""" )
lowerCamelCase__: List[Any] =TransfoXLLMHeadModel(__a )
lowerCamelCase__: List[str] =load_tf_weights_in_transfo_xl(__a , __a , __a )
# Save pytorch-model
lowerCamelCase__: List[str] =os.path.join(__a , __a )
lowerCamelCase__: Tuple =os.path.join(__a , __a )
print(F"""Save PyTorch model to {os.path.abspath(__a )}""" )
torch.save(model.state_dict() , __a )
print(F"""Save configuration file to {os.path.abspath(__a )}""" )
with open(__a , "w" , encoding="utf-8" ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
parser.add_argument(
"--pytorch_dump_folder_path",
default=None,
type=str,
required=True,
help="Path to the folder to store the PyTorch model or dataset/vocab.",
)
parser.add_argument(
"--tf_checkpoint_path",
default="",
type=str,
help="An optional path to a TensorFlow checkpoint path to be converted.",
)
parser.add_argument(
"--transfo_xl_config_file",
default="",
type=str,
help=(
"An optional config json file corresponding to the pre-trained BERT model. \n"
"This specifies the model architecture."
),
)
parser.add_argument(
"--transfo_xl_dataset_file",
default="",
type=str,
help="An optional dataset file to be converted in a vocabulary.",
)
__A = parser.parse_args()
convert_transfo_xl_checkpoint_to_pytorch(
args.tf_checkpoint_path,
args.transfo_xl_config_file,
args.pytorch_dump_folder_path,
args.transfo_xl_dataset_file,
)
| 59 | 1 |
import unittest
from transformers import SPIECE_UNDERLINE
from transformers.models.speechta import SpeechTaTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from transformers.tokenization_utils import AddedToken
from ...test_tokenization_common import TokenizerTesterMixin
__A = get_tests_dir("fixtures/test_sentencepiece_bpe_char.model")
@require_sentencepiece
@require_tokenizers
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ):
'''simple docstring'''
lowercase_ = SpeechTaTokenizer
lowercase_ = False
lowercase_ = True
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Any:
'''simple docstring'''
super().setUp()
# We have a SentencePiece fixture for testing
lowerCamelCase__: Optional[int] =SpeechTaTokenizer(UpperCAmelCase_)
lowerCamelCase__: List[Any] =AddedToken("<mask>" , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_)
lowerCamelCase__: int =mask_token
tokenizer.add_special_tokens({"mask_token": mask_token})
tokenizer.add_tokens(["<ctc_blank>"])
tokenizer.save_pretrained(self.tmpdirname)
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : int) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: int ="this is a test"
lowerCamelCase__: int ="this is a test"
return input_text, output_text
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : int=False , UpperCAmelCase_ : List[Any]=20 , UpperCAmelCase_ : List[str]=5) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: List[str] =self.get_input_output_texts(UpperCAmelCase_)
lowerCamelCase__: Union[str, Any] =tokenizer.encode(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_)
lowerCamelCase__: List[Any] =tokenizer.decode(UpperCAmelCase_ , clean_up_tokenization_spaces=UpperCAmelCase_)
return text, ids
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->List[str]:
'''simple docstring'''
lowerCamelCase__: Any ="<pad>"
lowerCamelCase__: Dict =1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_) , UpperCAmelCase_)
self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_) , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: int =list(self.get_tokenizer().get_vocab().keys())
self.assertEqual(vocab_keys[0] , "<s>")
self.assertEqual(vocab_keys[1] , "<pad>")
self.assertEqual(vocab_keys[-4] , "œ")
self.assertEqual(vocab_keys[-2] , "<mask>")
self.assertEqual(vocab_keys[-1] , "<ctc_blank>")
self.assertEqual(len(UpperCAmelCase_) , 81)
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Optional[Any]:
'''simple docstring'''
self.assertEqual(self.get_tokenizer().vocab_size , 79)
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Dict:
'''simple docstring'''
lowerCamelCase__: Optional[int] =self.get_tokenizers(do_lower_case=UpperCAmelCase_)
for tokenizer in tokenizers:
with self.subTest(F"""{tokenizer.__class__.__name__}"""):
lowerCamelCase__: Optional[int] =tokenizer.vocab_size
lowerCamelCase__: Any =len(UpperCAmelCase_)
self.assertNotEqual(UpperCAmelCase_ , 0)
# We usually have added tokens from the start in tests because our vocab fixtures are
# smaller than the original vocabs - let's not assert this
# self.assertEqual(vocab_size, all_size)
lowerCamelCase__: Union[str, Any] =["aaaaa bbbbbb", "cccccccccdddddddd"]
lowerCamelCase__: Optional[int] =tokenizer.add_tokens(UpperCAmelCase_)
lowerCamelCase__: str =tokenizer.vocab_size
lowerCamelCase__: List[str] =len(UpperCAmelCase_)
self.assertNotEqual(UpperCAmelCase_ , 0)
self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_)
self.assertEqual(UpperCAmelCase_ , len(UpperCAmelCase_))
self.assertEqual(UpperCAmelCase_ , all_size + len(UpperCAmelCase_))
lowerCamelCase__: List[Any] =tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l" , add_special_tokens=UpperCAmelCase_)
self.assertGreaterEqual(len(UpperCAmelCase_) , 4)
self.assertGreater(tokens[0] , tokenizer.vocab_size - 1)
self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1)
lowerCamelCase__: Optional[Any] ={"eos_token": ">>>>|||<||<<|<<", "pad_token": "<<<<<|||>|>>>>|>"}
lowerCamelCase__: Dict =tokenizer.add_special_tokens(UpperCAmelCase_)
lowerCamelCase__: str =tokenizer.vocab_size
lowerCamelCase__: List[Any] =len(UpperCAmelCase_)
self.assertNotEqual(UpperCAmelCase_ , 0)
self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_)
self.assertEqual(UpperCAmelCase_ , len(UpperCAmelCase_))
self.assertEqual(UpperCAmelCase_ , all_size_a + len(UpperCAmelCase_))
lowerCamelCase__: Tuple =tokenizer.encode(
">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l" , add_special_tokens=UpperCAmelCase_)
self.assertGreaterEqual(len(UpperCAmelCase_) , 6)
self.assertGreater(tokens[0] , tokenizer.vocab_size - 1)
self.assertGreater(tokens[0] , tokens[1])
self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1)
self.assertGreater(tokens[-3] , tokens[-4])
self.assertEqual(tokens[0] , tokenizer.eos_token_id)
self.assertEqual(tokens[-3] , tokenizer.pad_token_id)
def SCREAMING_SNAKE_CASE_ (self : str) ->int:
'''simple docstring'''
pass
def SCREAMING_SNAKE_CASE_ (self : Dict) ->int:
'''simple docstring'''
pass
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[Any]:
'''simple docstring'''
lowerCamelCase__: List[str] =self.get_tokenizer()
lowerCamelCase__: Dict =tokenizer.tokenize("This is a test")
# fmt: off
self.assertListEqual(UpperCAmelCase_ , [SPIECE_UNDERLINE, "T", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "a", SPIECE_UNDERLINE, "t", "e", "s", "t"])
# fmt: on
self.assertListEqual(
tokenizer.convert_tokens_to_ids(UpperCAmelCase_) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , )
lowerCamelCase__: str =tokenizer.tokenize("I was born in 92000, and this is falsé.")
self.assertListEqual(
UpperCAmelCase_ , [SPIECE_UNDERLINE, "I", SPIECE_UNDERLINE, "w", "a", "s", SPIECE_UNDERLINE, "b", "o", "r", "n", SPIECE_UNDERLINE, "i", "n", SPIECE_UNDERLINE, "92000", ",", SPIECE_UNDERLINE, "a", "n", "d", SPIECE_UNDERLINE, "t", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "f", "a", "l", "s", "é", "."])
lowerCamelCase__: List[Any] =tokenizer.convert_tokens_to_ids(UpperCAmelCase_)
# fmt: off
self.assertListEqual(UpperCAmelCase_ , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26])
# fmt: on
lowerCamelCase__: Optional[int] =tokenizer.convert_ids_to_tokens(UpperCAmelCase_)
self.assertListEqual(
UpperCAmelCase_ , [SPIECE_UNDERLINE, "I", SPIECE_UNDERLINE, "w", "a", "s", SPIECE_UNDERLINE, "b", "o", "r", "n", SPIECE_UNDERLINE, "i", "n", SPIECE_UNDERLINE, "<unk>", ",", SPIECE_UNDERLINE, "a", "n", "d", SPIECE_UNDERLINE, "t", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "f", "a", "l", "s", "é", "."])
@slow
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Any:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =[
"Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides "
"general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural "
"Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained "
"models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.",
"BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly "
"conditioning on both left and right context in all layers.",
"The quick brown fox jumps over the lazy dog.",
]
# fmt: off
lowerCamelCase__: Any ={
"input_ids": [
[4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2],
[4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
],
"attention_mask": [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
]
}
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=UpperCAmelCase_ , model_name="microsoft/speecht5_asr" , revision="c5ef64c71905caeccde0e4462ef3f9077224c524" , sequences=UpperCAmelCase_ , )
| 59 |
from collections import UserDict
from typing import List, Union
from ..utils import (
add_end_docstrings,
is_tf_available,
is_torch_available,
is_vision_available,
logging,
requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_vision_available():
from PIL import Image
from ..image_utils import load_image
if is_torch_available():
from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
if is_tf_available():
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
from ..tf_utils import stable_softmax
__A = logging.get_logger(__name__)
@add_end_docstrings(__SCREAMING_SNAKE_CASE )
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__(self : Optional[int] , **UpperCAmelCase_ : List[Any]) ->List[str]:
'''simple docstring'''
super().__init__(**UpperCAmelCase_)
requires_backends(self , "vision")
self.check_model_type(
TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
if self.framework == "tf"
else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING)
def __call__(self : List[str] , UpperCAmelCase_ : Union[str, List[str], "Image", List["Image"]] , **UpperCAmelCase_ : List[Any]) ->Tuple:
'''simple docstring'''
return super().__call__(UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[Any] , **UpperCAmelCase_ : Optional[int]) ->Any:
'''simple docstring'''
lowerCamelCase__: Optional[int] ={}
if "candidate_labels" in kwargs:
lowerCamelCase__: Tuple =kwargs["candidate_labels"]
if "hypothesis_template" in kwargs:
lowerCamelCase__: Tuple =kwargs["hypothesis_template"]
return preprocess_params, {}, {}
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Optional[Any]="This is a photo of {}.") ->str:
'''simple docstring'''
lowerCamelCase__: int =load_image(UpperCAmelCase_)
lowerCamelCase__: Any =self.image_processor(images=[image] , return_tensors=self.framework)
lowerCamelCase__: Any =candidate_labels
lowerCamelCase__: List[str] =[hypothesis_template.format(UpperCAmelCase_) for x in candidate_labels]
lowerCamelCase__: int =self.tokenizer(UpperCAmelCase_ , return_tensors=self.framework , padding=UpperCAmelCase_)
lowerCamelCase__: str =[text_inputs]
return inputs
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Any) ->Tuple:
'''simple docstring'''
lowerCamelCase__: int =model_inputs.pop("candidate_labels")
lowerCamelCase__: List[str] =model_inputs.pop("text_inputs")
if isinstance(text_inputs[0] , UpperCAmelCase_):
lowerCamelCase__: List[Any] =text_inputs[0]
else:
# Batching case.
lowerCamelCase__: List[Any] =text_inputs[0][0]
lowerCamelCase__: List[str] =self.model(**UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: str ={
"candidate_labels": candidate_labels,
"logits": outputs.logits_per_image,
}
return model_outputs
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Union[str, Any]) ->int:
'''simple docstring'''
lowerCamelCase__: List[Any] =model_outputs.pop("candidate_labels")
lowerCamelCase__: Optional[int] =model_outputs["logits"][0]
if self.framework == "pt":
lowerCamelCase__: Optional[Any] =logits.softmax(dim=-1).squeeze(-1)
lowerCamelCase__: Optional[Any] =probs.tolist()
if not isinstance(UpperCAmelCase_ , UpperCAmelCase_):
lowerCamelCase__: Optional[int] =[scores]
elif self.framework == "tf":
lowerCamelCase__: List[str] =stable_softmax(UpperCAmelCase_ , axis=-1)
lowerCamelCase__: Optional[int] =probs.numpy().tolist()
else:
raise ValueError(F"""Unsupported framework: {self.framework}""")
lowerCamelCase__: Optional[int] =[
{"score": score, "label": candidate_label}
for score, candidate_label in sorted(zip(UpperCAmelCase_ , UpperCAmelCase_) , key=lambda UpperCAmelCase_: -x[0])
]
return result
| 59 | 1 |
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 = logging.get_logger(__name__) # pylint: disable=invalid-name
__A = 256
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = ["melgan"]
def __init__(self : Tuple , UpperCAmelCase_ : SpectrogramNotesEncoder , UpperCAmelCase_ : SpectrogramContEncoder , UpperCAmelCase_ : TaFilmDecoder , UpperCAmelCase_ : DDPMScheduler , UpperCAmelCase_ : OnnxRuntimeModel if is_onnx_available() else Any , ) ->None:
'''simple docstring'''
super().__init__()
# From MELGAN
lowerCamelCase__: List[Any] =math.log(1E-5) # Matches MelGAN training.
lowerCamelCase__: str =4.0 # Largest value for most examples
lowerCamelCase__: Dict =128
self.register_modules(
notes_encoder=UpperCAmelCase_ , continuous_encoder=UpperCAmelCase_ , decoder=UpperCAmelCase_ , scheduler=UpperCAmelCase_ , melgan=UpperCAmelCase_ , )
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Any=(-1.0, 1.0) , UpperCAmelCase_ : Dict=False) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: str =output_range
if clip:
lowerCamelCase__: Any =torch.clip(UpperCAmelCase_ , self.min_value , self.max_value)
# Scale to [0, 1].
lowerCamelCase__: 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 SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any]=(-1.0, 1.0) , UpperCAmelCase_ : List[str]=False) ->Dict:
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: List[Any] =input_range
lowerCamelCase__: List[str] =torch.clip(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) if clip else outputs
# Scale to [0, 1].
lowerCamelCase__: 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 SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[Any]) ->int:
'''simple docstring'''
lowerCamelCase__: Dict =input_tokens > 0
lowerCamelCase__ , lowerCamelCase__: int =self.notes_encoder(
encoder_input_tokens=UpperCAmelCase_ , encoder_inputs_mask=UpperCAmelCase_)
lowerCamelCase__ , lowerCamelCase__: Dict =self.continuous_encoder(
encoder_inputs=UpperCAmelCase_ , encoder_inputs_mask=UpperCAmelCase_)
return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)]
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Tuple) ->int:
'''simple docstring'''
lowerCamelCase__: Tuple =noise_time
if not torch.is_tensor(UpperCAmelCase_):
lowerCamelCase__: Tuple =torch.tensor([timesteps] , dtype=torch.long , device=input_tokens.device)
elif torch.is_tensor(UpperCAmelCase_) and len(timesteps.shape) == 0:
lowerCamelCase__: Union[str, Any] =timesteps[None].to(input_tokens.device)
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
lowerCamelCase__: List[Any] =timesteps * torch.ones(input_tokens.shape[0] , dtype=timesteps.dtype , device=timesteps.device)
lowerCamelCase__: Tuple =self.decoder(
encodings_and_masks=UpperCAmelCase_ , decoder_input_tokens=UpperCAmelCase_ , decoder_noise_time=UpperCAmelCase_)
return logits
@torch.no_grad()
def __call__(self : Union[str, Any] , UpperCAmelCase_ : List[List[int]] , UpperCAmelCase_ : Optional[torch.Generator] = None , UpperCAmelCase_ : int = 100 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : str = "numpy" , UpperCAmelCase_ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , UpperCAmelCase_ : int = 1 , ) ->Union[AudioPipelineOutput, Tuple]:
'''simple docstring'''
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_)}.""")
lowerCamelCase__: List[str] =np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] , dtype=np.floataa)
lowerCamelCase__: Union[str, Any] =np.zeros([1, 0, self.n_dims] , np.floataa)
lowerCamelCase__: Optional[int] =torch.ones((1, TARGET_FEATURE_LENGTH) , dtype=UpperCAmelCase_ , device=self.device)
for i, encoder_input_tokens in enumerate(UpperCAmelCase_):
if i == 0:
lowerCamelCase__: Optional[Any] =torch.from_numpy(pred_mel[:1].copy()).to(
device=self.device , dtype=self.decoder.dtype)
# The first chunk has no previous context.
lowerCamelCase__: 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.
lowerCamelCase__: Tuple =ones
lowerCamelCase__: Optional[Any] =self.scale_features(
UpperCAmelCase_ , output_range=[-1.0, 1.0] , clip=UpperCAmelCase_)
lowerCamelCase__: 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
lowerCamelCase__: 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)):
lowerCamelCase__: 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
lowerCamelCase__: str =self.scheduler.step(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , generator=UpperCAmelCase_).prev_sample
lowerCamelCase__: Optional[Any] =self.scale_to_features(UpperCAmelCase_ , input_range=[-1.0, 1.0])
lowerCamelCase__: List[Any] =mel[:1]
lowerCamelCase__: Optional[int] =mel.cpu().float().numpy()
lowerCamelCase__: 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":
lowerCamelCase__: Any =self.melgan(input_features=full_pred_mel.astype(np.floataa))
else:
lowerCamelCase__: Union[str, Any] =full_pred_mel
if not return_dict:
return (output,)
return AudioPipelineOutput(audios=UpperCAmelCase_)
| 59 |
import json
import os
from dataclasses import dataclass
from functools import partial
from typing import Callable
import flax.linen as nn
import jax
import jax.numpy as jnp
import joblib
import optax
import wandb
from flax import jax_utils, struct, traverse_util
from flax.serialization import from_bytes, to_bytes
from flax.training import train_state
from flax.training.common_utils import shard
from tqdm.auto import tqdm
from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering
from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = 42
lowercase_ = jnp.floataa
lowercase_ = True
def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]:
'''simple docstring'''
super().setup()
lowerCamelCase__: int =nn.Dense(5 , dtype=self.dtype)
def __call__(self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Any) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =super().__call__(*UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: int =self.cls(outputs[2])
return outputs[:2] + (cls_out,)
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = FlaxBigBirdForNaturalQuestionsModule
def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a ) -> Tuple:
"""simple docstring"""
def cross_entropy(__a , __a , __a=None ):
lowerCamelCase__: Tuple =logits.shape[-1]
lowerCamelCase__: Tuple =(labels[..., None] == jnp.arange(__a )[None]).astype("f4" )
lowerCamelCase__: str =jax.nn.log_softmax(__a , axis=-1 )
lowerCamelCase__: Optional[Any] =-jnp.sum(labels * logits , axis=-1 )
if reduction is not None:
lowerCamelCase__: Optional[Any] =reduction(__a )
return loss
lowerCamelCase__: str =partial(__a , reduction=jnp.mean )
lowerCamelCase__: str =cross_entropy(__a , __a )
lowerCamelCase__: Optional[int] =cross_entropy(__a , __a )
lowerCamelCase__: Optional[Any] =cross_entropy(__a , __a )
return (start_loss + end_loss + pooled_loss) / 3
@dataclass
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
lowercase_ = "google/bigbird-roberta-base"
lowercase_ = 3000
lowercase_ = 1_0500
lowercase_ = 128
lowercase_ = 3
lowercase_ = 1
lowercase_ = 5
# tx_args
lowercase_ = 3E-5
lowercase_ = 0.0
lowercase_ = 2_0000
lowercase_ = 0.0095
lowercase_ = "bigbird-roberta-natural-questions"
lowercase_ = "training-expt"
lowercase_ = "data/nq-training.jsonl"
lowercase_ = "data/nq-validation.jsonl"
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[str]:
'''simple docstring'''
os.makedirs(self.base_dir , exist_ok=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =os.path.join(self.base_dir , self.save_dir)
lowerCamelCase__: List[str] =self.batch_size_per_device * jax.device_count()
@dataclass
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
lowercase_ = 42
lowercase_ = 4096 # no dynamic padding on TPUs
def __call__(self : List[Any] , UpperCAmelCase_ : Optional[Any]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =self.collate_fn(UpperCAmelCase_)
lowerCamelCase__: List[Any] =jax.tree_util.tree_map(UpperCAmelCase_ , UpperCAmelCase_)
return batch
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List[str]) ->List[Any]:
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: List[Any] =self.fetch_inputs(features["input_ids"])
lowerCamelCase__: Union[str, Any] ={
"input_ids": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa),
"attention_mask": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa),
"start_labels": jnp.array(features["start_token"] , dtype=jnp.intaa),
"end_labels": jnp.array(features["end_token"] , dtype=jnp.intaa),
"pooled_labels": jnp.array(features["category"] , dtype=jnp.intaa),
}
return batch
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : list) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Tuple =[self._fetch_inputs(UpperCAmelCase_) for ids in input_ids]
return zip(*UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : list) ->Any:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =[1 for _ in range(len(UpperCAmelCase_))]
while len(UpperCAmelCase_) < self.max_length:
input_ids.append(self.pad_id)
attention_mask.append(0)
return input_ids, attention_mask
def lowerCAmelCase_ ( __a , __a , __a=None ) -> str:
"""simple docstring"""
if seed is not None:
lowerCamelCase__: Any =dataset.shuffle(seed=__a )
for i in range(len(__a ) // batch_size ):
lowerCamelCase__: Any =dataset[i * batch_size : (i + 1) * batch_size]
yield dict(__a )
@partial(jax.pmap , axis_name="batch" )
def lowerCAmelCase_ ( __a , __a , **__a ) -> List[str]:
"""simple docstring"""
def loss_fn(__a ):
lowerCamelCase__: Optional[int] =model_inputs.pop("start_labels" )
lowerCamelCase__: int =model_inputs.pop("end_labels" )
lowerCamelCase__: List[str] =model_inputs.pop("pooled_labels" )
lowerCamelCase__: Optional[int] =state.apply_fn(**__a , params=__a , dropout_rng=__a , train=__a )
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[Any] =outputs
return state.loss_fn(
__a , __a , __a , __a , __a , __a , )
lowerCamelCase__ , lowerCamelCase__: int =jax.random.split(__a )
lowerCamelCase__: Optional[Any] =jax.value_and_grad(__a )
lowerCamelCase__ , lowerCamelCase__: List[str] =grad_fn(state.params )
lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" )
lowerCamelCase__: List[str] =jax.lax.pmean(__a , "batch" )
lowerCamelCase__: List[str] =state.apply_gradients(grads=__a )
return state, metrics, new_drp_rng
@partial(jax.pmap , axis_name="batch" )
def lowerCAmelCase_ ( __a , **__a ) -> List[Any]:
"""simple docstring"""
lowerCamelCase__: int =model_inputs.pop("start_labels" )
lowerCamelCase__: List[str] =model_inputs.pop("end_labels" )
lowerCamelCase__: int =model_inputs.pop("pooled_labels" )
lowerCamelCase__: Optional[Any] =state.apply_fn(**__a , params=state.params , train=__a )
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[str] =outputs
lowerCamelCase__: Optional[int] =state.loss_fn(__a , __a , __a , __a , __a , __a )
lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" )
return metrics
class _SCREAMING_SNAKE_CASE ( train_state.TrainState ):
'''simple docstring'''
lowercase_ = struct.field(pytree_node=__SCREAMING_SNAKE_CASE )
@dataclass
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = None
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int=None) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Dict =model.params
lowerCamelCase__: Tuple =TrainState.create(
apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , loss_fn=UpperCAmelCase_ , )
if ckpt_dir is not None:
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =restore_checkpoint(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Tuple ={
"lr": args.lr,
"init_lr": args.init_lr,
"warmup_steps": args.warmup_steps,
"num_train_steps": num_train_steps,
"weight_decay": args.weight_decay,
}
lowerCamelCase__ , lowerCamelCase__: List[Any] =build_tx(**UpperCAmelCase_)
lowerCamelCase__: str =train_state.TrainState(
step=UpperCAmelCase_ , apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , opt_state=UpperCAmelCase_ , )
lowerCamelCase__: Tuple =args
lowerCamelCase__: Tuple =data_collator
lowerCamelCase__: str =lr
lowerCamelCase__: Dict =params
lowerCamelCase__: List[str] =jax_utils.replicate(UpperCAmelCase_)
return state
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Tuple =self.args
lowerCamelCase__: Any =len(UpperCAmelCase_) // args.batch_size
lowerCamelCase__: List[str] =jax.random.PRNGKey(0)
lowerCamelCase__: Optional[Any] =jax.random.split(UpperCAmelCase_ , jax.device_count())
for epoch in range(args.max_epochs):
lowerCamelCase__: Union[str, Any] =jnp.array(0 , dtype=jnp.floataa)
lowerCamelCase__: str =get_batched_dataset(UpperCAmelCase_ , args.batch_size , seed=UpperCAmelCase_)
lowerCamelCase__: Dict =0
for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc=F"""Running EPOCH-{epoch}"""):
lowerCamelCase__: List[str] =self.data_collator(UpperCAmelCase_)
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.train_step_fn(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_)
running_loss += jax_utils.unreplicate(metrics["loss"])
i += 1
if i % args.logging_steps == 0:
lowerCamelCase__: Optional[int] =jax_utils.unreplicate(state.step)
lowerCamelCase__: List[Any] =running_loss.item() / i
lowerCamelCase__: Tuple =self.scheduler_fn(state_step - 1)
lowerCamelCase__: Union[str, Any] =self.evaluate(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Dict ={
"step": state_step.item(),
"eval_loss": eval_loss.item(),
"tr_loss": tr_loss,
"lr": lr.item(),
}
tqdm.write(str(UpperCAmelCase_))
self.logger.log(UpperCAmelCase_ , commit=UpperCAmelCase_)
if i % args.save_steps == 0:
self.save_checkpoint(args.save_dir + F"""-e{epoch}-s{i}""" , state=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str) ->Any:
'''simple docstring'''
lowerCamelCase__: List[Any] =get_batched_dataset(UpperCAmelCase_ , self.args.batch_size)
lowerCamelCase__: List[str] =len(UpperCAmelCase_) // self.args.batch_size
lowerCamelCase__: str =jnp.array(0 , dtype=jnp.floataa)
lowerCamelCase__: Optional[Any] =0
for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc="Evaluating ... "):
lowerCamelCase__: int =self.data_collator(UpperCAmelCase_)
lowerCamelCase__: str =self.val_step_fn(UpperCAmelCase_ , **UpperCAmelCase_)
running_loss += jax_utils.unreplicate(metrics["loss"])
i += 1
return running_loss / i
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int]) ->int:
'''simple docstring'''
lowerCamelCase__: Any =jax_utils.unreplicate(UpperCAmelCase_)
print(F"""SAVING CHECKPOINT IN {save_dir}""" , end=" ... ")
self.model_save_fn(UpperCAmelCase_ , params=state.params)
with open(os.path.join(UpperCAmelCase_ , "opt_state.msgpack") , "wb") as f:
f.write(to_bytes(state.opt_state))
joblib.dump(self.args , os.path.join(UpperCAmelCase_ , "args.joblib"))
joblib.dump(self.data_collator , os.path.join(UpperCAmelCase_ , "data_collator.joblib"))
with open(os.path.join(UpperCAmelCase_ , "training_state.json") , "w") as f:
json.dump({"step": state.step.item()} , UpperCAmelCase_)
print("DONE")
def lowerCAmelCase_ ( __a , __a ) -> str:
"""simple docstring"""
print(F"""RESTORING CHECKPOINT FROM {save_dir}""" , end=" ... " )
with open(os.path.join(__a , "flax_model.msgpack" ) , "rb" ) as f:
lowerCamelCase__: Tuple =from_bytes(state.params , f.read() )
with open(os.path.join(__a , "opt_state.msgpack" ) , "rb" ) as f:
lowerCamelCase__: Optional[int] =from_bytes(state.opt_state , f.read() )
lowerCamelCase__: Any =joblib.load(os.path.join(__a , "args.joblib" ) )
lowerCamelCase__: Union[str, Any] =joblib.load(os.path.join(__a , "data_collator.joblib" ) )
with open(os.path.join(__a , "training_state.json" ) , "r" ) as f:
lowerCamelCase__: Optional[Any] =json.load(__a )
lowerCamelCase__: Any =training_state["step"]
print("DONE" )
return params, opt_state, step, args, data_collator
def lowerCAmelCase_ ( __a , __a , __a , __a ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase__: int =num_train_steps - warmup_steps
lowerCamelCase__: str =optax.linear_schedule(init_value=__a , end_value=__a , transition_steps=__a )
lowerCamelCase__: Optional[Any] =optax.linear_schedule(init_value=__a , end_value=1e-7 , transition_steps=__a )
lowerCamelCase__: List[Any] =optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] )
return lr
def lowerCAmelCase_ ( __a , __a , __a , __a , __a ) -> str:
"""simple docstring"""
def weight_decay_mask(__a ):
lowerCamelCase__: List[str] =traverse_util.flatten_dict(__a )
lowerCamelCase__: List[str] ={k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()}
return traverse_util.unflatten_dict(__a )
lowerCamelCase__: Optional[Any] =scheduler_fn(__a , __a , __a , __a )
lowerCamelCase__: Tuple =optax.adamw(learning_rate=__a , weight_decay=__a , mask=__a )
return tx, lr
| 59 | 1 |
from __future__ import annotations
import unittest
from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, 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, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel
@require_tf
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
lowercase_ = BlenderbotSmallConfig
lowercase_ = {}
lowercase_ = "gelu"
def __init__(self : str , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple=13 , UpperCAmelCase_ : str=7 , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Union[str, Any]=False , UpperCAmelCase_ : Optional[int]=99 , UpperCAmelCase_ : Optional[int]=32 , UpperCAmelCase_ : Any=2 , UpperCAmelCase_ : Dict=4 , UpperCAmelCase_ : Optional[int]=37 , UpperCAmelCase_ : str=0.1 , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : List[str]=20 , UpperCAmelCase_ : Any=2 , UpperCAmelCase_ : Dict=1 , UpperCAmelCase_ : Tuple=0 , ) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: List[str] =parent
lowerCamelCase__: Optional[int] =batch_size
lowerCamelCase__: Tuple =seq_length
lowerCamelCase__: Tuple =is_training
lowerCamelCase__: Union[str, Any] =use_labels
lowerCamelCase__: Optional[Any] =vocab_size
lowerCamelCase__: Optional[int] =hidden_size
lowerCamelCase__: int =num_hidden_layers
lowerCamelCase__: Union[str, Any] =num_attention_heads
lowerCamelCase__: Tuple =intermediate_size
lowerCamelCase__: Optional[Any] =hidden_dropout_prob
lowerCamelCase__: int =attention_probs_dropout_prob
lowerCamelCase__: List[Any] =max_position_embeddings
lowerCamelCase__: Tuple =eos_token_id
lowerCamelCase__: Tuple =pad_token_id
lowerCamelCase__: Optional[int] =bos_token_id
def SCREAMING_SNAKE_CASE_ (self : Any) ->int:
'''simple docstring'''
lowerCamelCase__: Any =ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size)
lowerCamelCase__: List[Any] =tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size) , 1)
lowerCamelCase__: List[Any] =tf.concat([input_ids, eos_tensor] , axis=1)
lowerCamelCase__: str =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
lowerCamelCase__: List[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 , )
lowerCamelCase__: Optional[Any] =prepare_blenderbot_small_inputs_dict(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
return config, inputs_dict
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : str) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Any =TFBlenderbotSmallModel(config=UpperCAmelCase_).get_decoder()
lowerCamelCase__: str =inputs_dict["input_ids"]
lowerCamelCase__: Optional[int] =input_ids[:1, :]
lowerCamelCase__: List[str] =inputs_dict["attention_mask"][:1, :]
lowerCamelCase__: List[str] =inputs_dict["head_mask"]
lowerCamelCase__: Tuple =1
# first forward pass
lowerCamelCase__: Union[str, Any] =model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , head_mask=UpperCAmelCase_ , use_cache=UpperCAmelCase_)
lowerCamelCase__ , lowerCamelCase__: int =outputs.to_tuple()
# create hypothetical next token and extent to next_input_ids
lowerCamelCase__: Dict =ids_tensor((self.batch_size, 3) , config.vocab_size)
lowerCamelCase__: Optional[int] =tf.cast(ids_tensor((self.batch_size, 3) , 2) , tf.inta)
# append to next input_ids and
lowerCamelCase__: List[str] =tf.concat([input_ids, next_tokens] , axis=-1)
lowerCamelCase__: str =tf.concat([attention_mask, next_attn_mask] , axis=-1)
lowerCamelCase__: List[str] =model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_)[0]
lowerCamelCase__: Optional[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
lowerCamelCase__: List[Any] =int(ids_tensor((1,) , output_from_past.shape[-1]))
lowerCamelCase__: Dict =output_from_no_past[:, -3:, random_slice_idx]
lowerCamelCase__: Dict =output_from_past[:, :, random_slice_idx]
# test that outputs are equal for slice
tf.debugging.assert_near(UpperCAmelCase_ , UpperCAmelCase_ , rtol=1E-3)
def lowerCAmelCase_ ( __a , __a , __a , __a=None , __a=None , __a=None , __a=None , __a=None , ) -> List[str]:
"""simple docstring"""
if attention_mask is None:
lowerCamelCase__: List[str] =tf.cast(tf.math.not_equal(__a , config.pad_token_id ) , tf.inta )
if decoder_attention_mask is None:
lowerCamelCase__: 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:
lowerCamelCase__: str =tf.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
lowerCamelCase__: List[Any] =tf.ones((config.decoder_layers, config.decoder_attention_heads) )
if cross_attn_head_mask is None:
lowerCamelCase__: List[str] =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 _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ):
'''simple docstring'''
lowercase_ = (
(TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else ()
)
lowercase_ = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else ()
lowercase_ = (
{
"conversational": TFBlenderbotSmallForConditionalGeneration,
"feature-extraction": TFBlenderbotSmallModel,
"summarization": TFBlenderbotSmallForConditionalGeneration,
"text2text-generation": TFBlenderbotSmallForConditionalGeneration,
"translation": TFBlenderbotSmallForConditionalGeneration,
}
if is_tf_available()
else {}
)
lowercase_ = True
lowercase_ = False
lowercase_ = False
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =TFBlenderbotSmallModelTester(self)
lowerCamelCase__: Optional[int] =ConfigTester(self , config_class=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Union[str, Any]:
'''simple docstring'''
self.config_tester.run_common_tests()
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Any:
'''simple docstring'''
lowerCamelCase__: str =self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*UpperCAmelCase_)
@require_tokenizers
@require_tf
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
lowercase_ = [
"Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like "
" i'm going to throw up.\nand why is that?"
]
lowercase_ = "facebook/blenderbot_small-90M"
@cached_property
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Tuple:
'''simple docstring'''
return BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M")
@cached_property
def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name)
return model
@slow
def SCREAMING_SNAKE_CASE_ (self : Dict) ->List[str]:
'''simple docstring'''
lowerCamelCase__: Dict =self.tokenizer(self.src_text , return_tensors="tf")
lowerCamelCase__: Optional[int] =self.model.generate(
model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=UpperCAmelCase_ , )
lowerCamelCase__: Any =self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=UpperCAmelCase_)[0]
assert generated_words in (
"i don't know. i just feel like i'm going to throw up. it's not fun.",
"i'm not sure. i just feel like i've been feeling like i have to be in a certain place",
"i'm not sure. i just feel like i've been in a bad situation.",
)
| 59 |
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = ["image_processor", "tokenizer"]
lowercase_ = "ChineseCLIPImageProcessor"
lowercase_ = ("BertTokenizer", "BertTokenizerFast")
def __init__(self : Any , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Union[str, Any]=None , **UpperCAmelCase_ : str) ->Dict:
'''simple docstring'''
lowerCamelCase__: str =None
if "feature_extractor" in kwargs:
warnings.warn(
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
" instead." , UpperCAmelCase_ , )
lowerCamelCase__: Tuple =kwargs.pop("feature_extractor")
lowerCamelCase__: Optional[int] =image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError("You need to specify an `image_processor`.")
if tokenizer is None:
raise ValueError("You need to specify a `tokenizer`.")
super().__init__(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Optional[int] =self.image_processor
def __call__(self : int , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[int]:
'''simple docstring'''
if text is None and images is None:
raise ValueError("You have to specify either text or images. Both cannot be none.")
if text is not None:
lowerCamelCase__: Dict =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if images is not None:
lowerCamelCase__: List[str] =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if text is not None and images is not None:
lowerCamelCase__: Union[str, Any] =image_features.pixel_values
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int) ->str:
'''simple docstring'''
return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any]) ->Dict:
'''simple docstring'''
return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_)
@property
def SCREAMING_SNAKE_CASE_ (self : int) ->List[str]:
'''simple docstring'''
lowerCamelCase__: str =self.tokenizer.model_input_names
lowerCamelCase__: Union[str, Any] =self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
@property
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str:
'''simple docstring'''
warnings.warn(
"`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , UpperCAmelCase_ , )
return self.image_processor_class
| 59 | 1 |
import json
from typing import TYPE_CHECKING, List, Optional, Tuple
from tokenizers import pre_tokenizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
if TYPE_CHECKING:
from transformers.pipelines.conversational import Conversation
__A = logging.get_logger(__name__)
__A = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
__A = {
"tokenizer_file": {
"EleutherAI/gpt-neox-20b": "https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json",
},
}
__A = {
"gpt-neox-20b": 2048,
}
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = VOCAB_FILES_NAMES
lowercase_ = PRETRAINED_VOCAB_FILES_MAP
lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowercase_ = ["input_ids", "attention_mask"]
def __init__(self : int , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : List[str]="<|endoftext|>" , UpperCAmelCase_ : Optional[int]="<|endoftext|>" , UpperCAmelCase_ : int="<|endoftext|>" , UpperCAmelCase_ : int=False , **UpperCAmelCase_ : Optional[int] , ) ->int:
'''simple docstring'''
super().__init__(
UpperCAmelCase_ , UpperCAmelCase_ , tokenizer_file=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , add_prefix_space=UpperCAmelCase_ , **UpperCAmelCase_ , )
lowerCamelCase__: Union[str, Any] =json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
if pre_tok_state.get("add_prefix_space" , UpperCAmelCase_) != add_prefix_space:
lowerCamelCase__: Dict =getattr(UpperCAmelCase_ , pre_tok_state.pop("type"))
lowerCamelCase__: Optional[int] =add_prefix_space
lowerCamelCase__: Any =pre_tok_class(**UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =add_prefix_space
def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None) ->Tuple[str]:
'''simple docstring'''
lowerCamelCase__: str =self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_)
return tuple(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : "Conversation") ->List[int]:
'''simple docstring'''
lowerCamelCase__: int =[]
for is_user, text in conversation.iter_texts():
input_ids.extend(self.encode(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_) + [self.eos_token_id])
if len(UpperCAmelCase_) > self.model_max_length:
lowerCamelCase__: str =input_ids[-self.model_max_length :]
return input_ids
| 59 |
from math import ceil, sqrt
def lowerCAmelCase_ ( __a = 1000000 ) -> int:
"""simple docstring"""
lowerCamelCase__: Any =0
for outer_width in range(3 , (limit // 4) + 2 ):
if outer_width**2 > limit:
lowerCamelCase__: Optional[int] =max(ceil(sqrt(outer_width**2 - limit ) ) , 1 )
else:
lowerCamelCase__: Tuple =1
if (outer_width - hole_width_lower_bound) % 2:
hole_width_lower_bound += 1
answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1
return answer
if __name__ == "__main__":
print(f'{solution() = }')
| 59 | 1 |
import numpy as np
from numpy import ndarray
from scipy.optimize import Bounds, LinearConstraint, minimize
def lowerCAmelCase_ ( __a ) -> float:
"""simple docstring"""
return np.dot(__a , __a )
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__(self : List[str] , *,
UpperCAmelCase_ : float = np.inf , UpperCAmelCase_ : str = "linear" , UpperCAmelCase_ : float = 0.0 , ) ->None:
'''simple docstring'''
lowerCamelCase__: Dict =regularization
lowerCamelCase__: Any =gamma
if kernel == "linear":
lowerCamelCase__: Dict =self.__linear
elif kernel == "rbf":
if self.gamma == 0:
raise ValueError("rbf kernel requires gamma")
if not isinstance(self.gamma , (float, int)):
raise ValueError("gamma must be float or int")
if not self.gamma > 0:
raise ValueError("gamma must be > 0")
lowerCamelCase__: Tuple =self.__rbf
# in the future, there could be a default value like in sklearn
# sklear: def_gamma = 1/(n_features * X.var()) (wiki)
# previously it was 1/(n_features)
else:
lowerCamelCase__: Optional[Any] =F"""Unknown kernel: {kernel}"""
raise ValueError(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float:
'''simple docstring'''
return np.dot(UpperCAmelCase_ , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float:
'''simple docstring'''
return np.exp(-(self.gamma * norm_squared(vectora - vectora)))
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : list[ndarray] , UpperCAmelCase_ : ndarray) ->None:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =observations
lowerCamelCase__: Optional[int] =classes
# using Wolfe's Dual to calculate w.
# Primal problem: minimize 1/2*norm_squared(w)
# constraint: yn(w . xn + b) >= 1
#
# With l a vector
# Dual problem: maximize sum_n(ln) -
# 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm))
# constraint: self.C >= ln >= 0
# and sum_n(ln*yn) = 0
# Then we get w using w = sum_n(ln*yn*xn)
# At the end we can get b ~= mean(yn - w . xn)
#
# Since we use kernels, we only need l_star to calculate b
# and to classify observations
((lowerCamelCase__) , ): List[str] =np.shape(UpperCAmelCase_)
def to_minimize(UpperCAmelCase_ : ndarray) -> float:
lowerCamelCase__: int =0
((lowerCamelCase__) , ): Optional[Any] =np.shape(UpperCAmelCase_)
for i in range(UpperCAmelCase_):
for j in range(UpperCAmelCase_):
s += (
candidate[i]
* candidate[j]
* classes[i]
* classes[j]
* self.kernel(observations[i] , observations[j])
)
return 1 / 2 * s - sum(UpperCAmelCase_)
lowerCamelCase__: List[Any] =LinearConstraint(UpperCAmelCase_ , 0 , 0)
lowerCamelCase__: str =Bounds(0 , self.regularization)
lowerCamelCase__: Union[str, Any] =minimize(
UpperCAmelCase_ , np.ones(UpperCAmelCase_) , bounds=UpperCAmelCase_ , constraints=[ly_contraint]).x
lowerCamelCase__: str =l_star
# calculating mean offset of separation plane to points
lowerCamelCase__: Tuple =0
for i in range(UpperCAmelCase_):
for j in range(UpperCAmelCase_):
s += classes[i] - classes[i] * self.optimum[i] * self.kernel(
observations[i] , observations[j])
lowerCamelCase__: int =s / n
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : ndarray) ->int:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =sum(
self.optimum[n]
* self.classes[n]
* self.kernel(self.observations[n] , UpperCAmelCase_)
for n in range(len(self.classes)))
return 1 if s + self.offset >= 0 else -1
if __name__ == "__main__":
import doctest
doctest.testmod()
| 59 |
def lowerCAmelCase_ ( __a = 50000000 ) -> int:
"""simple docstring"""
lowerCamelCase__: Any =set()
lowerCamelCase__: int =int((limit - 24) ** (1 / 2) )
lowerCamelCase__: Tuple =set(range(3 , prime_square_limit + 1 , 2 ) )
primes.add(2 )
for p in range(3 , prime_square_limit + 1 , 2 ):
if p not in primes:
continue
primes.difference_update(set(range(p * p , prime_square_limit + 1 , __a ) ) )
for primea in primes:
lowerCamelCase__: Optional[int] =primea * primea
for primea in primes:
lowerCamelCase__: List[str] =primea * primea * primea
if square + cube >= limit - 16:
break
for primea in primes:
lowerCamelCase__: int =primea * primea * primea * primea
lowerCamelCase__: Optional[Any] =square + cube + tetr
if total >= limit:
break
ret.add(__a )
return len(__a )
if __name__ == "__main__":
print(f'{solution() = }')
| 59 | 1 |
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import numpy as np
import torch
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, randn_tensor
from .scheduling_utils import SchedulerMixin
@dataclass
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = 42
lowercase_ = 42
lowercase_ = None
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = 2
@register_to_config
def __init__(self : Optional[int] , UpperCAmelCase_ : float = 0.02 , UpperCAmelCase_ : float = 100 , UpperCAmelCase_ : float = 1.007 , UpperCAmelCase_ : float = 80 , UpperCAmelCase_ : float = 0.05 , UpperCAmelCase_ : float = 50 , ) ->List[Any]:
'''simple docstring'''
lowerCamelCase__: Dict =sigma_max
# setable values
lowerCamelCase__: int =None
lowerCamelCase__: np.IntTensor =None
lowerCamelCase__: torch.FloatTensor =None # sigma(t_i)
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : torch.FloatTensor , UpperCAmelCase_ : Optional[int] = None) ->torch.FloatTensor:
'''simple docstring'''
return sample
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, torch.device] = None) ->List[Any]:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =num_inference_steps
lowerCamelCase__: List[Any] =np.arange(0 , self.num_inference_steps)[::-1].copy()
lowerCamelCase__: Union[str, Any] =torch.from_numpy(UpperCAmelCase_).to(UpperCAmelCase_)
lowerCamelCase__: Union[str, Any] =[
(
self.config.sigma_max**2
* (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1))
)
for i in self.timesteps
]
lowerCamelCase__: int =torch.tensor(UpperCAmelCase_ , dtype=torch.floataa , device=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : torch.FloatTensor , UpperCAmelCase_ : float , UpperCAmelCase_ : Optional[torch.Generator] = None) ->Tuple[torch.FloatTensor, float]:
'''simple docstring'''
if self.config.s_min <= sigma <= self.config.s_max:
lowerCamelCase__: List[Any] =min(self.config.s_churn / self.num_inference_steps , 2**0.5 - 1)
else:
lowerCamelCase__: Any =0
# sample eps ~ N(0, S_noise^2 * I)
lowerCamelCase__: Any =self.config.s_noise * randn_tensor(sample.shape , generator=UpperCAmelCase_).to(sample.device)
lowerCamelCase__: Optional[Any] =sigma + gamma * sigma
lowerCamelCase__: str =sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps)
return sample_hat, sigma_hat
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : torch.FloatTensor , UpperCAmelCase_ : float , UpperCAmelCase_ : float , UpperCAmelCase_ : torch.FloatTensor , UpperCAmelCase_ : bool = True , ) ->Union[KarrasVeOutput, Tuple]:
'''simple docstring'''
lowerCamelCase__: Tuple =sample_hat + sigma_hat * model_output
lowerCamelCase__: Optional[Any] =(sample_hat - pred_original_sample) / sigma_hat
lowerCamelCase__: Optional[int] =sample_hat + (sigma_prev - sigma_hat) * derivative
if not return_dict:
return (sample_prev, derivative)
return KarrasVeOutput(
prev_sample=UpperCAmelCase_ , derivative=UpperCAmelCase_ , pred_original_sample=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : torch.FloatTensor , UpperCAmelCase_ : float , UpperCAmelCase_ : float , UpperCAmelCase_ : torch.FloatTensor , UpperCAmelCase_ : torch.FloatTensor , UpperCAmelCase_ : torch.FloatTensor , UpperCAmelCase_ : bool = True , ) ->Union[KarrasVeOutput, Tuple]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =sample_prev + sigma_prev * model_output
lowerCamelCase__: List[Any] =(sample_prev - pred_original_sample) / sigma_prev
lowerCamelCase__: Any =sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr)
if not return_dict:
return (sample_prev, derivative)
return KarrasVeOutput(
prev_sample=UpperCAmelCase_ , derivative=UpperCAmelCase_ , pred_original_sample=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[int]) ->Any:
'''simple docstring'''
raise NotImplementedError()
| 59 |
from __future__ import annotations
from decimal import Decimal
from math import * # noqa: F403
from sympy import diff
def lowerCAmelCase_ ( __a , __a , __a = 10**-10 ) -> float:
"""simple docstring"""
lowerCamelCase__: List[str] =a
while True:
lowerCamelCase__: Optional[Any] =Decimal(__a ) - (
Decimal(eval(__a ) ) / Decimal(eval(str(diff(__a ) ) ) ) # noqa: S307
)
# This number dictates the accuracy of the answer
if abs(eval(__a ) ) < precision: # noqa: S307
return float(__a )
# Let's Execute
if __name__ == "__main__":
# Find root of trigonometric function
# Find value of pi
print(f'The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}')
# Find root of polynomial
print(f'The root of x**2 - 5*x + 2 = 0 is {newton_raphson("x**2 - 5*x + 2", 0.4)}')
# Find Square Root of 5
print(f'The root of log(x) - 1 = 0 is {newton_raphson("log(x) - 1", 2)}')
# Exponential Roots
print(f'The root of exp(x) - 1 = 0 is {newton_raphson("exp(x) - 1", 0)}')
| 59 | 1 |
def lowerCAmelCase_ ( __a ) -> bool:
"""simple docstring"""
lowerCamelCase__: Tuple =[int(__a ) for i in ip_va_address.split("." ) if i.isdigit()]
return len(__a ) == 4 and all(0 <= int(__a ) <= 254 for octet in octets )
if __name__ == "__main__":
__A = input().strip()
__A = "valid" if is_ip_va_address_valid(ip) else "invalid"
print(f'{ip} is a {valid_or_invalid} IP v4 address.')
| 59 |
import numpy as np
from numpy import ndarray
from scipy.optimize import Bounds, LinearConstraint, minimize
def lowerCAmelCase_ ( __a ) -> float:
"""simple docstring"""
return np.dot(__a , __a )
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__(self : List[str] , *,
UpperCAmelCase_ : float = np.inf , UpperCAmelCase_ : str = "linear" , UpperCAmelCase_ : float = 0.0 , ) ->None:
'''simple docstring'''
lowerCamelCase__: Dict =regularization
lowerCamelCase__: Any =gamma
if kernel == "linear":
lowerCamelCase__: Dict =self.__linear
elif kernel == "rbf":
if self.gamma == 0:
raise ValueError("rbf kernel requires gamma")
if not isinstance(self.gamma , (float, int)):
raise ValueError("gamma must be float or int")
if not self.gamma > 0:
raise ValueError("gamma must be > 0")
lowerCamelCase__: Tuple =self.__rbf
# in the future, there could be a default value like in sklearn
# sklear: def_gamma = 1/(n_features * X.var()) (wiki)
# previously it was 1/(n_features)
else:
lowerCamelCase__: Optional[Any] =F"""Unknown kernel: {kernel}"""
raise ValueError(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float:
'''simple docstring'''
return np.dot(UpperCAmelCase_ , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float:
'''simple docstring'''
return np.exp(-(self.gamma * norm_squared(vectora - vectora)))
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : list[ndarray] , UpperCAmelCase_ : ndarray) ->None:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =observations
lowerCamelCase__: Optional[int] =classes
# using Wolfe's Dual to calculate w.
# Primal problem: minimize 1/2*norm_squared(w)
# constraint: yn(w . xn + b) >= 1
#
# With l a vector
# Dual problem: maximize sum_n(ln) -
# 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm))
# constraint: self.C >= ln >= 0
# and sum_n(ln*yn) = 0
# Then we get w using w = sum_n(ln*yn*xn)
# At the end we can get b ~= mean(yn - w . xn)
#
# Since we use kernels, we only need l_star to calculate b
# and to classify observations
((lowerCamelCase__) , ): List[str] =np.shape(UpperCAmelCase_)
def to_minimize(UpperCAmelCase_ : ndarray) -> float:
lowerCamelCase__: int =0
((lowerCamelCase__) , ): Optional[Any] =np.shape(UpperCAmelCase_)
for i in range(UpperCAmelCase_):
for j in range(UpperCAmelCase_):
s += (
candidate[i]
* candidate[j]
* classes[i]
* classes[j]
* self.kernel(observations[i] , observations[j])
)
return 1 / 2 * s - sum(UpperCAmelCase_)
lowerCamelCase__: List[Any] =LinearConstraint(UpperCAmelCase_ , 0 , 0)
lowerCamelCase__: str =Bounds(0 , self.regularization)
lowerCamelCase__: Union[str, Any] =minimize(
UpperCAmelCase_ , np.ones(UpperCAmelCase_) , bounds=UpperCAmelCase_ , constraints=[ly_contraint]).x
lowerCamelCase__: str =l_star
# calculating mean offset of separation plane to points
lowerCamelCase__: Tuple =0
for i in range(UpperCAmelCase_):
for j in range(UpperCAmelCase_):
s += classes[i] - classes[i] * self.optimum[i] * self.kernel(
observations[i] , observations[j])
lowerCamelCase__: int =s / n
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : ndarray) ->int:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =sum(
self.optimum[n]
* self.classes[n]
* self.kernel(self.observations[n] , UpperCAmelCase_)
for n in range(len(self.classes)))
return 1 if s + self.offset >= 0 else -1
if __name__ == "__main__":
import doctest
doctest.testmod()
| 59 | 1 |
from collections import OrderedDict
from ...utils import logging
from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update
from .configuration_auto import CONFIG_MAPPING_NAMES
__A = logging.get_logger(__name__)
__A = OrderedDict(
[
# Base model mapping
("albert", "FlaxAlbertModel"),
("bart", "FlaxBartModel"),
("beit", "FlaxBeitModel"),
("bert", "FlaxBertModel"),
("big_bird", "FlaxBigBirdModel"),
("blenderbot", "FlaxBlenderbotModel"),
("blenderbot-small", "FlaxBlenderbotSmallModel"),
("clip", "FlaxCLIPModel"),
("distilbert", "FlaxDistilBertModel"),
("electra", "FlaxElectraModel"),
("gpt-sw3", "FlaxGPT2Model"),
("gpt2", "FlaxGPT2Model"),
("gpt_neo", "FlaxGPTNeoModel"),
("gptj", "FlaxGPTJModel"),
("longt5", "FlaxLongT5Model"),
("marian", "FlaxMarianModel"),
("mbart", "FlaxMBartModel"),
("mt5", "FlaxMT5Model"),
("opt", "FlaxOPTModel"),
("pegasus", "FlaxPegasusModel"),
("regnet", "FlaxRegNetModel"),
("resnet", "FlaxResNetModel"),
("roberta", "FlaxRobertaModel"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormModel"),
("roformer", "FlaxRoFormerModel"),
("t5", "FlaxT5Model"),
("vision-text-dual-encoder", "FlaxVisionTextDualEncoderModel"),
("vit", "FlaxViTModel"),
("wav2vec2", "FlaxWav2Vec2Model"),
("whisper", "FlaxWhisperModel"),
("xglm", "FlaxXGLMModel"),
("xlm-roberta", "FlaxXLMRobertaModel"),
]
)
__A = OrderedDict(
[
# Model for pre-training mapping
("albert", "FlaxAlbertForPreTraining"),
("bart", "FlaxBartForConditionalGeneration"),
("bert", "FlaxBertForPreTraining"),
("big_bird", "FlaxBigBirdForPreTraining"),
("electra", "FlaxElectraForPreTraining"),
("longt5", "FlaxLongT5ForConditionalGeneration"),
("mbart", "FlaxMBartForConditionalGeneration"),
("mt5", "FlaxMT5ForConditionalGeneration"),
("roberta", "FlaxRobertaForMaskedLM"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"),
("roformer", "FlaxRoFormerForMaskedLM"),
("t5", "FlaxT5ForConditionalGeneration"),
("wav2vec2", "FlaxWav2Vec2ForPreTraining"),
("whisper", "FlaxWhisperForConditionalGeneration"),
("xlm-roberta", "FlaxXLMRobertaForMaskedLM"),
]
)
__A = OrderedDict(
[
# Model for Masked LM mapping
("albert", "FlaxAlbertForMaskedLM"),
("bart", "FlaxBartForConditionalGeneration"),
("bert", "FlaxBertForMaskedLM"),
("big_bird", "FlaxBigBirdForMaskedLM"),
("distilbert", "FlaxDistilBertForMaskedLM"),
("electra", "FlaxElectraForMaskedLM"),
("mbart", "FlaxMBartForConditionalGeneration"),
("roberta", "FlaxRobertaForMaskedLM"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"),
("roformer", "FlaxRoFormerForMaskedLM"),
("xlm-roberta", "FlaxXLMRobertaForMaskedLM"),
]
)
__A = OrderedDict(
[
# Model for Seq2Seq Causal LM mapping
("bart", "FlaxBartForConditionalGeneration"),
("blenderbot", "FlaxBlenderbotForConditionalGeneration"),
("blenderbot-small", "FlaxBlenderbotSmallForConditionalGeneration"),
("encoder-decoder", "FlaxEncoderDecoderModel"),
("longt5", "FlaxLongT5ForConditionalGeneration"),
("marian", "FlaxMarianMTModel"),
("mbart", "FlaxMBartForConditionalGeneration"),
("mt5", "FlaxMT5ForConditionalGeneration"),
("pegasus", "FlaxPegasusForConditionalGeneration"),
("t5", "FlaxT5ForConditionalGeneration"),
]
)
__A = OrderedDict(
[
# Model for Image-classsification
("beit", "FlaxBeitForImageClassification"),
("regnet", "FlaxRegNetForImageClassification"),
("resnet", "FlaxResNetForImageClassification"),
("vit", "FlaxViTForImageClassification"),
]
)
__A = OrderedDict(
[
("vision-encoder-decoder", "FlaxVisionEncoderDecoderModel"),
]
)
__A = OrderedDict(
[
# Model for Causal LM mapping
("bart", "FlaxBartForCausalLM"),
("bert", "FlaxBertForCausalLM"),
("big_bird", "FlaxBigBirdForCausalLM"),
("electra", "FlaxElectraForCausalLM"),
("gpt-sw3", "FlaxGPT2LMHeadModel"),
("gpt2", "FlaxGPT2LMHeadModel"),
("gpt_neo", "FlaxGPTNeoForCausalLM"),
("gptj", "FlaxGPTJForCausalLM"),
("opt", "FlaxOPTForCausalLM"),
("roberta", "FlaxRobertaForCausalLM"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForCausalLM"),
("xglm", "FlaxXGLMForCausalLM"),
("xlm-roberta", "FlaxXLMRobertaForCausalLM"),
]
)
__A = OrderedDict(
[
# Model for Sequence Classification mapping
("albert", "FlaxAlbertForSequenceClassification"),
("bart", "FlaxBartForSequenceClassification"),
("bert", "FlaxBertForSequenceClassification"),
("big_bird", "FlaxBigBirdForSequenceClassification"),
("distilbert", "FlaxDistilBertForSequenceClassification"),
("electra", "FlaxElectraForSequenceClassification"),
("mbart", "FlaxMBartForSequenceClassification"),
("roberta", "FlaxRobertaForSequenceClassification"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForSequenceClassification"),
("roformer", "FlaxRoFormerForSequenceClassification"),
("xlm-roberta", "FlaxXLMRobertaForSequenceClassification"),
]
)
__A = OrderedDict(
[
# Model for Question Answering mapping
("albert", "FlaxAlbertForQuestionAnswering"),
("bart", "FlaxBartForQuestionAnswering"),
("bert", "FlaxBertForQuestionAnswering"),
("big_bird", "FlaxBigBirdForQuestionAnswering"),
("distilbert", "FlaxDistilBertForQuestionAnswering"),
("electra", "FlaxElectraForQuestionAnswering"),
("mbart", "FlaxMBartForQuestionAnswering"),
("roberta", "FlaxRobertaForQuestionAnswering"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForQuestionAnswering"),
("roformer", "FlaxRoFormerForQuestionAnswering"),
("xlm-roberta", "FlaxXLMRobertaForQuestionAnswering"),
]
)
__A = OrderedDict(
[
# Model for Token Classification mapping
("albert", "FlaxAlbertForTokenClassification"),
("bert", "FlaxBertForTokenClassification"),
("big_bird", "FlaxBigBirdForTokenClassification"),
("distilbert", "FlaxDistilBertForTokenClassification"),
("electra", "FlaxElectraForTokenClassification"),
("roberta", "FlaxRobertaForTokenClassification"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForTokenClassification"),
("roformer", "FlaxRoFormerForTokenClassification"),
("xlm-roberta", "FlaxXLMRobertaForTokenClassification"),
]
)
__A = OrderedDict(
[
# Model for Multiple Choice mapping
("albert", "FlaxAlbertForMultipleChoice"),
("bert", "FlaxBertForMultipleChoice"),
("big_bird", "FlaxBigBirdForMultipleChoice"),
("distilbert", "FlaxDistilBertForMultipleChoice"),
("electra", "FlaxElectraForMultipleChoice"),
("roberta", "FlaxRobertaForMultipleChoice"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMultipleChoice"),
("roformer", "FlaxRoFormerForMultipleChoice"),
("xlm-roberta", "FlaxXLMRobertaForMultipleChoice"),
]
)
__A = OrderedDict(
[
("bert", "FlaxBertForNextSentencePrediction"),
]
)
__A = OrderedDict(
[
("speech-encoder-decoder", "FlaxSpeechEncoderDecoderModel"),
("whisper", "FlaxWhisperForConditionalGeneration"),
]
)
__A = OrderedDict(
[
("whisper", "FlaxWhisperForAudioClassification"),
]
)
__A = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES)
__A = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES)
__A = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES)
__A = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
)
__A = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES
)
__A = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES)
__A = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES)
__A = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
)
__A = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
)
__A = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES
)
__A = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES
)
__A = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES
)
__A = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES
)
__A = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES
)
class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ):
'''simple docstring'''
lowercase_ = FLAX_MODEL_MAPPING
__A = auto_class_update(FlaxAutoModel)
class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ):
'''simple docstring'''
lowercase_ = FLAX_MODEL_FOR_PRETRAINING_MAPPING
__A = auto_class_update(FlaxAutoModelForPreTraining, head_doc="pretraining")
class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ):
'''simple docstring'''
lowercase_ = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING
__A = auto_class_update(FlaxAutoModelForCausalLM, head_doc="causal language modeling")
class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ):
'''simple docstring'''
lowercase_ = FLAX_MODEL_FOR_MASKED_LM_MAPPING
__A = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="masked language modeling")
class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ):
'''simple docstring'''
lowercase_ = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
__A = auto_class_update(
FlaxAutoModelForSeqaSeqLM, head_doc="sequence-to-sequence language modeling", checkpoint_for_example="t5-base"
)
class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ):
'''simple docstring'''
lowercase_ = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
__A = auto_class_update(
FlaxAutoModelForSequenceClassification, head_doc="sequence classification"
)
class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ):
'''simple docstring'''
lowercase_ = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING
__A = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="question answering")
class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ):
'''simple docstring'''
lowercase_ = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING
__A = auto_class_update(
FlaxAutoModelForTokenClassification, head_doc="token classification"
)
class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ):
'''simple docstring'''
lowercase_ = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING
__A = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="multiple choice")
class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ):
'''simple docstring'''
lowercase_ = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING
__A = auto_class_update(
FlaxAutoModelForNextSentencePrediction, head_doc="next sentence prediction"
)
class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ):
'''simple docstring'''
lowercase_ = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
__A = auto_class_update(
FlaxAutoModelForImageClassification, head_doc="image classification"
)
class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ):
'''simple docstring'''
lowercase_ = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING
__A = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="vision-to-text modeling")
class _SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ):
'''simple docstring'''
lowercase_ = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING
__A = auto_class_update(
FlaxAutoModelForSpeechSeqaSeq, head_doc="sequence-to-sequence speech-to-text modeling"
)
| 59 |
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
__A = logging.getLogger(__name__)
def lowerCAmelCase_ ( __a , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = False , ) -> str:
"""simple docstring"""
lowerCamelCase__: int =bnb_quantization_config.load_in_abit
lowerCamelCase__: Any =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." )
lowerCamelCase__: List[Any] =[]
# custom device map
if isinstance(__a , __a ) and len(device_map.keys() ) > 1:
lowerCamelCase__: Optional[int] =[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:
lowerCamelCase__: Any =get_keys_to_not_convert(__a )
# add cpu modules to skip modules only for 4-bit modules
if load_in_abit:
bnb_quantization_config.skip_modules.extend(__a )
lowerCamelCase__: List[str] =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:
lowerCamelCase__: List[Any] =[]
lowerCamelCase__: int =bnb_quantization_config.keep_in_fpaa_modules
modules_to_not_convert.extend(__a )
# compatibility with peft
lowerCamelCase__: List[str] =load_in_abit
lowerCamelCase__: int =load_in_abit
lowerCamelCase__: Tuple =get_parameter_device(__a )
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." )
lowerCamelCase__: Tuple =replace_with_bnb_layers(__a , __a , modules_to_not_convert=__a )
# convert param to the right dtype
lowerCamelCase__: Dict =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:
lowerCamelCase__: str =name.replace(".weight" , "" ).replace(".bias" , "" )
lowerCamelCase__: Optional[Any] =getattr(__a , __a , __a )
if param is not None:
param.to(torch.floataa )
elif torch.is_floating_point(__a ):
param.to(__a )
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():
lowerCamelCase__: str =replace_with_bnb_layers(
__a , __a , modules_to_not_convert=__a )
lowerCamelCase__: Optional[Any] =get_quantized_model_device_map(
__a , __a , __a , max_memory=__a , no_split_module_classes=__a , )
if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
lowerCamelCase__: Any =True
lowerCamelCase__: List[str] =any(x in list(device_map.values() ) for x in ["cpu", "disk"] )
load_checkpoint_in_model(
__a , __a , __a , dtype=bnb_quantization_config.torch_dtype , offload_folder=__a , offload_state_dict=__a , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , )
return dispatch_model(__a , device_map=__a , offload_dir=__a )
def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , __a=None ) -> str:
"""simple docstring"""
if device_map is None:
if torch.cuda.is_available():
lowerCamelCase__: str ={"": 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(__a , __a ):
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'." )
lowerCamelCase__: Optional[int] ={}
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 )
} )
lowerCamelCase__: Optional[Any] ={}
lowerCamelCase__: str =special_dtypes
lowerCamelCase__: List[str] =no_split_module_classes
lowerCamelCase__: Dict =bnb_quantization_config.target_dtype
# get max_memory for each device.
if device_map != "sequential":
lowerCamelCase__: Optional[Any] =get_balanced_memory(
__a , low_zero=(device_map == "balanced_low_0") , max_memory=__a , **__a , )
lowerCamelCase__: Union[str, Any] =max_memory
lowerCamelCase__: Dict =infer_auto_device_map(__a , **__a )
if isinstance(__a , __a ):
# check if don't have any quantized module on the cpu
lowerCamelCase__: Union[str, Any] =bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules
lowerCamelCase__: List[Any] ={
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(
"\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n " )
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 lowerCAmelCase_ ( __a , __a , __a=None , __a=None ) -> Optional[Any]:
"""simple docstring"""
if modules_to_not_convert is None:
lowerCamelCase__: List[Any] =[]
lowerCamelCase__ , lowerCamelCase__: Any =_replace_with_bnb_layers(
__a , __a , __a , __a )
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 lowerCAmelCase_ ( __a , __a , __a=None , __a=None , ) -> List[Any]:
"""simple docstring"""
lowerCamelCase__: Optional[int] =False
for name, module in model.named_children():
if current_key_name is None:
lowerCamelCase__: Optional[Any] =[]
current_key_name.append(__a )
if isinstance(__a , nn.Linear ) and name not in modules_to_not_convert:
# Check if the current key is not in the `modules_to_not_convert`
lowerCamelCase__: List[str] =".".join(__a )
lowerCamelCase__: Optional[Any] =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:
lowerCamelCase__: int =False
break
if proceed:
# Load bnb module with empty weight and replace ``nn.Linear` module
if bnb_quantization_config.load_in_abit:
lowerCamelCase__: Optional[int] =bnb.nn.LinearabitLt(
module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=__a , threshold=bnb_quantization_config.llm_inta_threshold , )
elif bnb_quantization_config.load_in_abit:
lowerCamelCase__: Dict =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" )
lowerCamelCase__: Dict =module.weight.data
if module.bias is not None:
lowerCamelCase__: List[Any] =module.bias.data
bnb_module.requires_grad_(__a )
setattr(__a , __a , __a )
lowerCamelCase__: int =True
if len(list(module.children() ) ) > 0:
lowerCamelCase__ , lowerCamelCase__: List[str] =_replace_with_bnb_layers(
__a , __a , __a , __a )
lowerCamelCase__: Union[str, Any] =has_been_replaced | _has_been_replaced
# Remove the last key for recursion
current_key_name.pop(-1 )
return model, has_been_replaced
def lowerCAmelCase_ ( __a ) -> List[Any]:
"""simple docstring"""
with init_empty_weights():
lowerCamelCase__: Any =deepcopy(__a ) # this has 0 cost since it is done inside `init_empty_weights` context manager`
lowerCamelCase__: str =find_tied_parameters(__a )
# For compatibility with Accelerate < 0.18
if isinstance(__a , __a ):
lowerCamelCase__: int =sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() )
else:
lowerCamelCase__: str =sum(__a , [] )
lowerCamelCase__: str =len(__a ) > 0
# Check if it is a base model
lowerCamelCase__: Optional[Any] =False
if hasattr(__a , "base_model_prefix" ):
lowerCamelCase__: Union[str, Any] =not hasattr(__a , 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
lowerCamelCase__: Optional[int] =list(model.named_children() )
lowerCamelCase__: Optional[int] =[list_modules[-1][0]]
# add last module together with tied weights
lowerCamelCase__: Union[str, Any] =set(__a ) - set(__a )
lowerCamelCase__: List[str] =list(set(__a ) ) + list(__a )
# remove ".weight" from the keys
lowerCamelCase__: List[Any] =[".weight", ".bias"]
lowerCamelCase__: Tuple =[]
for name in list_untouched:
for name_to_remove in names_to_remove:
if name_to_remove in name:
lowerCamelCase__: Optional[Any] =name.replace(__a , "" )
filtered_module_names.append(__a )
return filtered_module_names
def lowerCAmelCase_ ( __a ) -> Tuple:
"""simple docstring"""
for m in model.modules():
if isinstance(__a , bnb.nn.Linearabit ):
return True
return False
def lowerCAmelCase_ ( __a ) -> List[str]:
"""simple docstring"""
return next(parameter.parameters() ).device
def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a , __a ) -> Any:
"""simple docstring"""
if fpaa_statistics is None:
set_module_tensor_to_device(__a , __a , 0 , dtype=__a , value=__a )
lowerCamelCase__: Dict =param_name
lowerCamelCase__: Tuple =model
if "." in tensor_name:
lowerCamelCase__: Any =tensor_name.split("." )
for split in splits[:-1]:
lowerCamelCase__: Any =getattr(__a , __a )
if new_module is None:
raise ValueError(F"""{module} has no attribute {split}.""" )
lowerCamelCase__: str =new_module
lowerCamelCase__: int =splits[-1]
# offload weights
lowerCamelCase__: str =False
offload_weight(module._parameters[tensor_name] , __a , __a , index=__a )
if hasattr(module._parameters[tensor_name] , "SCB" ):
offload_weight(
module._parameters[tensor_name].SCB , param_name.replace("weight" , "SCB" ) , __a , index=__a , )
else:
offload_weight(__a , __a , __a , index=__a )
offload_weight(__a , param_name.replace("weight" , "SCB" ) , __a , index=__a )
set_module_tensor_to_device(__a , __a , "meta" , dtype=__a , value=torch.empty(*param.size() ) )
| 59 | 1 |
from __future__ import annotations
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__(self : Any , UpperCAmelCase_ : int) ->None:
'''simple docstring'''
lowerCamelCase__: List[str] =order
# a_{0} ... a_{k}
lowerCamelCase__: Tuple =[1.0] + [0.0] * order
# b_{0} ... b_{k}
lowerCamelCase__: Any =[1.0] + [0.0] * order
# x[n-1] ... x[n-k]
lowerCamelCase__: int =[0.0] * self.order
# y[n-1] ... y[n-k]
lowerCamelCase__: List[Any] =[0.0] * self.order
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : list[float] , UpperCAmelCase_ : list[float]) ->None:
'''simple docstring'''
if len(UpperCAmelCase_) < self.order:
lowerCamelCase__: Tuple =[1.0, *a_coeffs]
if len(UpperCAmelCase_) != self.order + 1:
lowerCamelCase__: List[str] =(
F"""Expected a_coeffs to have {self.order + 1} elements """
F"""for {self.order}-order filter, got {len(UpperCAmelCase_)}"""
)
raise ValueError(UpperCAmelCase_)
if len(UpperCAmelCase_) != self.order + 1:
lowerCamelCase__: List[Any] =(
F"""Expected b_coeffs to have {self.order + 1} elements """
F"""for {self.order}-order filter, got {len(UpperCAmelCase_)}"""
)
raise ValueError(UpperCAmelCase_)
lowerCamelCase__: Tuple =a_coeffs
lowerCamelCase__: List[Any] =b_coeffs
def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : float) ->float:
'''simple docstring'''
lowerCamelCase__: List[Any] =0.0
# Start at index 1 and do index 0 at the end.
for i in range(1 , self.order + 1):
result += (
self.b_coeffs[i] * self.input_history[i - 1]
- self.a_coeffs[i] * self.output_history[i - 1]
)
lowerCamelCase__: Union[str, Any] =(result + self.b_coeffs[0] * sample) / self.a_coeffs[0]
lowerCamelCase__: str =self.input_history[:-1]
lowerCamelCase__: Any =self.output_history[:-1]
lowerCamelCase__: int =sample
lowerCamelCase__: Tuple =result
return result
| 59 |
from __future__ import annotations
from math import pi
def lowerCAmelCase_ ( __a , __a , __a ) -> dict[str, float]:
"""simple docstring"""
if (inductance, frequency, reactance).count(0 ) != 1:
raise ValueError("One and only one argument must be 0" )
if inductance < 0:
raise ValueError("Inductance cannot be negative" )
if frequency < 0:
raise ValueError("Frequency cannot be negative" )
if reactance < 0:
raise ValueError("Inductive reactance cannot be negative" )
if inductance == 0:
return {"inductance": reactance / (2 * pi * frequency)}
elif frequency == 0:
return {"frequency": reactance / (2 * pi * inductance)}
elif reactance == 0:
return {"reactance": 2 * pi * frequency * inductance}
else:
raise ValueError("Exactly one argument must be 0" )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 59 | 1 |
from collections.abc import Sequence
def lowerCAmelCase_ ( __a , __a = False ) -> float:
"""simple docstring"""
if not arr:
return 0
lowerCamelCase__: Tuple =0 if allow_empty_subarrays else float("-inf" )
lowerCamelCase__: Optional[int] =0.0
for num in arr:
lowerCamelCase__: Union[str, Any] =max(0 if allow_empty_subarrays else num , curr_sum + num )
lowerCamelCase__: List[str] =max(__a , __a )
return max_sum
if __name__ == "__main__":
from doctest import testmod
testmod()
__A = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(f'{max_subarray_sum(nums) = }')
| 59 |
import pyarrow.parquet as pq
import pytest
from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config
from datasets.features.image import Image
from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size
from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases
def lowerCAmelCase_ ( __a , __a ) -> List[Any]:
"""simple docstring"""
assert isinstance(__a , __a )
assert dataset.num_rows == 4
assert dataset.num_columns == 3
assert dataset.column_names == ["col_1", "col_2", "col_3"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("keep_in_memory" , [False, True] )
def lowerCAmelCase_ ( __a , __a , __a ) -> Any:
"""simple docstring"""
lowerCamelCase__: Any =tmp_path / "cache"
lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
lowerCamelCase__: Tuple =ParquetDatasetReader(__a , cache_dir=__a , keep_in_memory=__a ).read()
_check_parquet_dataset(__a , __a )
@pytest.mark.parametrize(
"features" , [
None,
{"col_1": "string", "col_2": "int64", "col_3": "float64"},
{"col_1": "string", "col_2": "string", "col_3": "string"},
{"col_1": "int32", "col_2": "int32", "col_3": "int32"},
{"col_1": "float32", "col_2": "float32", "col_3": "float32"},
] , )
def lowerCAmelCase_ ( __a , __a , __a ) -> List[str]:
"""simple docstring"""
lowerCamelCase__: int =tmp_path / "cache"
lowerCamelCase__: Tuple ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
lowerCamelCase__: Union[str, Any] =features.copy() if features else default_expected_features
lowerCamelCase__: Optional[int] =(
Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None
)
lowerCamelCase__: int =ParquetDatasetReader(__a , features=__a , cache_dir=__a ).read()
_check_parquet_dataset(__a , __a )
@pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] )
def lowerCAmelCase_ ( __a , __a , __a ) -> Any:
"""simple docstring"""
lowerCamelCase__: Any =tmp_path / "cache"
lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
lowerCamelCase__: Optional[Any] =ParquetDatasetReader(__a , cache_dir=__a , split=__a ).read()
_check_parquet_dataset(__a , __a )
assert dataset.split == split if split else "train"
@pytest.mark.parametrize("path_type" , [str, list] )
def lowerCAmelCase_ ( __a , __a , __a ) -> int:
"""simple docstring"""
if issubclass(__a , __a ):
lowerCamelCase__: List[Any] =parquet_path
elif issubclass(__a , __a ):
lowerCamelCase__: str =[parquet_path]
lowerCamelCase__: Tuple =tmp_path / "cache"
lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read()
_check_parquet_dataset(__a , __a )
def lowerCAmelCase_ ( __a , __a , __a=("train",) ) -> Dict:
"""simple docstring"""
assert isinstance(__a , __a )
for split in splits:
lowerCamelCase__: Tuple =dataset_dict[split]
assert dataset.num_rows == 4
assert dataset.num_columns == 3
assert dataset.column_names == ["col_1", "col_2", "col_3"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("keep_in_memory" , [False, True] )
def lowerCAmelCase_ ( __a , __a , __a ) -> Any:
"""simple docstring"""
lowerCamelCase__: List[Any] =tmp_path / "cache"
lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
lowerCamelCase__: Tuple =ParquetDatasetReader(
{"train": parquet_path} , cache_dir=__a , keep_in_memory=__a ).read()
_check_parquet_datasetdict(__a , __a )
@pytest.mark.parametrize(
"features" , [
None,
{"col_1": "string", "col_2": "int64", "col_3": "float64"},
{"col_1": "string", "col_2": "string", "col_3": "string"},
{"col_1": "int32", "col_2": "int32", "col_3": "int32"},
{"col_1": "float32", "col_2": "float32", "col_3": "float32"},
] , )
def lowerCAmelCase_ ( __a , __a , __a ) -> Optional[Any]:
"""simple docstring"""
lowerCamelCase__: Tuple =tmp_path / "cache"
lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
lowerCamelCase__: List[Any] =features.copy() if features else default_expected_features
lowerCamelCase__: int =(
Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None
)
lowerCamelCase__: Optional[Any] =ParquetDatasetReader({"train": parquet_path} , features=__a , cache_dir=__a ).read()
_check_parquet_datasetdict(__a , __a )
@pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] )
def lowerCAmelCase_ ( __a , __a , __a ) -> Union[str, Any]:
"""simple docstring"""
if split:
lowerCamelCase__: Any ={split: parquet_path}
else:
lowerCamelCase__: int ="train"
lowerCamelCase__: Any ={"train": parquet_path, "test": parquet_path}
lowerCamelCase__: str =tmp_path / "cache"
lowerCamelCase__: Any ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read()
_check_parquet_datasetdict(__a , __a , splits=list(path.keys() ) )
assert all(dataset[split].split == split for split in path.keys() )
def lowerCAmelCase_ ( __a , __a ) -> int:
"""simple docstring"""
lowerCamelCase__: List[str] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" )
assert writer.write() > 0
lowerCamelCase__: List[str] =pq.ParquetFile(tmp_path / "foo.parquet" )
lowerCamelCase__: List[str] =pf.read()
assert dataset.data.table == output_table
def lowerCAmelCase_ ( __a , __a ) -> List[str]:
"""simple docstring"""
lowerCamelCase__: List[str] =str(shared_datadir / "test_image_rgb.jpg" )
lowerCamelCase__: Union[str, Any] ={"image": [image_path]}
lowerCamelCase__: Optional[Any] =Features({"image": Image()} )
lowerCamelCase__: Optional[int] =Dataset.from_dict(__a , features=__a )
lowerCamelCase__: Optional[int] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" )
assert writer.write() > 0
lowerCamelCase__: Dict =Dataset.from_parquet(str(tmp_path / "foo.parquet" ) )
assert dataset.features == reloaded_dataset.features
lowerCamelCase__: Optional[Any] =ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=__a ).read()
assert dataset.features == reloaded_iterable_dataset.features
@pytest.mark.parametrize(
"feature, expected" , [
(Features({"foo": Value("int32" )} ), None),
(Features({"image": Image(), "foo": Value("int32" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS),
(Features({"nested": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS),
] , )
def lowerCAmelCase_ ( __a , __a ) -> Optional[Any]:
"""simple docstring"""
assert get_writer_batch_size(__a ) == expected
| 59 | 1 |
import numpy as np
from nltk.translate import meteor_score
import datasets
from datasets.config import importlib_metadata, version
__A = version.parse(importlib_metadata.version("nltk"))
if NLTK_VERSION >= version.Version("3.6.4"):
from nltk import word_tokenize
__A = "\\n@inproceedings{banarjee2005,\n title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n author = {Banerjee, Satanjeev and Lavie, Alon},\n booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n month = jun,\n year = {2005},\n address = {Ann Arbor, Michigan},\n publisher = {Association for Computational Linguistics},\n url = {https://www.aclweb.org/anthology/W05-0909},\n pages = {65--72},\n}\n"
__A = "\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n"
__A = "\nComputes METEOR score of translated segments against one or more references.\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n 'meteor': meteor score.\nExamples:\n\n >>> meteor = datasets.load_metric('meteor')\n >>> predictions = [\"It is a guide to action which ensures that the military always obeys the commands of the party\"]\n >>> references = [\"It is a guide to action that ensures that the military will forever heed Party commands\"]\n >>> results = meteor.compute(predictions=predictions, references=references)\n >>> print(round(results[\"meteor\"], 4))\n 0.6944\n"
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class _SCREAMING_SNAKE_CASE ( datasets.Metric ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->List[Any]:
'''simple docstring'''
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"predictions": datasets.Value("string" , id="sequence"),
"references": datasets.Value("string" , id="sequence"),
}) , codebase_urls=["https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py"] , reference_urls=[
"https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score",
"https://en.wikipedia.org/wiki/METEOR",
] , )
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : str) ->List[Any]:
'''simple docstring'''
import nltk
nltk.download("wordnet")
if NLTK_VERSION >= version.Version("3.6.5"):
nltk.download("punkt")
if NLTK_VERSION >= version.Version("3.6.6"):
nltk.download("omw-1.4")
def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Dict=0.9 , UpperCAmelCase_ : Any=3 , UpperCAmelCase_ : Any=0.5) ->Optional[Any]:
'''simple docstring'''
if NLTK_VERSION >= version.Version("3.6.5"):
lowerCamelCase__: Any =[
meteor_score.single_meteor_score(
word_tokenize(UpperCAmelCase_) , word_tokenize(UpperCAmelCase_) , alpha=UpperCAmelCase_ , beta=UpperCAmelCase_ , gamma=UpperCAmelCase_)
for ref, pred in zip(UpperCAmelCase_ , UpperCAmelCase_)
]
else:
lowerCamelCase__: str =[
meteor_score.single_meteor_score(UpperCAmelCase_ , UpperCAmelCase_ , alpha=UpperCAmelCase_ , beta=UpperCAmelCase_ , gamma=UpperCAmelCase_)
for ref, pred in zip(UpperCAmelCase_ , UpperCAmelCase_)
]
return {"meteor": np.mean(UpperCAmelCase_)}
| 59 |
import unittest
from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin
__A = get_tests_dir("fixtures/test_sentencepiece.model")
@require_sentencepiece
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ):
'''simple docstring'''
lowercase_ = XLMProphetNetTokenizer
lowercase_ = False
lowercase_ = True
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[Any]:
'''simple docstring'''
super().setUp()
# We have a SentencePiece fixture for testing
lowerCamelCase__: Any =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_)
tokenizer.save_pretrained(self.tmpdirname)
def SCREAMING_SNAKE_CASE_ (self : str) ->str:
'''simple docstring'''
lowerCamelCase__: List[Any] ="[PAD]"
lowerCamelCase__: Tuple =0
self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_) , UpperCAmelCase_)
self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_) , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Dict) ->int:
'''simple docstring'''
lowerCamelCase__: List[Any] =list(self.get_tokenizer().get_vocab().keys())
self.assertEqual(vocab_keys[0] , "[PAD]")
self.assertEqual(vocab_keys[1] , "[CLS]")
self.assertEqual(vocab_keys[-1] , "j")
self.assertEqual(len(UpperCAmelCase_) , 1_012)
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]:
'''simple docstring'''
self.assertEqual(self.get_tokenizer().vocab_size , 1_012)
def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_)
lowerCamelCase__: Tuple =tokenizer.tokenize("This is a test")
self.assertListEqual(UpperCAmelCase_ , ["▁This", "▁is", "▁a", "▁t", "est"])
self.assertListEqual(
tokenizer.convert_tokens_to_ids(UpperCAmelCase_) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , )
lowerCamelCase__: Optional[Any] =tokenizer.tokenize("I was born in 92000, and this is falsé.")
self.assertListEqual(
UpperCAmelCase_ , [
SPIECE_UNDERLINE + "I",
SPIECE_UNDERLINE + "was",
SPIECE_UNDERLINE + "b",
"or",
"n",
SPIECE_UNDERLINE + "in",
SPIECE_UNDERLINE + "",
"9",
"2",
"0",
"0",
"0",
",",
SPIECE_UNDERLINE + "and",
SPIECE_UNDERLINE + "this",
SPIECE_UNDERLINE + "is",
SPIECE_UNDERLINE + "f",
"al",
"s",
"é",
".",
] , )
lowerCamelCase__: Any =tokenizer.convert_tokens_to_ids(UpperCAmelCase_)
self.assertListEqual(
UpperCAmelCase_ , [
value + tokenizer.fairseq_offset
for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4]
] , )
lowerCamelCase__: Any =tokenizer.convert_ids_to_tokens(UpperCAmelCase_)
self.assertListEqual(
UpperCAmelCase_ , [
SPIECE_UNDERLINE + "I",
SPIECE_UNDERLINE + "was",
SPIECE_UNDERLINE + "b",
"or",
"n",
SPIECE_UNDERLINE + "in",
SPIECE_UNDERLINE + "",
"[UNK]",
"2",
"0",
"0",
"0",
",",
SPIECE_UNDERLINE + "and",
SPIECE_UNDERLINE + "this",
SPIECE_UNDERLINE + "is",
SPIECE_UNDERLINE + "f",
"al",
"s",
"[UNK]",
".",
] , )
@cached_property
def SCREAMING_SNAKE_CASE_ (self : Any) ->int:
'''simple docstring'''
return XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased")
@slow
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[str]:
'''simple docstring'''
lowerCamelCase__: Optional[int] ="Hello World!"
lowerCamelCase__: Dict =[35_389, 6_672, 49, 2]
self.assertListEqual(UpperCAmelCase_ , self.big_tokenizer.encode(UpperCAmelCase_))
@slow
def SCREAMING_SNAKE_CASE_ (self : int) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__: Any ={"input_ids": [[11_073, 82_783, 18, 26, 82_783, 549, 51_540, 248, 17_209, 1_301, 217, 20, 215_186, 1_325, 147, 17_209, 1_301, 217, 20, 56_370, 53, 122_020, 20, 16_477, 27, 87_355, 4_548, 20, 4_728, 78_392, 17, 159_969, 18, 26, 24_491, 629, 15, 538, 22_704, 5_439, 15, 2_788, 24_491, 9_885, 15, 43_534, 605, 15, 814, 18_403, 33_200, 29, 15, 43_534, 24_458, 12_410, 111, 24_966, 83_669, 9_637, 144_068, 26, 850, 22_346, 27, 147, 24_966, 83_669, 83_490, 26, 39_113, 735, 27, 689, 656, 2_800, 1_339, 4_600, 53, 122_020, 115_785, 34, 816, 1_339, 46_887, 18, 147, 53_905, 1_951, 42_238, 41_170, 17_732, 834, 436, 15, 27_523, 98_733, 217, 147, 5_542, 4_981, 930, 17_347, 16, 2], [20_091, 629, 94, 82_786, 58, 490, 20, 1_528, 84, 53_905, 344, 80_592, 110_128, 18_822, 5_267, 1_306, 62, 152_537, 308, 7_997, 401, 124_427, 549, 35_442, 225, 109, 15_055, 25_748, 147, 7_119, 43_712, 34, 767, 135_366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63_784, 119_466, 17, 147_808, 88_214, 18, 656, 81, 32, 3_296, 10_280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=UpperCAmelCase_ , model_name="microsoft/xprophetnet-large-wiki100-cased" , revision="1acad1643ddd54a44df6a1b797ada8373685d90e" , )
| 59 | 1 |
import argparse
import json
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel
from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
torch.set_grad_enabled(False)
def lowerCAmelCase_ ( __a , __a=False ) -> Union[str, Any]:
"""simple docstring"""
lowerCamelCase__: Dict =[]
for i in range(config.num_hidden_layers ):
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
rename_keys.append((F"""module.blocks.{i}.norm1.weight""", F"""vit.encoder.layer.{i}.layernorm_before.weight""") )
rename_keys.append((F"""module.blocks.{i}.norm1.bias""", F"""vit.encoder.layer.{i}.layernorm_before.bias""") )
rename_keys.append(
(F"""module.blocks.{i}.attn.proj.weight""", F"""vit.encoder.layer.{i}.attention.output.dense.weight""") )
rename_keys.append((F"""module.blocks.{i}.attn.proj.bias""", F"""vit.encoder.layer.{i}.attention.output.dense.bias""") )
rename_keys.append((F"""module.blocks.{i}.norm2.weight""", F"""vit.encoder.layer.{i}.layernorm_after.weight""") )
rename_keys.append((F"""module.blocks.{i}.norm2.bias""", F"""vit.encoder.layer.{i}.layernorm_after.bias""") )
rename_keys.append((F"""module.blocks.{i}.mlp.fc1.weight""", F"""vit.encoder.layer.{i}.intermediate.dense.weight""") )
rename_keys.append((F"""module.blocks.{i}.mlp.fc1.bias""", F"""vit.encoder.layer.{i}.intermediate.dense.bias""") )
rename_keys.append((F"""module.blocks.{i}.mlp.fc2.weight""", F"""vit.encoder.layer.{i}.output.dense.weight""") )
rename_keys.append((F"""module.blocks.{i}.mlp.fc2.bias""", F"""vit.encoder.layer.{i}.output.dense.bias""") )
# projection layer + position embeddings
rename_keys.extend(
[
("module.cls_token", "vit.embeddings.cls_token"),
("module.patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight"),
("module.patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias"),
("module.pos_embed", "vit.embeddings.position_embeddings"),
] )
if base_model:
# layernorm + pooler
rename_keys.extend(
[
("module.norm.weight", "layernorm.weight"),
("module.norm.bias", "layernorm.bias"),
] )
# if just the base model, we should remove "vit" from all keys that start with "vit"
lowerCamelCase__: int =[(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 lowerCAmelCase_ ( __a , __a , __a=False ) -> Any:
"""simple docstring"""
for i in range(config.num_hidden_layers ):
if base_model:
lowerCamelCase__: List[Any] =""
else:
lowerCamelCase__: Dict ="vit."
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
lowerCamelCase__: Tuple =state_dict.pop(F"""module.blocks.{i}.attn.qkv.weight""" )
lowerCamelCase__: int =state_dict.pop(F"""module.blocks.{i}.attn.qkv.bias""" )
# next, add query, keys and values (in that order) to the state dict
lowerCamelCase__: int =in_proj_weight[
: config.hidden_size, :
]
lowerCamelCase__: Optional[int] =in_proj_bias[: config.hidden_size]
lowerCamelCase__: Union[str, Any] =in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
lowerCamelCase__: str =in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
lowerCamelCase__: Dict =in_proj_weight[
-config.hidden_size :, :
]
lowerCamelCase__: str =in_proj_bias[-config.hidden_size :]
def lowerCAmelCase_ ( __a ) -> Optional[Any]:
"""simple docstring"""
lowerCamelCase__: Tuple =["head.weight", "head.bias"]
for k in ignore_keys:
state_dict.pop(__a , __a )
def lowerCAmelCase_ ( __a ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase__: Any =[
"module.fc.fc1.weight",
"module.fc.fc1.bias",
"module.fc.bn1.weight",
"module.fc.bn1.bias",
"module.fc.bn1.running_mean",
"module.fc.bn1.running_var",
"module.fc.bn1.num_batches_tracked",
"module.fc.fc2.weight",
"module.fc.fc2.bias",
"module.fc.bn2.weight",
"module.fc.bn2.bias",
"module.fc.bn2.running_mean",
"module.fc.bn2.running_var",
"module.fc.bn2.num_batches_tracked",
"module.fc.fc3.weight",
"module.fc.fc3.bias",
]
for k in ignore_keys:
state_dict.pop(__a , __a )
def lowerCAmelCase_ ( __a , __a , __a ) -> Union[str, Any]:
"""simple docstring"""
lowerCamelCase__: int =dct.pop(__a )
lowerCamelCase__: Tuple =val
def lowerCAmelCase_ ( __a , __a ) -> str:
"""simple docstring"""
lowerCamelCase__: List[str] =ViTMSNConfig()
lowerCamelCase__: Optional[Any] =1000
lowerCamelCase__: Dict ="datasets/huggingface/label-files"
lowerCamelCase__: List[str] ="imagenet-1k-id2label.json"
lowerCamelCase__: List[str] =json.load(open(hf_hub_download(__a , __a ) , "r" ) )
lowerCamelCase__: int ={int(__a ): v for k, v in idalabel.items()}
lowerCamelCase__: List[str] =idalabel
lowerCamelCase__: Union[str, Any] ={v: k for k, v in idalabel.items()}
if "s16" in checkpoint_url:
lowerCamelCase__: Dict =384
lowerCamelCase__: Union[str, Any] =1536
lowerCamelCase__: Dict =6
elif "l16" in checkpoint_url:
lowerCamelCase__: str =1024
lowerCamelCase__: List[Any] =4096
lowerCamelCase__: List[str] =24
lowerCamelCase__: List[Any] =16
lowerCamelCase__: Any =0.1
elif "b4" in checkpoint_url:
lowerCamelCase__: List[str] =4
elif "l7" in checkpoint_url:
lowerCamelCase__: Optional[Any] =7
lowerCamelCase__: int =1024
lowerCamelCase__: int =4096
lowerCamelCase__: Tuple =24
lowerCamelCase__: List[Any] =16
lowerCamelCase__: Tuple =0.1
lowerCamelCase__: Union[str, Any] =ViTMSNModel(__a )
lowerCamelCase__: Tuple =torch.hub.load_state_dict_from_url(__a , map_location="cpu" )["target_encoder"]
lowerCamelCase__: Union[str, Any] =ViTImageProcessor(size=config.image_size )
remove_projection_head(__a )
lowerCamelCase__: Optional[Any] =create_rename_keys(__a , base_model=__a )
for src, dest in rename_keys:
rename_key(__a , __a , __a )
read_in_q_k_v(__a , __a , base_model=__a )
model.load_state_dict(__a )
model.eval()
lowerCamelCase__: Dict ="http://images.cocodataset.org/val2017/000000039769.jpg"
lowerCamelCase__: Any =Image.open(requests.get(__a , stream=__a ).raw )
lowerCamelCase__: Union[str, Any] =ViTImageProcessor(
size=config.image_size , image_mean=__a , image_std=__a )
lowerCamelCase__: List[str] =image_processor(images=__a , return_tensors="pt" )
# forward pass
torch.manual_seed(2 )
lowerCamelCase__: Union[str, Any] =model(**__a )
lowerCamelCase__: List[str] =outputs.last_hidden_state
# The following Colab Notebook was used to generate these outputs:
# https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb
if "s16" in checkpoint_url:
lowerCamelCase__: str =torch.tensor([[-1.0_9_1_5, -1.4_8_7_6, -1.1_8_0_9]] )
elif "b16" in checkpoint_url:
lowerCamelCase__: Tuple =torch.tensor([[1_4.2_8_8_9, -1_8.9_0_4_5, 1_1.7_2_8_1]] )
elif "l16" in checkpoint_url:
lowerCamelCase__: List[Any] =torch.tensor([[4_1.5_0_2_8, -2_2.8_6_8_1, 4_5.6_4_7_5]] )
elif "b4" in checkpoint_url:
lowerCamelCase__: Union[str, Any] =torch.tensor([[-4.3_8_6_8, 5.2_9_3_2, -0.4_1_3_7]] )
else:
lowerCamelCase__: Dict =torch.tensor([[-0.1_7_9_2, -0.6_4_6_5, 2.4_2_6_3]] )
# verify logits
assert torch.allclose(last_hidden_state[:, 0, :3] , __a , atol=1e-4 )
print(F"""Saving model to {pytorch_dump_folder_path}""" )
model.save_pretrained(__a )
print(F"""Saving image processor to {pytorch_dump_folder_path}""" )
image_processor.save_pretrained(__a )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--checkpoint_url",
default="https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar",
type=str,
help="URL of the checkpoint you'd like to convert.",
)
parser.add_argument(
"--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
)
__A = parser.parse_args()
convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
| 59 |
import os
import shutil
import tempfile
import unittest
import numpy as np
from transformers import AutoTokenizer, BarkProcessor
from transformers.testing_utils import require_torch, slow
@require_torch
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->str:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] ="ylacombe/bark-small"
lowerCamelCase__: Tuple =tempfile.mkdtemp()
lowerCamelCase__: Tuple ="en_speaker_1"
lowerCamelCase__: Optional[int] ="This is a test string"
lowerCamelCase__: List[str] ="speaker_embeddings_path.json"
lowerCamelCase__: int ="speaker_embeddings"
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , **UpperCAmelCase_ : Any) ->Tuple:
'''simple docstring'''
return AutoTokenizer.from_pretrained(self.checkpoint , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Union[str, Any]:
'''simple docstring'''
shutil.rmtree(self.tmpdirname)
def SCREAMING_SNAKE_CASE_ (self : int) ->Any:
'''simple docstring'''
lowerCamelCase__: List[Any] =self.get_tokenizer()
lowerCamelCase__: List[str] =BarkProcessor(tokenizer=UpperCAmelCase_)
processor.save_pretrained(self.tmpdirname)
lowerCamelCase__: Dict =BarkProcessor.from_pretrained(self.tmpdirname)
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab())
@slow
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Tuple =BarkProcessor.from_pretrained(
pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , )
processor.save_pretrained(
self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , )
lowerCamelCase__: Dict =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)")
lowerCamelCase__: Any =BarkProcessor.from_pretrained(
self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="(BOS)" , eos_token="(EOS)" , )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab())
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->int:
'''simple docstring'''
lowerCamelCase__: Any =BarkProcessor.from_pretrained(
pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , )
lowerCamelCase__: List[str] =35
lowerCamelCase__: Optional[Any] =2
lowerCamelCase__: Optional[Any] =8
lowerCamelCase__: Optional[int] ={
"semantic_prompt": np.ones(UpperCAmelCase_),
"coarse_prompt": np.ones((nb_codebooks_coarse, seq_len)),
"fine_prompt": np.ones((nb_codebooks_total, seq_len)),
}
# test providing already loaded voice_preset
lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=UpperCAmelCase_)
lowerCamelCase__: int =inputs["history_prompt"]
for key in voice_preset:
self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist())
# test loading voice preset from npz file
lowerCamelCase__: Union[str, Any] =os.path.join(self.tmpdirname , "file.npz")
np.savez(UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: Tuple =processor(text=self.input_string , voice_preset=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =inputs["history_prompt"]
for key in voice_preset:
self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist())
# test loading voice preset from the hub
lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=self.voice_preset)
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__: str =self.get_tokenizer()
lowerCamelCase__: Dict =BarkProcessor(tokenizer=UpperCAmelCase_)
lowerCamelCase__: List[Any] =processor(text=self.input_string)
lowerCamelCase__: Optional[int] =tokenizer(
self.input_string , padding="max_length" , max_length=256 , add_special_tokens=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist())
| 59 | 1 |
from __future__ import annotations
import math
from collections import Counter
from string import ascii_lowercase
def lowerCAmelCase_ ( __a ) -> None:
"""simple docstring"""
lowerCamelCase__ , lowerCamelCase__: Any =analyze_text(__a )
lowerCamelCase__: List[Any] =list(" " + ascii_lowercase )
# what is our total sum of probabilities.
lowerCamelCase__: str =sum(single_char_strings.values() )
# one length string
lowerCamelCase__: Any =0
# for each alpha we go in our dict and if it is in it we calculate entropy
for ch in my_alphas:
if ch in single_char_strings:
lowerCamelCase__: Tuple =single_char_strings[ch]
lowerCamelCase__: Any =my_str / all_sum
my_fir_sum += prob * math.loga(__a ) # entropy formula.
# print entropy
print(F"""{round(-1 * my_fir_sum ):.1f}""" )
# two len string
lowerCamelCase__: Any =sum(two_char_strings.values() )
lowerCamelCase__: str =0
# for each alpha (two in size) calculate entropy.
for cha in my_alphas:
for cha in my_alphas:
lowerCamelCase__: Union[str, Any] =cha + cha
if sequence in two_char_strings:
lowerCamelCase__: Dict =two_char_strings[sequence]
lowerCamelCase__: List[str] =int(__a ) / all_sum
my_sec_sum += prob * math.loga(__a )
# print second entropy
print(F"""{round(-1 * my_sec_sum ):.1f}""" )
# print the difference between them
print(F"""{round((-1 * my_sec_sum) - (-1 * my_fir_sum) ):.1f}""" )
def lowerCAmelCase_ ( __a ) -> tuple[dict, dict]:
"""simple docstring"""
lowerCamelCase__: str =Counter() # type: ignore
lowerCamelCase__: Union[str, Any] =Counter() # type: ignore
single_char_strings[text[-1]] += 1
# first case when we have space at start.
two_char_strings[" " + text[0]] += 1
for i in range(0 , len(__a ) - 1 ):
single_char_strings[text[i]] += 1
two_char_strings[text[i : i + 2]] += 1
return single_char_strings, two_char_strings
def lowerCAmelCase_ ( ) -> Union[str, Any]:
"""simple docstring"""
import doctest
doctest.testmod()
# text = (
# "Had repulsive dashwoods suspicion sincerity but advantage now him. Remark "
# "easily garret nor nay. Civil those mrs enjoy shy fat merry. You greatest "
# "jointure saw horrible. He private he on be imagine suppose. Fertile "
# "beloved evident through no service elderly is. Blind there if every no so "
# "at. Own neglected you preferred way sincerity delivered his attempted. To "
# "of message cottage windows do besides against uncivil. Delightful "
# "unreserved impossible few estimating men favourable see entreaties. She "
# "propriety immediate was improving. He or entrance humoured likewise "
# "moderate. Much nor game son say feel. Fat make met can must form into "
# "gate. Me we offending prevailed discovery. "
# )
# calculate_prob(text)
if __name__ == "__main__":
main()
| 59 |
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = ["image_processor", "tokenizer"]
lowercase_ = "CLIPImageProcessor"
lowercase_ = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast")
def __init__(self : List[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : List[str]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =None
if "feature_extractor" in kwargs:
warnings.warn(
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
" instead." , UpperCAmelCase_ , )
lowerCamelCase__: int =kwargs.pop("feature_extractor")
lowerCamelCase__: int =image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError("You need to specify an `image_processor`.")
if tokenizer is None:
raise ValueError("You need to specify a `tokenizer`.")
super().__init__(UpperCAmelCase_ , UpperCAmelCase_)
def __call__(self : List[Any] , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : int=None , **UpperCAmelCase_ : Any) ->Union[str, Any]:
'''simple docstring'''
if text is None and images is None:
raise ValueError("You have to specify either text or images. Both cannot be none.")
if text is not None:
lowerCamelCase__: List[Any] =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if images is not None:
lowerCamelCase__: int =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if text is not None and images is not None:
lowerCamelCase__: str =image_features.pixel_values
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[Any]) ->Dict:
'''simple docstring'''
return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Any) ->Optional[Any]:
'''simple docstring'''
return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_)
@property
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =self.tokenizer.model_input_names
lowerCamelCase__: str =self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
| 59 | 1 |
import re
from pathlib import Path
from unittest import TestCase
import pytest
@pytest.mark.integration
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : str) ->Tuple:
'''simple docstring'''
with open(UpperCAmelCase_ , encoding="utf-8") as input_file:
lowerCamelCase__: int =re.compile(R"(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)")
lowerCamelCase__: List[str] =input_file.read()
lowerCamelCase__: int =regexp.search(UpperCAmelCase_)
return match
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : str) ->Tuple:
'''simple docstring'''
with open(UpperCAmelCase_ , encoding="utf-8") as input_file:
lowerCamelCase__: Optional[Any] =re.compile(R"#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()" , re.DOTALL)
lowerCamelCase__: List[str] =input_file.read()
# use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search`
lowerCamelCase__: Dict =regexp.finditer(UpperCAmelCase_)
lowerCamelCase__: Dict =[match for match in matches if match is not None and match.group(1) is not None]
return matches[0] if matches else None
def SCREAMING_SNAKE_CASE_ (self : str) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =Path("./datasets")
lowerCamelCase__: int =list(dataset_paths.absolute().glob("**/*.py"))
for dataset in dataset_files:
if self._no_encoding_on_file_open(str(UpperCAmelCase_)):
raise AssertionError(F"""open(...) must use utf-8 encoding in {dataset}""")
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->str:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =Path("./datasets")
lowerCamelCase__: int =list(dataset_paths.absolute().glob("**/*.py"))
for dataset in dataset_files:
if self._no_print_statements(str(UpperCAmelCase_)):
raise AssertionError(F"""print statement found in {dataset}. Use datasets.logger/logging instead.""")
| 59 |
from datetime import datetime
import matplotlib.pyplot as plt
import torch
def lowerCAmelCase_ ( __a ) -> Any:
"""simple docstring"""
for param in module.parameters():
lowerCamelCase__: Tuple =False
def lowerCAmelCase_ ( ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase__: List[str] ="cuda" if torch.cuda.is_available() else "cpu"
if torch.backends.mps.is_available() and torch.backends.mps.is_built():
lowerCamelCase__: str ="mps"
if device == "mps":
print(
"WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch"
" errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues"
" with generations." )
return device
def lowerCAmelCase_ ( __a ) -> List[str]:
"""simple docstring"""
lowerCamelCase__: Union[str, Any] =plt.imshow(__a )
fig.axes.get_xaxis().set_visible(__a )
fig.axes.get_yaxis().set_visible(__a )
plt.show()
def lowerCAmelCase_ ( ) -> Optional[Any]:
"""simple docstring"""
lowerCamelCase__: List[str] =datetime.now()
lowerCamelCase__: str =current_time.strftime("%H:%M:%S" )
return timestamp
| 59 | 1 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
__A = {
"configuration_funnel": ["FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP", "FunnelConfig"],
"convert_funnel_original_tf_checkpoint_to_pytorch": [],
"tokenization_funnel": ["FunnelTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = ["FunnelTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
"FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST",
"FunnelBaseModel",
"FunnelForMaskedLM",
"FunnelForMultipleChoice",
"FunnelForPreTraining",
"FunnelForQuestionAnswering",
"FunnelForSequenceClassification",
"FunnelForTokenClassification",
"FunnelModel",
"FunnelPreTrainedModel",
"load_tf_weights_in_funnel",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
"TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFFunnelBaseModel",
"TFFunnelForMaskedLM",
"TFFunnelForMultipleChoice",
"TFFunnelForPreTraining",
"TFFunnelForQuestionAnswering",
"TFFunnelForSequenceClassification",
"TFFunnelForTokenClassification",
"TFFunnelModel",
"TFFunnelPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig
from .tokenization_funnel import FunnelTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_funnel_fast import FunnelTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_funnel import (
FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST,
FunnelBaseModel,
FunnelForMaskedLM,
FunnelForMultipleChoice,
FunnelForPreTraining,
FunnelForQuestionAnswering,
FunnelForSequenceClassification,
FunnelForTokenClassification,
FunnelModel,
FunnelPreTrainedModel,
load_tf_weights_in_funnel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_funnel import (
TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST,
TFFunnelBaseModel,
TFFunnelForMaskedLM,
TFFunnelForMultipleChoice,
TFFunnelForPreTraining,
TFFunnelForQuestionAnswering,
TFFunnelForSequenceClassification,
TFFunnelForTokenClassification,
TFFunnelModel,
TFFunnelPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 59 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
__A = {
"configuration_pix2struct": [
"PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP",
"Pix2StructConfig",
"Pix2StructTextConfig",
"Pix2StructVisionConfig",
],
"processing_pix2struct": ["Pix2StructProcessor"],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = ["Pix2StructImageProcessor"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
"PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST",
"Pix2StructPreTrainedModel",
"Pix2StructForConditionalGeneration",
"Pix2StructVisionModel",
"Pix2StructTextModel",
]
if TYPE_CHECKING:
from .configuration_pixastruct import (
PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP,
PixaStructConfig,
PixaStructTextConfig,
PixaStructVisionConfig,
)
from .processing_pixastruct import PixaStructProcessor
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .image_processing_pixastruct import PixaStructImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_pixastruct import (
PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST,
PixaStructForConditionalGeneration,
PixaStructPreTrainedModel,
PixaStructTextModel,
PixaStructVisionModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 59 | 1 |
import math
def lowerCAmelCase_ ( __a , __a ) -> float:
"""simple docstring"""
if (
not isinstance(__a , (int, float) )
or power_factor < -1
or power_factor > 1
):
raise ValueError("power_factor must be a valid float value between -1 and 1." )
return apparent_power * power_factor
def lowerCAmelCase_ ( __a , __a ) -> float:
"""simple docstring"""
if (
not isinstance(__a , (int, float) )
or power_factor < -1
or power_factor > 1
):
raise ValueError("power_factor must be a valid float value between -1 and 1." )
return apparent_power * math.sqrt(1 - power_factor**2 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 59 |
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_distilbert import DistilBertTokenizer
__A = logging.get_logger(__name__)
__A = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
__A = {
"vocab_file": {
"distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt",
"distilbert-base-uncased-distilled-squad": (
"https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt"
),
"distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt",
"distilbert-base-cased-distilled-squad": (
"https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt"
),
"distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt",
"distilbert-base-multilingual-cased": (
"https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt"
),
},
"tokenizer_file": {
"distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json",
"distilbert-base-uncased-distilled-squad": (
"https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json"
),
"distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json",
"distilbert-base-cased-distilled-squad": (
"https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json"
),
"distilbert-base-german-cased": (
"https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json"
),
"distilbert-base-multilingual-cased": (
"https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json"
),
},
}
__A = {
"distilbert-base-uncased": 512,
"distilbert-base-uncased-distilled-squad": 512,
"distilbert-base-cased": 512,
"distilbert-base-cased-distilled-squad": 512,
"distilbert-base-german-cased": 512,
"distilbert-base-multilingual-cased": 512,
}
__A = {
"distilbert-base-uncased": {"do_lower_case": True},
"distilbert-base-uncased-distilled-squad": {"do_lower_case": True},
"distilbert-base-cased": {"do_lower_case": False},
"distilbert-base-cased-distilled-squad": {"do_lower_case": False},
"distilbert-base-german-cased": {"do_lower_case": False},
"distilbert-base-multilingual-cased": {"do_lower_case": False},
}
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = VOCAB_FILES_NAMES
lowercase_ = PRETRAINED_VOCAB_FILES_MAP
lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowercase_ = PRETRAINED_INIT_CONFIGURATION
lowercase_ = ["input_ids", "attention_mask"]
lowercase_ = DistilBertTokenizer
def __init__(self : Tuple , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[Any]="[UNK]" , UpperCAmelCase_ : Dict="[SEP]" , UpperCAmelCase_ : Dict="[PAD]" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[str]=None , **UpperCAmelCase_ : List[str] , ) ->str:
'''simple docstring'''
super().__init__(
UpperCAmelCase_ , tokenizer_file=UpperCAmelCase_ , do_lower_case=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , tokenize_chinese_chars=UpperCAmelCase_ , strip_accents=UpperCAmelCase_ , **UpperCAmelCase_ , )
lowerCamelCase__: Union[str, Any] =json.loads(self.backend_tokenizer.normalizer.__getstate__())
if (
normalizer_state.get("lowercase" , UpperCAmelCase_) != do_lower_case
or normalizer_state.get("strip_accents" , UpperCAmelCase_) != strip_accents
or normalizer_state.get("handle_chinese_chars" , UpperCAmelCase_) != tokenize_chinese_chars
):
lowerCamelCase__: List[str] =getattr(UpperCAmelCase_ , normalizer_state.pop("type"))
lowerCamelCase__: Optional[int] =do_lower_case
lowerCamelCase__: int =strip_accents
lowerCamelCase__: Any =tokenize_chinese_chars
lowerCamelCase__: Any =normalizer_class(**UpperCAmelCase_)
lowerCamelCase__: str =do_lower_case
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any]=None) ->Dict:
'''simple docstring'''
lowerCamelCase__: str =[self.cls_token_id] + token_ids_a + [self.sep_token_id]
if token_ids_a:
output += token_ids_a + [self.sep_token_id]
return output
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None) ->List[int]:
'''simple docstring'''
lowerCamelCase__: str =[self.sep_token_id]
lowerCamelCase__: str =[self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep) * [0]
return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1]
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None) ->Tuple[str]:
'''simple docstring'''
lowerCamelCase__: str =self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_)
return tuple(UpperCAmelCase_)
| 59 | 1 |
# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
from .config import config_command_parser
from .config_args import default_config_file, load_config_from_file # noqa: F401
from .default import default_command_parser
from .update import update_command_parser
def lowerCAmelCase_ ( __a=None ) -> Tuple:
"""simple docstring"""
lowerCamelCase__: str =argparse.ArgumentParser(add_help=__a , allow_abbrev=__a )
# The main config parser
lowerCamelCase__: Any =config_command_parser(__a )
# The subparser to add commands to
lowerCamelCase__: int =config_parser.add_subparsers(title="subcommands" , dest="subcommand" )
# Then add other parsers with the parent parser
default_command_parser(__a , parents=[parent_parser] )
update_command_parser(__a , parents=[parent_parser] )
return config_parser
def lowerCAmelCase_ ( ) -> int:
"""simple docstring"""
lowerCamelCase__: Optional[int] =get_config_parser()
lowerCamelCase__: Dict =config_parser.parse_args()
if not hasattr(__a , "func" ):
config_parser.print_help()
exit(1 )
# Run
args.func(__a )
if __name__ == "__main__":
main()
| 59 |
import operator as op
def lowerCAmelCase_ ( __a ) -> Tuple:
"""simple docstring"""
lowerCamelCase__: Optional[Any] =[]
lowerCamelCase__: Tuple =lambda __a , __a : int(x / y ) # noqa: E731 integer division operation
lowerCamelCase__: Tuple ={
"^": op.pow,
"*": op.mul,
"/": div,
"+": op.add,
"-": op.sub,
} # operators & their respective operation
# print table header
print("Symbol".center(8 ) , "Action".center(12 ) , "Stack" , sep=" | " )
print("-" * (30 + len(__a )) )
for x in post_fix:
if x.isdigit(): # if x in digit
stack.append(__a ) # append x to stack
# output in tabular format
print(x.rjust(8 ) , ("push(" + x + ")").ljust(12 ) , ",".join(__a ) , sep=" | " )
else:
lowerCamelCase__: List[Any] =stack.pop() # pop stack
# output in tabular format
print("".rjust(8 ) , ("pop(" + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " )
lowerCamelCase__: Optional[Any] =stack.pop() # pop stack
# output in tabular format
print("".rjust(8 ) , ("pop(" + a + ")").ljust(12 ) , ",".join(__a ) , sep=" | " )
stack.append(
str(opr[x](int(__a ) , int(__a ) ) ) ) # evaluate the 2 values popped from stack & push result to stack
# output in tabular format
print(
x.rjust(8 ) , ("push(" + a + x + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " , )
return int(stack[0] )
if __name__ == "__main__":
__A = input("\n\nEnter a Postfix Equation (space separated) = ").split(" ")
print("\n\tResult = ", solve(Postfix))
| 59 | 1 |
from __future__ import annotations
def lowerCAmelCase_ ( __a , __a , __a ) -> int | float:
"""simple docstring"""
if len(__a ) == 0:
raise ValueError("find_max() arg is an empty sequence" )
if (
left >= len(__a )
or left < -len(__a )
or right >= len(__a )
or right < -len(__a )
):
raise IndexError("list index out of range" )
if left == right:
return nums[left]
lowerCamelCase__: Any =(left + right) >> 1 # the middle
lowerCamelCase__: Optional[Any] =find_max(__a , __a , __a ) # find max in range[left, mid]
lowerCamelCase__: List[str] =find_max(__a , mid + 1 , __a ) # find max in range[mid + 1, right]
return left_max if left_max >= right_max else right_max
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
| 59 |
from collections import defaultdict
from typing import Optional
from ..image_utils import load_image
from ..utils import (
add_end_docstrings,
is_torch_available,
logging,
requires_backends,
)
from .base import PIPELINE_INIT_ARGS, ChunkPipeline
if is_torch_available():
import torch
from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING
__A = logging.get_logger(__name__)
@add_end_docstrings(__SCREAMING_SNAKE_CASE )
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__(self : List[Any] , **UpperCAmelCase_ : Any) ->Any:
'''simple docstring'''
super().__init__(**UpperCAmelCase_)
requires_backends(self , "vision")
requires_backends(self , "torch")
if self.framework != "pt":
raise ValueError(F"""The {self.__class__} is only available in PyTorch.""")
self.check_model_type(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Tuple , **UpperCAmelCase_ : List[Any]) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Optional[int] ={}
lowerCamelCase__: Tuple ={}
lowerCamelCase__: str ={}
# preprocess args
if "points_per_batch" in kwargs:
lowerCamelCase__: Optional[Any] =kwargs["points_per_batch"]
if "points_per_crop" in kwargs:
lowerCamelCase__: int =kwargs["points_per_crop"]
if "crops_n_layers" in kwargs:
lowerCamelCase__: Any =kwargs["crops_n_layers"]
if "crop_overlap_ratio" in kwargs:
lowerCamelCase__: Tuple =kwargs["crop_overlap_ratio"]
if "crop_n_points_downscale_factor" in kwargs:
lowerCamelCase__: List[Any] =kwargs["crop_n_points_downscale_factor"]
# postprocess args
if "pred_iou_thresh" in kwargs:
lowerCamelCase__: List[str] =kwargs["pred_iou_thresh"]
if "stability_score_offset" in kwargs:
lowerCamelCase__: int =kwargs["stability_score_offset"]
if "mask_threshold" in kwargs:
lowerCamelCase__: Optional[int] =kwargs["mask_threshold"]
if "stability_score_thresh" in kwargs:
lowerCamelCase__: str =kwargs["stability_score_thresh"]
if "crops_nms_thresh" in kwargs:
lowerCamelCase__: Any =kwargs["crops_nms_thresh"]
if "output_rle_mask" in kwargs:
lowerCamelCase__: List[Any] =kwargs["output_rle_mask"]
if "output_bboxes_mask" in kwargs:
lowerCamelCase__: List[str] =kwargs["output_bboxes_mask"]
return preprocess_kwargs, forward_params, postprocess_kwargs
def __call__(self : int , UpperCAmelCase_ : Dict , *UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[Any]:
'''simple docstring'''
return super().__call__(UpperCAmelCase_ , *UpperCAmelCase_ , num_workers=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any]=64 , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : float = 512 / 1_500 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 1 , ) ->Dict:
'''simple docstring'''
lowerCamelCase__: Dict =load_image(UpperCAmelCase_)
lowerCamelCase__: List[str] =self.image_processor.size["longest_edge"]
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =self.image_processor.generate_crop_boxes(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: str =self.image_processor(images=UpperCAmelCase_ , return_tensors="pt")
with self.device_placement():
if self.framework == "pt":
lowerCamelCase__: str =self.get_inference_context()
with inference_context():
lowerCamelCase__: Union[str, Any] =self._ensure_tensor_on_device(UpperCAmelCase_ , device=self.device)
lowerCamelCase__: Optional[Any] =self.model.get_image_embeddings(model_inputs.pop("pixel_values"))
lowerCamelCase__: str =image_embeddings
lowerCamelCase__: int =grid_points.shape[1]
lowerCamelCase__: int =points_per_batch if points_per_batch is not None else n_points
if points_per_batch <= 0:
raise ValueError(
"Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. "
"To return all points at once, set points_per_batch to None")
for i in range(0 , UpperCAmelCase_ , UpperCAmelCase_):
lowerCamelCase__: int =grid_points[:, i : i + points_per_batch, :, :]
lowerCamelCase__: Optional[Any] =input_labels[:, i : i + points_per_batch]
lowerCamelCase__: Dict =i == n_points - points_per_batch
yield {
"input_points": batched_points,
"input_labels": labels,
"input_boxes": crop_boxes,
"is_last": is_last,
**model_inputs,
}
def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=0.88 , UpperCAmelCase_ : Optional[Any]=0.95 , UpperCAmelCase_ : Tuple=0 , UpperCAmelCase_ : Any=1 , ) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Any =model_inputs.pop("input_boxes")
lowerCamelCase__: Dict =model_inputs.pop("is_last")
lowerCamelCase__: int =model_inputs.pop("original_sizes").tolist()
lowerCamelCase__: Union[str, Any] =model_inputs.pop("reshaped_input_sizes").tolist()
lowerCamelCase__: Union[str, Any] =self.model(**UpperCAmelCase_)
# post processing happens here in order to avoid CPU GPU copies of ALL the masks
lowerCamelCase__: Optional[int] =model_outputs["pred_masks"]
lowerCamelCase__: Union[str, Any] =self.image_processor.post_process_masks(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , binarize=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =model_outputs["iou_scores"]
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =self.image_processor.filter_masks(
masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , )
return {
"masks": masks,
"is_last": is_last,
"boxes": boxes,
"iou_scores": iou_scores,
}
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Optional[int]=0.7 , ) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Any =[]
lowerCamelCase__: Optional[int] =[]
lowerCamelCase__: List[str] =[]
for model_output in model_outputs:
all_scores.append(model_output.pop("iou_scores"))
all_masks.extend(model_output.pop("masks"))
all_boxes.append(model_output.pop("boxes"))
lowerCamelCase__: str =torch.cat(UpperCAmelCase_)
lowerCamelCase__: List[str] =torch.cat(UpperCAmelCase_)
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Dict =self.image_processor.post_process_for_mask_generation(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: List[str] =defaultdict(UpperCAmelCase_)
for output in model_outputs:
for k, v in output.items():
extra[k].append(UpperCAmelCase_)
lowerCamelCase__: Any ={}
if output_rle_mask:
lowerCamelCase__: Union[str, Any] =rle_mask
if output_bboxes_mask:
lowerCamelCase__: int =bounding_boxes
return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
| 59 | 1 |
from collections import OrderedDict
from typing import Any, List, Mapping, Optional
from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
"EleutherAI/gpt-j-6B": "https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json",
# See all GPT-J models at https://huggingface.co/models?filter=gpt_j
}
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = "gptj"
lowercase_ = {
"max_position_embeddings": "n_positions",
"hidden_size": "n_embd",
"num_attention_heads": "n_head",
"num_hidden_layers": "n_layer",
}
def __init__(self : List[Any] , UpperCAmelCase_ : Dict=50_400 , UpperCAmelCase_ : Any=2_048 , UpperCAmelCase_ : Dict=4_096 , UpperCAmelCase_ : Dict=28 , UpperCAmelCase_ : Dict=16 , UpperCAmelCase_ : int=64 , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : Tuple="gelu_new" , UpperCAmelCase_ : Tuple=0.0 , UpperCAmelCase_ : int=0.0 , UpperCAmelCase_ : int=0.0 , UpperCAmelCase_ : Union[str, Any]=1E-5 , UpperCAmelCase_ : List[Any]=0.02 , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Optional[Any]=50_256 , UpperCAmelCase_ : List[str]=50_256 , UpperCAmelCase_ : str=False , **UpperCAmelCase_ : Optional[int] , ) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =vocab_size
lowerCamelCase__: Union[str, Any] =n_positions
lowerCamelCase__: int =n_embd
lowerCamelCase__: Union[str, Any] =n_layer
lowerCamelCase__: Optional[Any] =n_head
lowerCamelCase__: str =n_inner
lowerCamelCase__: int =rotary_dim
lowerCamelCase__: List[str] =activation_function
lowerCamelCase__: int =resid_pdrop
lowerCamelCase__: Any =embd_pdrop
lowerCamelCase__: Union[str, Any] =attn_pdrop
lowerCamelCase__: List[Any] =layer_norm_epsilon
lowerCamelCase__: Optional[Any] =initializer_range
lowerCamelCase__: Optional[Any] =use_cache
lowerCamelCase__: Any =bos_token_id
lowerCamelCase__: Tuple =eos_token_id
super().__init__(
bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , tie_word_embeddings=UpperCAmelCase_ , **UpperCAmelCase_)
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__(self : Union[str, Any] , UpperCAmelCase_ : PretrainedConfig , UpperCAmelCase_ : str = "default" , UpperCAmelCase_ : List[PatchingSpec] = None , UpperCAmelCase_ : bool = False , ) ->List[Any]:
'''simple docstring'''
super().__init__(UpperCAmelCase_ , task=UpperCAmelCase_ , patching_specs=UpperCAmelCase_ , use_past=UpperCAmelCase_)
if not getattr(self._config , "pad_token_id" , UpperCAmelCase_):
# TODO: how to do that better?
lowerCamelCase__: Optional[int] =0
@property
def SCREAMING_SNAKE_CASE_ (self : str) ->Mapping[str, Mapping[int, str]]:
'''simple docstring'''
lowerCamelCase__: Dict =OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
if self.use_past:
self.fill_with_past_key_values_(UpperCAmelCase_ , direction="inputs")
lowerCamelCase__: int ={0: "batch", 1: "past_sequence + sequence"}
else:
lowerCamelCase__: List[Any] ={0: "batch", 1: "sequence"}
return common_inputs
@property
def SCREAMING_SNAKE_CASE_ (self : Any) ->int:
'''simple docstring'''
return self._config.n_layer
@property
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->int:
'''simple docstring'''
return self._config.n_head
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : PreTrainedTokenizer , UpperCAmelCase_ : int = -1 , UpperCAmelCase_ : int = -1 , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : Optional[TensorType] = None , ) ->Mapping[str, Any]:
'''simple docstring'''
lowerCamelCase__: List[Any] =super(UpperCAmelCase_ , self).generate_dummy_inputs(
UpperCAmelCase_ , batch_size=UpperCAmelCase_ , seq_length=UpperCAmelCase_ , is_pair=UpperCAmelCase_ , framework=UpperCAmelCase_)
# We need to order the input in the way they appears in the forward()
lowerCamelCase__: str =OrderedDict({"input_ids": common_inputs["input_ids"]})
# Need to add the past_keys
if self.use_past:
if not is_torch_available():
raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
else:
import torch
lowerCamelCase__ , lowerCamelCase__: List[str] =common_inputs["input_ids"].shape
# Not using the same length for past_key_values
lowerCamelCase__: List[Any] =seqlen + 2
lowerCamelCase__: Optional[int] =(
batch,
self.num_attention_heads,
past_key_values_length,
self._config.hidden_size // self.num_attention_heads,
)
lowerCamelCase__: str =[
(torch.zeros(UpperCAmelCase_), torch.zeros(UpperCAmelCase_)) for _ in range(self.num_layers)
]
lowerCamelCase__: Dict =common_inputs["attention_mask"]
if self.use_past:
lowerCamelCase__: Optional[Any] =ordered_inputs["attention_mask"].dtype
lowerCamelCase__: str =torch.cat(
[ordered_inputs["attention_mask"], torch.ones(UpperCAmelCase_ , UpperCAmelCase_ , dtype=UpperCAmelCase_)] , dim=1)
return ordered_inputs
@property
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->int:
'''simple docstring'''
return 13
| 59 |
from transformers import BertTokenizerFast
from .custom_tokenization import CustomTokenizer
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = CustomTokenizer
pass
| 59 | 1 |
import os
from glob import glob
import imageio
import torch
import torchvision
import wandb
from img_processing import custom_to_pil, loop_post_process, preprocess, preprocess_vqgan
from loaders import load_vqgan
from PIL import Image
from torch import nn
from transformers import CLIPModel, CLIPTokenizerFast
from utils import get_device, get_timestamp, show_pil
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__(self : List[Any] , UpperCAmelCase_ : str = "cpu" , UpperCAmelCase_ : str = "openai/clip-vit-large-patch14") ->None:
'''simple docstring'''
lowerCamelCase__: Tuple =device
lowerCamelCase__: Optional[int] =CLIPTokenizerFast.from_pretrained(UpperCAmelCase_)
lowerCamelCase__: Any =[0.4814_5466, 0.457_8275, 0.4082_1073]
lowerCamelCase__: Union[str, Any] =[0.2686_2954, 0.2613_0258, 0.2757_7711]
lowerCamelCase__: Union[str, Any] =torchvision.transforms.Normalize(self.image_mean , self.image_std)
lowerCamelCase__: List[Any] =torchvision.transforms.Resize(224)
lowerCamelCase__: Dict =torchvision.transforms.CenterCrop(224)
def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : str) ->Any:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =self.resize(UpperCAmelCase_)
lowerCamelCase__: Optional[int] =self.center_crop(UpperCAmelCase_)
lowerCamelCase__: Dict =self.normalize(UpperCAmelCase_)
return images
def __call__(self : Any , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : str=None , **UpperCAmelCase_ : Tuple) ->List[Any]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =self.tokenizer(text=UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: str =self.preprocess_img(UpperCAmelCase_)
lowerCamelCase__: str ={key: value.to(self.device) for (key, value) in encoding.items()}
return encoding
class _SCREAMING_SNAKE_CASE ( nn.Module ):
'''simple docstring'''
def __init__(self : Any , UpperCAmelCase_ : List[Any]=10 , UpperCAmelCase_ : int=0.01 , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Any=False , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : str="image" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : str=False , UpperCAmelCase_ : Dict=False , UpperCAmelCase_ : Optional[Any]=False , ) ->None:
'''simple docstring'''
super().__init__()
lowerCamelCase__: Optional[int] =None
lowerCamelCase__: str =device if device else get_device()
if vqgan:
lowerCamelCase__: Dict =vqgan
else:
lowerCamelCase__: Optional[Any] =load_vqgan(self.device , conf_path=UpperCAmelCase_ , ckpt_path=UpperCAmelCase_)
self.vqgan.eval()
if clip:
lowerCamelCase__: Union[str, Any] =clip
else:
lowerCamelCase__: str =CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
self.clip.to(self.device)
lowerCamelCase__: str =ProcessorGradientFlow(device=self.device)
lowerCamelCase__: Union[str, Any] =iterations
lowerCamelCase__: str =lr
lowerCamelCase__: str =log
lowerCamelCase__: str =make_grid
lowerCamelCase__: int =return_val
lowerCamelCase__: int =quantize
lowerCamelCase__: Dict =self.vqgan.decoder.z_shape
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : List[Any]=5 , UpperCAmelCase_ : Union[str, Any]=True) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Dict =[]
if output_path is None:
lowerCamelCase__: Union[str, Any] ="./animation.gif"
if input_path is None:
lowerCamelCase__: List[Any] =self.save_path
lowerCamelCase__: Any =sorted(glob(input_path + "/*"))
if not len(UpperCAmelCase_):
raise ValueError(
"No images found in save path, aborting (did you pass save_intermediate=True to the generate"
" function?)")
if len(UpperCAmelCase_) == 1:
print("Only one image found in save path, (did you pass save_intermediate=True to the generate function?)")
lowerCamelCase__: Tuple =total_duration / len(UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =[frame_duration] * len(UpperCAmelCase_)
if extend_frames:
lowerCamelCase__: int =1.5
lowerCamelCase__: Optional[int] =3
for file_name in paths:
if file_name.endswith(".png"):
images.append(imageio.imread(UpperCAmelCase_))
imageio.mimsave(UpperCAmelCase_ , UpperCAmelCase_ , duration=UpperCAmelCase_)
print(F"""gif saved to {output_path}""")
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Any=None) ->Tuple:
'''simple docstring'''
if not (path or img):
raise ValueError("Input either path or tensor")
if img is not None:
raise NotImplementedError
lowerCamelCase__: str =preprocess(Image.open(UpperCAmelCase_) , target_image_size=256).to(self.device)
lowerCamelCase__: Any =preprocess_vqgan(UpperCAmelCase_)
lowerCamelCase__ , *lowerCamelCase__: str =self.vqgan.encode(UpperCAmelCase_)
return z
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List[Any]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =self.latent.detach().requires_grad_()
lowerCamelCase__: List[Any] =base_latent + transform_vector
if self.quantize:
lowerCamelCase__ , *lowerCamelCase__: int =self.vqgan.quantize(UpperCAmelCase_)
else:
lowerCamelCase__: str =trans_latent
return self.vqgan.decode(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Union[str, Any]=None) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =self.clip_preprocessor(text=UpperCAmelCase_ , images=UpperCAmelCase_ , return_tensors="pt" , padding=UpperCAmelCase_)
lowerCamelCase__: List[str] =self.clip(**UpperCAmelCase_)
lowerCamelCase__: int =clip_outputs.logits_per_image
if weights is not None:
lowerCamelCase__: Optional[int] =similarity_logits * weights
return similarity_logits.sum()
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : int) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Dict =self._get_clip_similarity(pos_prompts["prompts"] , UpperCAmelCase_ , weights=(1 / pos_prompts["weights"]))
if neg_prompts:
lowerCamelCase__: Tuple =self._get_clip_similarity(neg_prompts["prompts"] , UpperCAmelCase_ , weights=neg_prompts["weights"])
else:
lowerCamelCase__: List[Any] =torch.tensor([1] , device=self.device)
lowerCamelCase__: Union[str, Any] =-torch.log(UpperCAmelCase_) + torch.log(UpperCAmelCase_)
return loss
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any]) ->int:
'''simple docstring'''
lowerCamelCase__: Dict =torch.randn_like(self.latent , requires_grad=UpperCAmelCase_ , device=self.device)
lowerCamelCase__: Any =torch.optim.Adam([vector] , lr=self.lr)
for i in range(self.iterations):
optim.zero_grad()
lowerCamelCase__: List[Any] =self._add_vector(UpperCAmelCase_)
lowerCamelCase__: Optional[int] =loop_post_process(UpperCAmelCase_)
lowerCamelCase__: str =self._get_CLIP_loss(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
print("CLIP loss" , UpperCAmelCase_)
if self.log:
wandb.log({"CLIP Loss": clip_loss})
clip_loss.backward(retain_graph=UpperCAmelCase_)
optim.step()
if self.return_val == "image":
yield custom_to_pil(transformed_img[0])
else:
yield vector
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any]) ->str:
'''simple docstring'''
wandb.init(reinit=UpperCAmelCase_ , project="face-editor")
wandb.config.update({"Positive Prompts": positive_prompts})
wandb.config.update({"Negative Prompts": negative_prompts})
wandb.config.update({"lr": self.lr, "iterations": self.iterations})
if image_path:
lowerCamelCase__: Dict =Image.open(UpperCAmelCase_)
lowerCamelCase__: str =image.resize((256, 256))
wandb.log("Original Image" , wandb.Image(UpperCAmelCase_))
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : Optional[int]) ->int:
'''simple docstring'''
if not prompts:
return []
lowerCamelCase__: Optional[Any] =[]
lowerCamelCase__: Union[str, Any] =[]
if isinstance(UpperCAmelCase_ , UpperCAmelCase_):
lowerCamelCase__: Tuple =[prompt.strip() for prompt in prompts.split("|")]
for prompt in prompts:
if isinstance(UpperCAmelCase_ , (tuple, list)):
lowerCamelCase__: Optional[Any] =prompt[0]
lowerCamelCase__: Dict =float(prompt[1])
elif ":" in prompt:
lowerCamelCase__ , lowerCamelCase__: Optional[Any] =prompt.split(":")
lowerCamelCase__: str =float(UpperCAmelCase_)
else:
lowerCamelCase__: List[str] =prompt
lowerCamelCase__: Any =1.0
processed_prompts.append(UpperCAmelCase_)
weights.append(UpperCAmelCase_)
return {
"prompts": processed_prompts,
"weights": torch.tensor(UpperCAmelCase_ , device=self.device),
}
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[Any]=False , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : Tuple=None , ) ->List[str]:
'''simple docstring'''
if image_path:
lowerCamelCase__: Any =self._get_latent(UpperCAmelCase_)
else:
lowerCamelCase__: int =torch.randn(self.latent_dim , device=self.device)
if self.log:
self._init_logging(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
assert pos_prompts, "You must provide at least one positive prompt."
lowerCamelCase__: Optional[int] =self.process_prompts(UpperCAmelCase_)
lowerCamelCase__: Dict =self.process_prompts(UpperCAmelCase_)
if save_final and save_path is None:
lowerCamelCase__: Optional[Any] =os.path.join("./outputs/" , "_".join(pos_prompts["prompts"]))
if not os.path.exists(UpperCAmelCase_):
os.makedirs(UpperCAmelCase_)
else:
lowerCamelCase__: Dict =save_path + "_" + get_timestamp()
os.makedirs(UpperCAmelCase_)
lowerCamelCase__: int =save_path
lowerCamelCase__: Dict =self.vqgan.decode(self.latent)[0]
if show_intermediate:
print("Original Image")
show_pil(custom_to_pil(UpperCAmelCase_))
lowerCamelCase__: List[Any] =loop_post_process(UpperCAmelCase_)
for iter, transformed_img in enumerate(self._optimize_CLIP(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)):
if show_intermediate:
show_pil(UpperCAmelCase_)
if save_intermediate:
transformed_img.save(os.path.join(self.save_path , F"""iter_{iter:03d}.png"""))
if self.log:
wandb.log({"Image": wandb.Image(UpperCAmelCase_)})
if show_final:
show_pil(UpperCAmelCase_)
if save_final:
transformed_img.save(os.path.join(self.save_path , F"""iter_{iter:03d}_final.png"""))
| 59 |
import inspect
import os
import unittest
import torch
import accelerate
from accelerate import Accelerator
from accelerate.test_utils import execute_subprocess_async, require_multi_gpu
from accelerate.utils import patch_environment
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: List[Any] =inspect.getfile(accelerate.test_utils)
lowerCamelCase__: List[Any] =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_script.py"])
lowerCamelCase__: Any =os.path.sep.join(
mod_file.split(os.path.sep)[:-1] + ["scripts", "test_distributed_data_loop.py"])
lowerCamelCase__: Tuple =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_ops.py"])
@require_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : str) ->str:
'''simple docstring'''
print(F"""Found {torch.cuda.device_count()} devices.""")
lowerCamelCase__: Union[str, Any] =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path]
with patch_environment(omp_num_threads=1):
execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy())
@require_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[Any]:
'''simple docstring'''
print(F"""Found {torch.cuda.device_count()} devices.""")
lowerCamelCase__: Dict =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path]
print(F"""Command: {cmd}""")
with patch_environment(omp_num_threads=1):
execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy())
@require_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Tuple:
'''simple docstring'''
lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__)]
with patch_environment(omp_num_threads=1):
execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy())
@require_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]:
'''simple docstring'''
print(F"""Found {torch.cuda.device_count()} devices, using 2 devices only""")
lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path]
with patch_environment(omp_num_threads=1 , cuda_visible_devices="0,1"):
execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy())
if __name__ == "__main__":
__A = Accelerator()
__A = (accelerator.state.process_index + 2, 10)
__A = torch.randint(0, 10, shape).to(accelerator.device)
__A = ""
__A = accelerator.pad_across_processes(tensor)
if tensora.shape[0] != accelerator.state.num_processes + 1:
error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0."
if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor):
error_msg += "Tensors have different values."
if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0):
error_msg += "Padding was not done with the right value (0)."
__A = accelerator.pad_across_processes(tensor, pad_first=True)
if tensora.shape[0] != accelerator.state.num_processes + 1:
error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0."
__A = accelerator.state.num_processes - accelerator.state.process_index - 1
if not torch.equal(tensora[index:], tensor):
error_msg += "Tensors have different values."
if not torch.all(tensora[:index] == 0):
error_msg += "Padding was not done with the right value (0)."
# Raise error at the end to make sure we don't stop at the first failure.
if len(error_msg) > 0:
raise ValueError(error_msg)
| 59 | 1 |
from typing import List, Optional, Union
import numpy as np
from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ....feature_extraction_sequence_utils import SequenceFeatureExtractor
from ....feature_extraction_utils import BatchFeature
from ....file_utils import PaddingStrategy, TensorType
from ....utils import logging
__A = logging.get_logger(__name__)
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = ["input_features", "attention_mask"]
def __init__(self : List[str] , UpperCAmelCase_ : Any=80 , UpperCAmelCase_ : List[Any]=16_000 , UpperCAmelCase_ : Dict=0.0 , UpperCAmelCase_ : Optional[Any]=10 , UpperCAmelCase_ : Optional[int]=25 , UpperCAmelCase_ : Optional[Any]="hamming_window" , UpperCAmelCase_ : Union[str, Any]=3_2768.0 , UpperCAmelCase_ : Union[str, Any]=0.97 , UpperCAmelCase_ : Optional[Any]=1.0 , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Any=False , **UpperCAmelCase_ : Optional[int] , ) ->List[str]:
'''simple docstring'''
super().__init__(feature_size=UpperCAmelCase_ , sampling_rate=UpperCAmelCase_ , padding_value=UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: Tuple =feature_size
lowerCamelCase__: str =sampling_rate
lowerCamelCase__: Tuple =padding_value
lowerCamelCase__: Optional[Any] =hop_length
lowerCamelCase__: List[str] =win_length
lowerCamelCase__: Dict =frame_signal_scale
lowerCamelCase__: Optional[int] =preemphasis_coeff
lowerCamelCase__: int =mel_floor
lowerCamelCase__: Optional[int] =normalize_means
lowerCamelCase__: Optional[int] =normalize_vars
lowerCamelCase__: List[Any] =win_function
lowerCamelCase__: int =return_attention_mask
lowerCamelCase__: Union[str, Any] =win_length * sampling_rate // 1_000
lowerCamelCase__: List[Any] =hop_length * sampling_rate // 1_000
lowerCamelCase__: Tuple =optimal_fft_length(self.sample_size)
lowerCamelCase__: Optional[Any] =(self.n_fft // 2) + 1
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : np.array) ->np.ndarray:
'''simple docstring'''
if self.win_function == "hamming_window":
lowerCamelCase__: Tuple =window_function(window_length=self.sample_size , name=self.win_function , periodic=UpperCAmelCase_)
else:
lowerCamelCase__: int =window_function(window_length=self.sample_size , name=self.win_function)
lowerCamelCase__: int =mel_filter_bank(
num_frequency_bins=self.n_freqs , num_mel_filters=self.feature_size , min_frequency=0.0 , max_frequency=self.sampling_rate / 2.0 , sampling_rate=self.sampling_rate , )
lowerCamelCase__: Dict =spectrogram(
one_waveform * self.frame_signal_scale , window=UpperCAmelCase_ , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , center=UpperCAmelCase_ , preemphasis=self.preemphasis_coeff , mel_filters=UpperCAmelCase_ , mel_floor=self.mel_floor , log_mel="log" , )
return msfc_features.T
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : int) ->List[str]:
'''simple docstring'''
if self.normalize_means:
lowerCamelCase__: str =x[:input_length].mean(axis=0)
lowerCamelCase__: Optional[Any] =np.subtract(UpperCAmelCase_ , UpperCAmelCase_)
if self.normalize_vars:
lowerCamelCase__: Tuple =x[:input_length].std(axis=0)
lowerCamelCase__: Union[str, Any] =np.divide(UpperCAmelCase_ , UpperCAmelCase_)
if input_length < x.shape[0]:
lowerCamelCase__: List[str] =padding_value
# make sure array is in float32
lowerCamelCase__: Union[str, Any] =x.astype(np.floataa)
return x
def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : List[np.ndarray] , UpperCAmelCase_ : Optional[np.ndarray] = None) ->List[np.ndarray]:
'''simple docstring'''
lowerCamelCase__: List[str] =attention_mask.sum(-1) if attention_mask is not None else [x.shape[0] for x in input_features]
return [self._normalize_one(UpperCAmelCase_ , UpperCAmelCase_ , self.padding_value) for x, n in zip(UpperCAmelCase_ , UpperCAmelCase_)]
def __call__(self : int , UpperCAmelCase_ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , UpperCAmelCase_ : Union[bool, str, PaddingStrategy] = False , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[Union[str, TensorType]] = None , UpperCAmelCase_ : Optional[int] = None , **UpperCAmelCase_ : List[str] , ) ->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} was trained using a sampling rate of"""
F""" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with"""
F""" {self.sampling_rate} and not {sampling_rate}.""")
else:
logger.warning(
"It is strongly recommended to pass the ``sampling_rate`` argument to this function. "
"Failing to do so can result in silent errors that might be hard to debug.")
lowerCamelCase__: Optional[Any] =isinstance(UpperCAmelCase_ , 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}""")
lowerCamelCase__: Optional[Any] =is_batched_numpy or (
isinstance(UpperCAmelCase_ , (list, tuple)) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list)))
)
if is_batched:
lowerCamelCase__: Tuple =[np.asarray(UpperCAmelCase_ , dtype=np.floataa) for speech in raw_speech]
elif not is_batched and not isinstance(UpperCAmelCase_ , np.ndarray):
lowerCamelCase__: str =np.asarray(UpperCAmelCase_ , dtype=np.floataa)
elif isinstance(UpperCAmelCase_ , np.ndarray) and raw_speech.dtype is np.dtype(np.floataa):
lowerCamelCase__: Optional[Any] =raw_speech.astype(np.floataa)
# always return batch
if not is_batched:
lowerCamelCase__: Optional[int] =[raw_speech]
# extract fbank features
lowerCamelCase__: List[Any] =[self._extract_mfsc_features(UpperCAmelCase_) for one_waveform in raw_speech]
# convert into correct format for padding
lowerCamelCase__: Dict =BatchFeature({"input_features": features})
lowerCamelCase__: Any =self.pad(
UpperCAmelCase_ , padding=UpperCAmelCase_ , max_length=UpperCAmelCase_ , truncation=UpperCAmelCase_ , pad_to_multiple_of=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , **UpperCAmelCase_ , )
# make sure list is in array format
lowerCamelCase__: Optional[Any] =padded_inputs.get("input_features")
if isinstance(input_features[0] , UpperCAmelCase_):
lowerCamelCase__: Any =[np.asarray(UpperCAmelCase_ , dtype=np.floataa) for feature in input_features]
lowerCamelCase__: Dict =padded_inputs.get("attention_mask")
if attention_mask is not None:
lowerCamelCase__: str =[np.asarray(UpperCAmelCase_ , dtype=np.intaa) for array in attention_mask]
if self.normalize_means or self.normalize_vars:
lowerCamelCase__: str =(
np.array(UpperCAmelCase_ , dtype=np.intaa)
if self._get_padding_strategies(UpperCAmelCase_ , max_length=UpperCAmelCase_) is not PaddingStrategy.DO_NOT_PAD
and padding
else None
)
lowerCamelCase__: Optional[Any] =self.normalize(
padded_inputs["input_features"] , attention_mask=UpperCAmelCase_)
if return_tensors is not None:
lowerCamelCase__: int =padded_inputs.convert_to_tensors(UpperCAmelCase_)
return padded_inputs
| 59 |
from typing import List, Optional, Tuple, Union
import PIL
import torch
from torchvision import transforms
from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
from diffusers.schedulers import DDIMScheduler
from diffusers.utils import randn_tensor
__A = transforms.Compose(
[
transforms.Resize((256, 256)),
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5]),
]
)
def lowerCAmelCase_ ( __a ) -> str:
"""simple docstring"""
if isinstance(__a , torch.Tensor ):
return image
elif isinstance(__a , PIL.Image.Image ):
lowerCamelCase__: Any =[image]
lowerCamelCase__: Optional[Any] =[trans(img.convert("RGB" ) ) for img in image]
lowerCamelCase__: Dict =torch.stack(__a )
return image
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__(self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple) ->int:
'''simple docstring'''
super().__init__()
# make sure scheduler can always be converted to DDIM
lowerCamelCase__: Tuple =DDIMScheduler.from_config(scheduler.config)
self.register_modules(unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Union[str, Any]) ->Dict:
'''simple docstring'''
if strength < 0 or strength > 1:
raise ValueError(F"""The value of strength should in [0.0, 1.0] but is {strength}""")
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple) ->Tuple:
'''simple docstring'''
lowerCamelCase__: int =min(int(num_inference_steps * strength) , UpperCAmelCase_)
lowerCamelCase__: str =max(num_inference_steps - init_timestep , 0)
lowerCamelCase__: int =self.scheduler.timesteps[t_start:]
return timesteps, num_inference_steps - t_start
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int]=None) ->Optional[int]:
'''simple docstring'''
if not isinstance(UpperCAmelCase_ , (torch.Tensor, PIL.Image.Image, list)):
raise ValueError(
F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(UpperCAmelCase_)}""")
lowerCamelCase__: Optional[int] =image.to(device=UpperCAmelCase_ , dtype=UpperCAmelCase_)
if isinstance(UpperCAmelCase_ , UpperCAmelCase_) and len(UpperCAmelCase_) != batch_size:
raise ValueError(
F"""You have passed a list of generators of length {len(UpperCAmelCase_)}, but requested an effective batch"""
F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""")
lowerCamelCase__: Dict =init_latents.shape
lowerCamelCase__: int =randn_tensor(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=UpperCAmelCase_)
# get latents
print("add noise to latents at timestep" , UpperCAmelCase_)
lowerCamelCase__: Union[str, Any] =self.scheduler.add_noise(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: int =init_latents
return latents
@torch.no_grad()
def __call__(self : Tuple , UpperCAmelCase_ : Union[torch.FloatTensor, PIL.Image.Image] = None , UpperCAmelCase_ : float = 0.8 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , ) ->Union[ImagePipelineOutput, Tuple]:
'''simple docstring'''
self.check_inputs(UpperCAmelCase_)
# 2. Preprocess image
lowerCamelCase__: Dict =preprocess(UpperCAmelCase_)
# 3. set timesteps
self.scheduler.set_timesteps(UpperCAmelCase_ , device=self.device)
lowerCamelCase__ , lowerCamelCase__: str =self.get_timesteps(UpperCAmelCase_ , UpperCAmelCase_ , self.device)
lowerCamelCase__: Optional[int] =timesteps[:1].repeat(UpperCAmelCase_)
# 4. Prepare latent variables
lowerCamelCase__: int =self.prepare_latents(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , self.unet.dtype , self.device , UpperCAmelCase_)
lowerCamelCase__: Tuple =latents
# 5. Denoising loop
for t in self.progress_bar(UpperCAmelCase_):
# 1. predict noise model_output
lowerCamelCase__: Dict =self.unet(UpperCAmelCase_ , UpperCAmelCase_).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
lowerCamelCase__: Optional[int] =self.scheduler.step(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , eta=UpperCAmelCase_ , use_clipped_model_output=UpperCAmelCase_ , generator=UpperCAmelCase_ , ).prev_sample
lowerCamelCase__: str =(image / 2 + 0.5).clamp(0 , 1)
lowerCamelCase__: Optional[Any] =image.cpu().permute(0 , 2 , 3 , 1).numpy()
if output_type == "pil":
lowerCamelCase__: Dict =self.numpy_to_pil(UpperCAmelCase_)
if not return_dict:
return (image, latent_timestep.item())
return ImagePipelineOutput(images=UpperCAmelCase_)
| 59 | 1 |
from math import factorial
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__(self : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[str]) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =real
if isinstance(UpperCAmelCase_ , UpperCAmelCase_):
lowerCamelCase__: Optional[int] =[1] * rank
else:
lowerCamelCase__: str =rank
def __repr__(self : Optional[int]) ->Optional[Any]:
'''simple docstring'''
return (
F"""{self.real}+"""
F"""{"+".join(str(UpperCAmelCase_)+"E"+str(n+1)for n,dual in enumerate(self.duals))}"""
)
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Any:
'''simple docstring'''
lowerCamelCase__: Any =self.duals.copy()
while cur[-1] == 0:
cur.pop(-1)
return Dual(self.real , UpperCAmelCase_)
def __add__(self : Union[str, Any] , UpperCAmelCase_ : List[str]) ->List[Any]:
'''simple docstring'''
if not isinstance(UpperCAmelCase_ , UpperCAmelCase_):
return Dual(self.real + other , self.duals)
lowerCamelCase__: List[Any] =self.duals.copy()
lowerCamelCase__: List[str] =other.duals.copy()
if len(UpperCAmelCase_) > len(UpperCAmelCase_):
o_dual.extend([1] * (len(UpperCAmelCase_) - len(UpperCAmelCase_)))
elif len(UpperCAmelCase_) < len(UpperCAmelCase_):
s_dual.extend([1] * (len(UpperCAmelCase_) - len(UpperCAmelCase_)))
lowerCamelCase__: List[str] =[]
for i in range(len(UpperCAmelCase_)):
new_duals.append(s_dual[i] + o_dual[i])
return Dual(self.real + other.real , UpperCAmelCase_)
lowercase_ = __add__
def __sub__(self : Union[str, Any] , UpperCAmelCase_ : List[Any]) ->str:
'''simple docstring'''
return self + other * -1
def __mul__(self : str , UpperCAmelCase_ : Optional[int]) ->Union[str, Any]:
'''simple docstring'''
if not isinstance(UpperCAmelCase_ , UpperCAmelCase_):
lowerCamelCase__: Dict =[]
for i in self.duals:
new_duals.append(i * other)
return Dual(self.real * other , UpperCAmelCase_)
lowerCamelCase__: Any =[0] * (len(self.duals) + len(other.duals) + 1)
for i, item in enumerate(self.duals):
for j, jtem in enumerate(other.duals):
new_duals[i + j + 1] += item * jtem
for k in range(len(self.duals)):
new_duals[k] += self.duals[k] * other.real
for index in range(len(other.duals)):
new_duals[index] += other.duals[index] * self.real
return Dual(self.real * other.real , UpperCAmelCase_)
lowercase_ = __mul__
def __truediv__(self : Tuple , UpperCAmelCase_ : str) ->List[str]:
'''simple docstring'''
if not isinstance(UpperCAmelCase_ , UpperCAmelCase_):
lowerCamelCase__: Tuple =[]
for i in self.duals:
new_duals.append(i / other)
return Dual(self.real / other , UpperCAmelCase_)
raise ValueError
def __floordiv__(self : Union[str, Any] , UpperCAmelCase_ : Dict) ->int:
'''simple docstring'''
if not isinstance(UpperCAmelCase_ , UpperCAmelCase_):
lowerCamelCase__: Any =[]
for i in self.duals:
new_duals.append(i // other)
return Dual(self.real // other , UpperCAmelCase_)
raise ValueError
def __pow__(self : List[Any] , UpperCAmelCase_ : Optional[Any]) ->Tuple:
'''simple docstring'''
if n < 0 or isinstance(UpperCAmelCase_ , UpperCAmelCase_):
raise ValueError("power must be a positive integer")
if n == 0:
return 1
if n == 1:
return self
lowerCamelCase__: Union[str, Any] =self
for _ in range(n - 1):
x *= self
return x
def lowerCAmelCase_ ( __a , __a , __a ) -> Any:
"""simple docstring"""
if not callable(__a ):
raise ValueError("differentiate() requires a function as input for func" )
if not isinstance(__a , (float, int) ):
raise ValueError("differentiate() requires a float as input for position" )
if not isinstance(__a , __a ):
raise ValueError("differentiate() requires an int as input for order" )
lowerCamelCase__: Union[str, Any] =Dual(__a , 1 )
lowerCamelCase__: str =func(__a )
if order == 0:
return result.real
return result.duals[order - 1] * factorial(__a )
if __name__ == "__main__":
import doctest
doctest.testmod()
def lowerCAmelCase_ ( __a ) -> str:
"""simple docstring"""
return y**2 * y**4
print(differentiate(f, 9, 2))
| 59 |
import argparse
import os
import pickle
import sys
import torch
from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl
from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils
from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
logging.set_verbosity_info()
# We do this to be able to load python 2 datasets pickles
# See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918
__A = data_utils.TransfoXLTokenizer
__A = data_utils.TransfoXLCorpus
__A = data_utils
__A = data_utils
def lowerCAmelCase_ ( __a , __a , __a , __a ) -> List[str]:
"""simple docstring"""
if transfo_xl_dataset_file:
# Convert a pre-processed corpus (see original TensorFlow repo)
with open(__a , "rb" ) as fp:
lowerCamelCase__: Optional[Any] =pickle.load(__a , encoding="latin1" )
# Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term)
lowerCamelCase__: Union[str, Any] =pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["pretrained_vocab_file"]
print(F"""Save vocabulary to {pytorch_vocab_dump_path}""" )
lowerCamelCase__: Any =corpus.vocab.__dict__
torch.save(__a , __a )
lowerCamelCase__: Dict =corpus.__dict__
corpus_dict_no_vocab.pop("vocab" , __a )
lowerCamelCase__: List[str] =pytorch_dump_folder_path + "/" + CORPUS_NAME
print(F"""Save dataset to {pytorch_dataset_dump_path}""" )
torch.save(__a , __a )
if tf_checkpoint_path:
# Convert a pre-trained TensorFlow model
lowerCamelCase__: Optional[Any] =os.path.abspath(__a )
lowerCamelCase__: Dict =os.path.abspath(__a )
print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" )
# Initialise PyTorch model
if transfo_xl_config_file == "":
lowerCamelCase__: int =TransfoXLConfig()
else:
lowerCamelCase__: Any =TransfoXLConfig.from_json_file(__a )
print(F"""Building PyTorch model from configuration: {config}""" )
lowerCamelCase__: List[Any] =TransfoXLLMHeadModel(__a )
lowerCamelCase__: List[str] =load_tf_weights_in_transfo_xl(__a , __a , __a )
# Save pytorch-model
lowerCamelCase__: List[str] =os.path.join(__a , __a )
lowerCamelCase__: Tuple =os.path.join(__a , __a )
print(F"""Save PyTorch model to {os.path.abspath(__a )}""" )
torch.save(model.state_dict() , __a )
print(F"""Save configuration file to {os.path.abspath(__a )}""" )
with open(__a , "w" , encoding="utf-8" ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
parser.add_argument(
"--pytorch_dump_folder_path",
default=None,
type=str,
required=True,
help="Path to the folder to store the PyTorch model or dataset/vocab.",
)
parser.add_argument(
"--tf_checkpoint_path",
default="",
type=str,
help="An optional path to a TensorFlow checkpoint path to be converted.",
)
parser.add_argument(
"--transfo_xl_config_file",
default="",
type=str,
help=(
"An optional config json file corresponding to the pre-trained BERT model. \n"
"This specifies the model architecture."
),
)
parser.add_argument(
"--transfo_xl_dataset_file",
default="",
type=str,
help="An optional dataset file to be converted in a vocabulary.",
)
__A = parser.parse_args()
convert_transfo_xl_checkpoint_to_pytorch(
args.tf_checkpoint_path,
args.transfo_xl_config_file,
args.pytorch_dump_folder_path,
args.transfo_xl_dataset_file,
)
| 59 | 1 |
def lowerCAmelCase_ ( __a = 50000000 ) -> int:
"""simple docstring"""
lowerCamelCase__: Any =set()
lowerCamelCase__: int =int((limit - 24) ** (1 / 2) )
lowerCamelCase__: Tuple =set(range(3 , prime_square_limit + 1 , 2 ) )
primes.add(2 )
for p in range(3 , prime_square_limit + 1 , 2 ):
if p not in primes:
continue
primes.difference_update(set(range(p * p , prime_square_limit + 1 , __a ) ) )
for primea in primes:
lowerCamelCase__: Optional[int] =primea * primea
for primea in primes:
lowerCamelCase__: List[str] =primea * primea * primea
if square + cube >= limit - 16:
break
for primea in primes:
lowerCamelCase__: int =primea * primea * primea * primea
lowerCamelCase__: Optional[Any] =square + cube + tetr
if total >= limit:
break
ret.add(__a )
return len(__a )
if __name__ == "__main__":
print(f'{solution() = }')
| 59 |
from collections import UserDict
from typing import List, Union
from ..utils import (
add_end_docstrings,
is_tf_available,
is_torch_available,
is_vision_available,
logging,
requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_vision_available():
from PIL import Image
from ..image_utils import load_image
if is_torch_available():
from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
if is_tf_available():
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
from ..tf_utils import stable_softmax
__A = logging.get_logger(__name__)
@add_end_docstrings(__SCREAMING_SNAKE_CASE )
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__(self : Optional[int] , **UpperCAmelCase_ : List[Any]) ->List[str]:
'''simple docstring'''
super().__init__(**UpperCAmelCase_)
requires_backends(self , "vision")
self.check_model_type(
TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
if self.framework == "tf"
else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING)
def __call__(self : List[str] , UpperCAmelCase_ : Union[str, List[str], "Image", List["Image"]] , **UpperCAmelCase_ : List[Any]) ->Tuple:
'''simple docstring'''
return super().__call__(UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[Any] , **UpperCAmelCase_ : Optional[int]) ->Any:
'''simple docstring'''
lowerCamelCase__: Optional[int] ={}
if "candidate_labels" in kwargs:
lowerCamelCase__: Tuple =kwargs["candidate_labels"]
if "hypothesis_template" in kwargs:
lowerCamelCase__: Tuple =kwargs["hypothesis_template"]
return preprocess_params, {}, {}
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Optional[Any]="This is a photo of {}.") ->str:
'''simple docstring'''
lowerCamelCase__: int =load_image(UpperCAmelCase_)
lowerCamelCase__: Any =self.image_processor(images=[image] , return_tensors=self.framework)
lowerCamelCase__: Any =candidate_labels
lowerCamelCase__: List[str] =[hypothesis_template.format(UpperCAmelCase_) for x in candidate_labels]
lowerCamelCase__: int =self.tokenizer(UpperCAmelCase_ , return_tensors=self.framework , padding=UpperCAmelCase_)
lowerCamelCase__: str =[text_inputs]
return inputs
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Any) ->Tuple:
'''simple docstring'''
lowerCamelCase__: int =model_inputs.pop("candidate_labels")
lowerCamelCase__: List[str] =model_inputs.pop("text_inputs")
if isinstance(text_inputs[0] , UpperCAmelCase_):
lowerCamelCase__: List[Any] =text_inputs[0]
else:
# Batching case.
lowerCamelCase__: List[Any] =text_inputs[0][0]
lowerCamelCase__: List[str] =self.model(**UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: str ={
"candidate_labels": candidate_labels,
"logits": outputs.logits_per_image,
}
return model_outputs
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Union[str, Any]) ->int:
'''simple docstring'''
lowerCamelCase__: List[Any] =model_outputs.pop("candidate_labels")
lowerCamelCase__: Optional[int] =model_outputs["logits"][0]
if self.framework == "pt":
lowerCamelCase__: Optional[Any] =logits.softmax(dim=-1).squeeze(-1)
lowerCamelCase__: Optional[Any] =probs.tolist()
if not isinstance(UpperCAmelCase_ , UpperCAmelCase_):
lowerCamelCase__: Optional[int] =[scores]
elif self.framework == "tf":
lowerCamelCase__: List[str] =stable_softmax(UpperCAmelCase_ , axis=-1)
lowerCamelCase__: Optional[int] =probs.numpy().tolist()
else:
raise ValueError(F"""Unsupported framework: {self.framework}""")
lowerCamelCase__: Optional[int] =[
{"score": score, "label": candidate_label}
for score, candidate_label in sorted(zip(UpperCAmelCase_ , UpperCAmelCase_) , key=lambda UpperCAmelCase_: -x[0])
]
return result
| 59 | 1 |
import datetime
import platform
import subprocess
from typing import Optional, Tuple, Union
import numpy as np
def lowerCAmelCase_ ( __a , __a ) -> np.array:
"""simple docstring"""
lowerCamelCase__: List[str] =F"""{sampling_rate}"""
lowerCamelCase__: Any ="1"
lowerCamelCase__: Optional[int] ="f32le"
lowerCamelCase__: Optional[int] =[
"ffmpeg",
"-i",
"pipe:0",
"-ac",
ac,
"-ar",
ar,
"-f",
format_for_conversion,
"-hide_banner",
"-loglevel",
"quiet",
"pipe:1",
]
try:
with subprocess.Popen(__a , stdin=subprocess.PIPE , stdout=subprocess.PIPE ) as ffmpeg_process:
lowerCamelCase__: Optional[Any] =ffmpeg_process.communicate(__a )
except FileNotFoundError as error:
raise ValueError("ffmpeg was not found but is required to load audio files from filename" ) from error
lowerCamelCase__: int =output_stream[0]
lowerCamelCase__: List[Any] =np.frombuffer(__a , np.floataa )
if audio.shape[0] == 0:
raise ValueError("Malformed soundfile" )
return audio
def lowerCAmelCase_ ( __a , __a , __a = "f32le" , ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase__: Any =F"""{sampling_rate}"""
lowerCamelCase__: Dict ="1"
if format_for_conversion == "s16le":
lowerCamelCase__: Tuple =2
elif format_for_conversion == "f32le":
lowerCamelCase__: List[Any] =4
else:
raise ValueError(F"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`""" )
lowerCamelCase__: List[Any] =platform.system()
if system == "Linux":
lowerCamelCase__: Dict ="alsa"
lowerCamelCase__: Any ="default"
elif system == "Darwin":
lowerCamelCase__: Optional[Any] ="avfoundation"
lowerCamelCase__: Optional[Any] =":0"
elif system == "Windows":
lowerCamelCase__: str ="dshow"
lowerCamelCase__: str ="default"
lowerCamelCase__: Any =[
"ffmpeg",
"-f",
format_,
"-i",
input_,
"-ac",
ac,
"-ar",
ar,
"-f",
format_for_conversion,
"-fflags",
"nobuffer",
"-hide_banner",
"-loglevel",
"quiet",
"pipe:1",
]
lowerCamelCase__: int =int(round(sampling_rate * chunk_length_s ) ) * size_of_sample
lowerCamelCase__: Optional[Any] =_ffmpeg_stream(__a , __a )
for item in iterator:
yield item
def lowerCAmelCase_ ( __a , __a , __a = None , __a = None , __a = "f32le" , ) -> Tuple:
"""simple docstring"""
if stream_chunk_s is not None:
lowerCamelCase__: int =stream_chunk_s
else:
lowerCamelCase__: int =chunk_length_s
lowerCamelCase__: Dict =ffmpeg_microphone(__a , __a , format_for_conversion=__a )
if format_for_conversion == "s16le":
lowerCamelCase__: List[Any] =np.intaa
lowerCamelCase__: Optional[Any] =2
elif format_for_conversion == "f32le":
lowerCamelCase__: List[str] =np.floataa
lowerCamelCase__: Dict =4
else:
raise ValueError(F"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`""" )
if stride_length_s is None:
lowerCamelCase__: str =chunk_length_s / 6
lowerCamelCase__: str =int(round(sampling_rate * chunk_length_s ) ) * size_of_sample
if isinstance(__a , (int, float) ):
lowerCamelCase__: List[str] =[stride_length_s, stride_length_s]
lowerCamelCase__: Dict =int(round(sampling_rate * stride_length_s[0] ) ) * size_of_sample
lowerCamelCase__: Optional[Any] =int(round(sampling_rate * stride_length_s[1] ) ) * size_of_sample
lowerCamelCase__: Optional[Any] =datetime.datetime.now()
lowerCamelCase__: Tuple =datetime.timedelta(seconds=__a )
for item in chunk_bytes_iter(__a , __a , stride=(stride_left, stride_right) , stream=__a ):
# Put everything back in numpy scale
lowerCamelCase__: str =np.frombuffer(item["raw"] , dtype=__a )
lowerCamelCase__: Tuple =(
item["stride"][0] // size_of_sample,
item["stride"][1] // size_of_sample,
)
lowerCamelCase__: Optional[Any] =sampling_rate
audio_time += delta
if datetime.datetime.now() > audio_time + 10 * delta:
# We're late !! SKIP
continue
yield item
def lowerCAmelCase_ ( __a , __a , __a , __a = False ) -> Union[str, Any]:
"""simple docstring"""
lowerCamelCase__: Union[str, Any] =b""
lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =stride
if stride_left + stride_right >= chunk_len:
raise ValueError(
F"""Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}""" )
lowerCamelCase__: List[Any] =0
for raw in iterator:
acc += raw
if stream and len(__a ) < chunk_len:
lowerCamelCase__: List[str] =(_stride_left, 0)
yield {"raw": acc[:chunk_len], "stride": stride, "partial": True}
else:
while len(__a ) >= chunk_len:
# We are flushing the accumulator
lowerCamelCase__: Optional[int] =(_stride_left, stride_right)
lowerCamelCase__: Any ={"raw": acc[:chunk_len], "stride": stride}
if stream:
lowerCamelCase__: List[str] =False
yield item
lowerCamelCase__: Dict =stride_left
lowerCamelCase__: str =acc[chunk_len - stride_left - stride_right :]
# Last chunk
if len(__a ) > stride_left:
lowerCamelCase__: Tuple ={"raw": acc, "stride": (_stride_left, 0)}
if stream:
lowerCamelCase__: Any =False
yield item
def lowerCAmelCase_ ( __a , __a ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase__: str =2**24 # 16Mo
try:
with subprocess.Popen(__a , stdout=subprocess.PIPE , bufsize=__a ) as ffmpeg_process:
while True:
lowerCamelCase__: Optional[Any] =ffmpeg_process.stdout.read(__a )
if raw == b"":
break
yield raw
except FileNotFoundError as error:
raise ValueError("ffmpeg was not found but is required to stream audio files from filename" ) from error
| 59 |
import json
import os
from dataclasses import dataclass
from functools import partial
from typing import Callable
import flax.linen as nn
import jax
import jax.numpy as jnp
import joblib
import optax
import wandb
from flax import jax_utils, struct, traverse_util
from flax.serialization import from_bytes, to_bytes
from flax.training import train_state
from flax.training.common_utils import shard
from tqdm.auto import tqdm
from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering
from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = 42
lowercase_ = jnp.floataa
lowercase_ = True
def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]:
'''simple docstring'''
super().setup()
lowerCamelCase__: int =nn.Dense(5 , dtype=self.dtype)
def __call__(self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Any) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =super().__call__(*UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: int =self.cls(outputs[2])
return outputs[:2] + (cls_out,)
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = FlaxBigBirdForNaturalQuestionsModule
def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a ) -> Tuple:
"""simple docstring"""
def cross_entropy(__a , __a , __a=None ):
lowerCamelCase__: Tuple =logits.shape[-1]
lowerCamelCase__: Tuple =(labels[..., None] == jnp.arange(__a )[None]).astype("f4" )
lowerCamelCase__: str =jax.nn.log_softmax(__a , axis=-1 )
lowerCamelCase__: Optional[Any] =-jnp.sum(labels * logits , axis=-1 )
if reduction is not None:
lowerCamelCase__: Optional[Any] =reduction(__a )
return loss
lowerCamelCase__: str =partial(__a , reduction=jnp.mean )
lowerCamelCase__: str =cross_entropy(__a , __a )
lowerCamelCase__: Optional[int] =cross_entropy(__a , __a )
lowerCamelCase__: Optional[Any] =cross_entropy(__a , __a )
return (start_loss + end_loss + pooled_loss) / 3
@dataclass
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
lowercase_ = "google/bigbird-roberta-base"
lowercase_ = 3000
lowercase_ = 1_0500
lowercase_ = 128
lowercase_ = 3
lowercase_ = 1
lowercase_ = 5
# tx_args
lowercase_ = 3E-5
lowercase_ = 0.0
lowercase_ = 2_0000
lowercase_ = 0.0095
lowercase_ = "bigbird-roberta-natural-questions"
lowercase_ = "training-expt"
lowercase_ = "data/nq-training.jsonl"
lowercase_ = "data/nq-validation.jsonl"
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[str]:
'''simple docstring'''
os.makedirs(self.base_dir , exist_ok=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =os.path.join(self.base_dir , self.save_dir)
lowerCamelCase__: List[str] =self.batch_size_per_device * jax.device_count()
@dataclass
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
lowercase_ = 42
lowercase_ = 4096 # no dynamic padding on TPUs
def __call__(self : List[Any] , UpperCAmelCase_ : Optional[Any]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =self.collate_fn(UpperCAmelCase_)
lowerCamelCase__: List[Any] =jax.tree_util.tree_map(UpperCAmelCase_ , UpperCAmelCase_)
return batch
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List[str]) ->List[Any]:
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: List[Any] =self.fetch_inputs(features["input_ids"])
lowerCamelCase__: Union[str, Any] ={
"input_ids": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa),
"attention_mask": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa),
"start_labels": jnp.array(features["start_token"] , dtype=jnp.intaa),
"end_labels": jnp.array(features["end_token"] , dtype=jnp.intaa),
"pooled_labels": jnp.array(features["category"] , dtype=jnp.intaa),
}
return batch
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : list) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Tuple =[self._fetch_inputs(UpperCAmelCase_) for ids in input_ids]
return zip(*UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : list) ->Any:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =[1 for _ in range(len(UpperCAmelCase_))]
while len(UpperCAmelCase_) < self.max_length:
input_ids.append(self.pad_id)
attention_mask.append(0)
return input_ids, attention_mask
def lowerCAmelCase_ ( __a , __a , __a=None ) -> str:
"""simple docstring"""
if seed is not None:
lowerCamelCase__: Any =dataset.shuffle(seed=__a )
for i in range(len(__a ) // batch_size ):
lowerCamelCase__: Any =dataset[i * batch_size : (i + 1) * batch_size]
yield dict(__a )
@partial(jax.pmap , axis_name="batch" )
def lowerCAmelCase_ ( __a , __a , **__a ) -> List[str]:
"""simple docstring"""
def loss_fn(__a ):
lowerCamelCase__: Optional[int] =model_inputs.pop("start_labels" )
lowerCamelCase__: int =model_inputs.pop("end_labels" )
lowerCamelCase__: List[str] =model_inputs.pop("pooled_labels" )
lowerCamelCase__: Optional[int] =state.apply_fn(**__a , params=__a , dropout_rng=__a , train=__a )
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[Any] =outputs
return state.loss_fn(
__a , __a , __a , __a , __a , __a , )
lowerCamelCase__ , lowerCamelCase__: int =jax.random.split(__a )
lowerCamelCase__: Optional[Any] =jax.value_and_grad(__a )
lowerCamelCase__ , lowerCamelCase__: List[str] =grad_fn(state.params )
lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" )
lowerCamelCase__: List[str] =jax.lax.pmean(__a , "batch" )
lowerCamelCase__: List[str] =state.apply_gradients(grads=__a )
return state, metrics, new_drp_rng
@partial(jax.pmap , axis_name="batch" )
def lowerCAmelCase_ ( __a , **__a ) -> List[Any]:
"""simple docstring"""
lowerCamelCase__: int =model_inputs.pop("start_labels" )
lowerCamelCase__: List[str] =model_inputs.pop("end_labels" )
lowerCamelCase__: int =model_inputs.pop("pooled_labels" )
lowerCamelCase__: Optional[Any] =state.apply_fn(**__a , params=state.params , train=__a )
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[str] =outputs
lowerCamelCase__: Optional[int] =state.loss_fn(__a , __a , __a , __a , __a , __a )
lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" )
return metrics
class _SCREAMING_SNAKE_CASE ( train_state.TrainState ):
'''simple docstring'''
lowercase_ = struct.field(pytree_node=__SCREAMING_SNAKE_CASE )
@dataclass
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = None
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int=None) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Dict =model.params
lowerCamelCase__: Tuple =TrainState.create(
apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , loss_fn=UpperCAmelCase_ , )
if ckpt_dir is not None:
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =restore_checkpoint(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Tuple ={
"lr": args.lr,
"init_lr": args.init_lr,
"warmup_steps": args.warmup_steps,
"num_train_steps": num_train_steps,
"weight_decay": args.weight_decay,
}
lowerCamelCase__ , lowerCamelCase__: List[Any] =build_tx(**UpperCAmelCase_)
lowerCamelCase__: str =train_state.TrainState(
step=UpperCAmelCase_ , apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , opt_state=UpperCAmelCase_ , )
lowerCamelCase__: Tuple =args
lowerCamelCase__: Tuple =data_collator
lowerCamelCase__: str =lr
lowerCamelCase__: Dict =params
lowerCamelCase__: List[str] =jax_utils.replicate(UpperCAmelCase_)
return state
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Tuple =self.args
lowerCamelCase__: Any =len(UpperCAmelCase_) // args.batch_size
lowerCamelCase__: List[str] =jax.random.PRNGKey(0)
lowerCamelCase__: Optional[Any] =jax.random.split(UpperCAmelCase_ , jax.device_count())
for epoch in range(args.max_epochs):
lowerCamelCase__: Union[str, Any] =jnp.array(0 , dtype=jnp.floataa)
lowerCamelCase__: str =get_batched_dataset(UpperCAmelCase_ , args.batch_size , seed=UpperCAmelCase_)
lowerCamelCase__: Dict =0
for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc=F"""Running EPOCH-{epoch}"""):
lowerCamelCase__: List[str] =self.data_collator(UpperCAmelCase_)
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.train_step_fn(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_)
running_loss += jax_utils.unreplicate(metrics["loss"])
i += 1
if i % args.logging_steps == 0:
lowerCamelCase__: Optional[int] =jax_utils.unreplicate(state.step)
lowerCamelCase__: List[Any] =running_loss.item() / i
lowerCamelCase__: Tuple =self.scheduler_fn(state_step - 1)
lowerCamelCase__: Union[str, Any] =self.evaluate(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Dict ={
"step": state_step.item(),
"eval_loss": eval_loss.item(),
"tr_loss": tr_loss,
"lr": lr.item(),
}
tqdm.write(str(UpperCAmelCase_))
self.logger.log(UpperCAmelCase_ , commit=UpperCAmelCase_)
if i % args.save_steps == 0:
self.save_checkpoint(args.save_dir + F"""-e{epoch}-s{i}""" , state=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str) ->Any:
'''simple docstring'''
lowerCamelCase__: List[Any] =get_batched_dataset(UpperCAmelCase_ , self.args.batch_size)
lowerCamelCase__: List[str] =len(UpperCAmelCase_) // self.args.batch_size
lowerCamelCase__: str =jnp.array(0 , dtype=jnp.floataa)
lowerCamelCase__: Optional[Any] =0
for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc="Evaluating ... "):
lowerCamelCase__: int =self.data_collator(UpperCAmelCase_)
lowerCamelCase__: str =self.val_step_fn(UpperCAmelCase_ , **UpperCAmelCase_)
running_loss += jax_utils.unreplicate(metrics["loss"])
i += 1
return running_loss / i
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int]) ->int:
'''simple docstring'''
lowerCamelCase__: Any =jax_utils.unreplicate(UpperCAmelCase_)
print(F"""SAVING CHECKPOINT IN {save_dir}""" , end=" ... ")
self.model_save_fn(UpperCAmelCase_ , params=state.params)
with open(os.path.join(UpperCAmelCase_ , "opt_state.msgpack") , "wb") as f:
f.write(to_bytes(state.opt_state))
joblib.dump(self.args , os.path.join(UpperCAmelCase_ , "args.joblib"))
joblib.dump(self.data_collator , os.path.join(UpperCAmelCase_ , "data_collator.joblib"))
with open(os.path.join(UpperCAmelCase_ , "training_state.json") , "w") as f:
json.dump({"step": state.step.item()} , UpperCAmelCase_)
print("DONE")
def lowerCAmelCase_ ( __a , __a ) -> str:
"""simple docstring"""
print(F"""RESTORING CHECKPOINT FROM {save_dir}""" , end=" ... " )
with open(os.path.join(__a , "flax_model.msgpack" ) , "rb" ) as f:
lowerCamelCase__: Tuple =from_bytes(state.params , f.read() )
with open(os.path.join(__a , "opt_state.msgpack" ) , "rb" ) as f:
lowerCamelCase__: Optional[int] =from_bytes(state.opt_state , f.read() )
lowerCamelCase__: Any =joblib.load(os.path.join(__a , "args.joblib" ) )
lowerCamelCase__: Union[str, Any] =joblib.load(os.path.join(__a , "data_collator.joblib" ) )
with open(os.path.join(__a , "training_state.json" ) , "r" ) as f:
lowerCamelCase__: Optional[Any] =json.load(__a )
lowerCamelCase__: Any =training_state["step"]
print("DONE" )
return params, opt_state, step, args, data_collator
def lowerCAmelCase_ ( __a , __a , __a , __a ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase__: int =num_train_steps - warmup_steps
lowerCamelCase__: str =optax.linear_schedule(init_value=__a , end_value=__a , transition_steps=__a )
lowerCamelCase__: Optional[Any] =optax.linear_schedule(init_value=__a , end_value=1e-7 , transition_steps=__a )
lowerCamelCase__: List[Any] =optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] )
return lr
def lowerCAmelCase_ ( __a , __a , __a , __a , __a ) -> str:
"""simple docstring"""
def weight_decay_mask(__a ):
lowerCamelCase__: List[str] =traverse_util.flatten_dict(__a )
lowerCamelCase__: List[str] ={k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()}
return traverse_util.unflatten_dict(__a )
lowerCamelCase__: Optional[Any] =scheduler_fn(__a , __a , __a , __a )
lowerCamelCase__: Tuple =optax.adamw(learning_rate=__a , weight_decay=__a , mask=__a )
return tx, lr
| 59 | 1 |
from typing import TYPE_CHECKING
# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__A = {
"configuration_informer": [
"INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP",
"InformerConfig",
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
"INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
"InformerForPrediction",
"InformerModel",
"InformerPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_informer import (
INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
InformerForPrediction,
InformerModel,
InformerPreTrainedModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 59 |
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = ["image_processor", "tokenizer"]
lowercase_ = "ChineseCLIPImageProcessor"
lowercase_ = ("BertTokenizer", "BertTokenizerFast")
def __init__(self : Any , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Union[str, Any]=None , **UpperCAmelCase_ : str) ->Dict:
'''simple docstring'''
lowerCamelCase__: str =None
if "feature_extractor" in kwargs:
warnings.warn(
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
" instead." , UpperCAmelCase_ , )
lowerCamelCase__: Tuple =kwargs.pop("feature_extractor")
lowerCamelCase__: Optional[int] =image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError("You need to specify an `image_processor`.")
if tokenizer is None:
raise ValueError("You need to specify a `tokenizer`.")
super().__init__(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Optional[int] =self.image_processor
def __call__(self : int , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[int]:
'''simple docstring'''
if text is None and images is None:
raise ValueError("You have to specify either text or images. Both cannot be none.")
if text is not None:
lowerCamelCase__: Dict =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if images is not None:
lowerCamelCase__: List[str] =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if text is not None and images is not None:
lowerCamelCase__: Union[str, Any] =image_features.pixel_values
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int) ->str:
'''simple docstring'''
return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any]) ->Dict:
'''simple docstring'''
return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_)
@property
def SCREAMING_SNAKE_CASE_ (self : int) ->List[str]:
'''simple docstring'''
lowerCamelCase__: str =self.tokenizer.model_input_names
lowerCamelCase__: Union[str, Any] =self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
@property
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str:
'''simple docstring'''
warnings.warn(
"`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , UpperCAmelCase_ , )
return self.image_processor_class
| 59 | 1 |
from __future__ import annotations
import requests
__A = set(
"approved_at_utc approved_by author_flair_background_color\nauthor_flair_css_class author_flair_richtext author_flair_template_id author_fullname\nauthor_premium can_mod_post category clicked content_categories created_utc downs\nedited gilded gildings hidden hide_score is_created_from_ads_ui is_meta\nis_original_content is_reddit_media_domain is_video link_flair_css_class\nlink_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title\nname permalink pwls quarantine saved score secure_media secure_media_embed selftext\nsubreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type\ntotal_awards_received ups upvote_ratio url user_reports".split()
)
def lowerCAmelCase_ ( __a , __a = 1 , __a = "new" , __a = None ) -> dict:
"""simple docstring"""
lowerCamelCase__: Optional[int] =wanted_data or []
if invalid_search_terms := ", ".join(sorted(set(__a ) - valid_terms ) ):
lowerCamelCase__: int =F"""Invalid search term: {invalid_search_terms}"""
raise ValueError(__a )
lowerCamelCase__: List[str] =requests.get(
F"""https://reddit.com/r/{subreddit}/{age}.json?limit={limit}""" , headers={"User-agent": "A random string"} , )
if response.status_code == 429:
raise requests.HTTPError
lowerCamelCase__: Tuple =response.json()
if not wanted_data:
return {id_: data["data"]["children"][id_] for id_ in range(__a )}
lowerCamelCase__: Dict ={}
for id_ in range(__a ):
lowerCamelCase__: Dict ={
item: data["data"]["children"][id_]["data"][item] for item in wanted_data
}
return data_dict
if __name__ == "__main__":
# If you get Error 429, that means you are rate limited.Try after some time
print(get_subreddit_data("learnpython", wanted_data=["title", "url", "selftext"]))
| 59 |
from math import ceil, sqrt
def lowerCAmelCase_ ( __a = 1000000 ) -> int:
"""simple docstring"""
lowerCamelCase__: Any =0
for outer_width in range(3 , (limit // 4) + 2 ):
if outer_width**2 > limit:
lowerCamelCase__: Optional[int] =max(ceil(sqrt(outer_width**2 - limit ) ) , 1 )
else:
lowerCamelCase__: Tuple =1
if (outer_width - hole_width_lower_bound) % 2:
hole_width_lower_bound += 1
answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1
return answer
if __name__ == "__main__":
print(f'{solution() = }')
| 59 | 1 |
import argparse
import torch
from transformers import BertForMaskedLM
if __name__ == "__main__":
__A = argparse.ArgumentParser(
description=(
"Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned"
" Distillation"
)
)
parser.add_argument("--model_type", default="bert", choices=["bert"])
parser.add_argument("--model_name", default="bert-base-uncased", type=str)
parser.add_argument("--dump_checkpoint", default="serialization_dir/tf_bert-base-uncased_0247911.pth", type=str)
parser.add_argument("--vocab_transform", action="store_true")
__A = parser.parse_args()
if args.model_type == "bert":
__A = BertForMaskedLM.from_pretrained(args.model_name)
__A = "bert"
else:
raise ValueError("args.model_type should be \"bert\".")
__A = model.state_dict()
__A = {}
for w in ["word_embeddings", "position_embeddings"]:
__A = state_dict[f'{prefix}.embeddings.{w}.weight']
for w in ["weight", "bias"]:
__A = state_dict[f'{prefix}.embeddings.LayerNorm.{w}']
__A = 0
for teacher_idx in [0, 2, 4, 7, 9, 11]:
for w in ["weight", "bias"]:
__A = state_dict[
f'{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}'
]
__A = state_dict[
f'{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}'
]
__A = state_dict[
f'{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}'
]
__A = state_dict[
f'{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}'
]
__A = state_dict[
f'{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}'
]
__A = state_dict[
f'{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}'
]
__A = state_dict[
f'{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}'
]
__A = state_dict[
f'{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}'
]
std_idx += 1
__A = state_dict["cls.predictions.decoder.weight"]
__A = state_dict["cls.predictions.bias"]
if args.vocab_transform:
for w in ["weight", "bias"]:
__A = state_dict[f'cls.predictions.transform.dense.{w}']
__A = state_dict[f'cls.predictions.transform.LayerNorm.{w}']
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)
| 59 |
def lowerCAmelCase_ ( __a = 50000000 ) -> int:
"""simple docstring"""
lowerCamelCase__: Any =set()
lowerCamelCase__: int =int((limit - 24) ** (1 / 2) )
lowerCamelCase__: Tuple =set(range(3 , prime_square_limit + 1 , 2 ) )
primes.add(2 )
for p in range(3 , prime_square_limit + 1 , 2 ):
if p not in primes:
continue
primes.difference_update(set(range(p * p , prime_square_limit + 1 , __a ) ) )
for primea in primes:
lowerCamelCase__: Optional[int] =primea * primea
for primea in primes:
lowerCamelCase__: List[str] =primea * primea * primea
if square + cube >= limit - 16:
break
for primea in primes:
lowerCamelCase__: int =primea * primea * primea * primea
lowerCamelCase__: Optional[Any] =square + cube + tetr
if total >= limit:
break
ret.add(__a )
return len(__a )
if __name__ == "__main__":
print(f'{solution() = }')
| 59 | 1 |
import unittest
from datasets import load_dataset
from transformers.pipelines import pipeline
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow
@is_pipeline_test
@require_torch
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
@require_torch
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->int:
'''simple docstring'''
lowerCamelCase__: int =pipeline(
task="zero-shot-audio-classification" , model="hf-internal-testing/tiny-clap-htsat-unfused")
lowerCamelCase__: Union[str, Any] =load_dataset("ashraq/esc50")
lowerCamelCase__: str =dataset["train"]["audio"][-1]["array"]
lowerCamelCase__: int =audio_classifier(UpperCAmelCase_ , candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"])
self.assertEqual(
nested_simplify(UpperCAmelCase_) , [{"score": 0.501, "label": "Sound of a dog"}, {"score": 0.499, "label": "Sound of vaccum cleaner"}] , )
@unittest.skip("No models are available in TF")
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Dict:
'''simple docstring'''
pass
@slow
@require_torch
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->int:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =pipeline(
task="zero-shot-audio-classification" , model="laion/clap-htsat-unfused" , )
# This is an audio of a dog
lowerCamelCase__: List[str] =load_dataset("ashraq/esc50")
lowerCamelCase__: str =dataset["train"]["audio"][-1]["array"]
lowerCamelCase__: Any =audio_classifier(UpperCAmelCase_ , candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"])
self.assertEqual(
nested_simplify(UpperCAmelCase_) , [
{"score": 0.999, "label": "Sound of a dog"},
{"score": 0.001, "label": "Sound of vaccum cleaner"},
] , )
lowerCamelCase__: List[Any] =audio_classifier([audio] * 5 , candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"])
self.assertEqual(
nested_simplify(UpperCAmelCase_) , [
[
{"score": 0.999, "label": "Sound of a dog"},
{"score": 0.001, "label": "Sound of vaccum cleaner"},
],
]
* 5 , )
lowerCamelCase__: List[Any] =audio_classifier(
[audio] * 5 , candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"] , batch_size=5)
self.assertEqual(
nested_simplify(UpperCAmelCase_) , [
[
{"score": 0.999, "label": "Sound of a dog"},
{"score": 0.001, "label": "Sound of vaccum cleaner"},
],
]
* 5 , )
@unittest.skip("No models are available in TF")
def SCREAMING_SNAKE_CASE_ (self : str) ->Tuple:
'''simple docstring'''
pass
| 59 |
from __future__ import annotations
from decimal import Decimal
from math import * # noqa: F403
from sympy import diff
def lowerCAmelCase_ ( __a , __a , __a = 10**-10 ) -> float:
"""simple docstring"""
lowerCamelCase__: List[str] =a
while True:
lowerCamelCase__: Optional[Any] =Decimal(__a ) - (
Decimal(eval(__a ) ) / Decimal(eval(str(diff(__a ) ) ) ) # noqa: S307
)
# This number dictates the accuracy of the answer
if abs(eval(__a ) ) < precision: # noqa: S307
return float(__a )
# Let's Execute
if __name__ == "__main__":
# Find root of trigonometric function
# Find value of pi
print(f'The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}')
# Find root of polynomial
print(f'The root of x**2 - 5*x + 2 = 0 is {newton_raphson("x**2 - 5*x + 2", 0.4)}')
# Find Square Root of 5
print(f'The root of log(x) - 1 = 0 is {newton_raphson("log(x) - 1", 2)}')
# Exponential Roots
print(f'The root of exp(x) - 1 = 0 is {newton_raphson("exp(x) - 1", 0)}')
| 59 | 1 |
def lowerCAmelCase_ ( __a ) -> Any:
"""simple docstring"""
return [
{
0: [1, 2],
1: [0, 2],
2: [0, 1, 3, 5],
3: [2, 4],
4: [3],
5: [2, 6, 8],
6: [5, 7],
7: [6, 8],
8: [5, 7],
},
{
0: [6],
1: [9],
2: [4, 5],
3: [4],
4: [2, 3],
5: [2],
6: [0, 7],
7: [6],
8: [],
9: [1],
},
{
0: [4],
1: [6],
2: [],
3: [5, 6, 7],
4: [0, 6],
5: [3, 8, 9],
6: [1, 3, 4, 7],
7: [3, 6, 8, 9],
8: [5, 7],
9: [5, 7],
},
{
0: [1, 3],
1: [0, 2, 4],
2: [1, 3, 4],
3: [0, 2, 4],
4: [1, 2, 3],
},
][index]
def lowerCAmelCase_ ( __a ) -> list[tuple[int, int]]:
"""simple docstring"""
lowerCamelCase__: Dict =0
lowerCamelCase__: Union[str, Any] =len(__a ) # No of vertices in graph
lowerCamelCase__: Optional[int] =[0] * n
lowerCamelCase__: List[str] =[False] * n
def dfs(__a , __a , __a , __a ):
lowerCamelCase__: Dict =True
lowerCamelCase__: List[Any] =id_
id_ += 1
for to in graph[at]:
if to == parent:
pass
elif not visited[to]:
dfs(__a , __a , __a , id_ )
lowerCamelCase__: str =min(low[at] , low[to] )
if id_ <= low[to]:
bridges.append((at, to) if at < to else (to, at) )
else:
# This edge is a back edge and cannot be a bridge
lowerCamelCase__: str =min(low[at] , low[to] )
lowerCamelCase__: list[tuple[int, int]] =[]
for i in range(__a ):
if not visited[i]:
dfs(__a , -1 , __a , id_ )
return bridges
if __name__ == "__main__":
import doctest
doctest.testmod()
| 59 |
import numpy as np
from numpy import ndarray
from scipy.optimize import Bounds, LinearConstraint, minimize
def lowerCAmelCase_ ( __a ) -> float:
"""simple docstring"""
return np.dot(__a , __a )
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__(self : List[str] , *,
UpperCAmelCase_ : float = np.inf , UpperCAmelCase_ : str = "linear" , UpperCAmelCase_ : float = 0.0 , ) ->None:
'''simple docstring'''
lowerCamelCase__: Dict =regularization
lowerCamelCase__: Any =gamma
if kernel == "linear":
lowerCamelCase__: Dict =self.__linear
elif kernel == "rbf":
if self.gamma == 0:
raise ValueError("rbf kernel requires gamma")
if not isinstance(self.gamma , (float, int)):
raise ValueError("gamma must be float or int")
if not self.gamma > 0:
raise ValueError("gamma must be > 0")
lowerCamelCase__: Tuple =self.__rbf
# in the future, there could be a default value like in sklearn
# sklear: def_gamma = 1/(n_features * X.var()) (wiki)
# previously it was 1/(n_features)
else:
lowerCamelCase__: Optional[Any] =F"""Unknown kernel: {kernel}"""
raise ValueError(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float:
'''simple docstring'''
return np.dot(UpperCAmelCase_ , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float:
'''simple docstring'''
return np.exp(-(self.gamma * norm_squared(vectora - vectora)))
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : list[ndarray] , UpperCAmelCase_ : ndarray) ->None:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =observations
lowerCamelCase__: Optional[int] =classes
# using Wolfe's Dual to calculate w.
# Primal problem: minimize 1/2*norm_squared(w)
# constraint: yn(w . xn + b) >= 1
#
# With l a vector
# Dual problem: maximize sum_n(ln) -
# 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm))
# constraint: self.C >= ln >= 0
# and sum_n(ln*yn) = 0
# Then we get w using w = sum_n(ln*yn*xn)
# At the end we can get b ~= mean(yn - w . xn)
#
# Since we use kernels, we only need l_star to calculate b
# and to classify observations
((lowerCamelCase__) , ): List[str] =np.shape(UpperCAmelCase_)
def to_minimize(UpperCAmelCase_ : ndarray) -> float:
lowerCamelCase__: int =0
((lowerCamelCase__) , ): Optional[Any] =np.shape(UpperCAmelCase_)
for i in range(UpperCAmelCase_):
for j in range(UpperCAmelCase_):
s += (
candidate[i]
* candidate[j]
* classes[i]
* classes[j]
* self.kernel(observations[i] , observations[j])
)
return 1 / 2 * s - sum(UpperCAmelCase_)
lowerCamelCase__: List[Any] =LinearConstraint(UpperCAmelCase_ , 0 , 0)
lowerCamelCase__: str =Bounds(0 , self.regularization)
lowerCamelCase__: Union[str, Any] =minimize(
UpperCAmelCase_ , np.ones(UpperCAmelCase_) , bounds=UpperCAmelCase_ , constraints=[ly_contraint]).x
lowerCamelCase__: str =l_star
# calculating mean offset of separation plane to points
lowerCamelCase__: Tuple =0
for i in range(UpperCAmelCase_):
for j in range(UpperCAmelCase_):
s += classes[i] - classes[i] * self.optimum[i] * self.kernel(
observations[i] , observations[j])
lowerCamelCase__: int =s / n
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : ndarray) ->int:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =sum(
self.optimum[n]
* self.classes[n]
* self.kernel(self.observations[n] , UpperCAmelCase_)
for n in range(len(self.classes)))
return 1 if s + self.offset >= 0 else -1
if __name__ == "__main__":
import doctest
doctest.testmod()
| 59 | 1 |
import argparse
from collections import defaultdict
def lowerCAmelCase_ ( __a , __a , __a , __a , __a ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase__: str =F"""{file}_{class_name}_{test_name}"""
done_test[_id] += 1
with open(__a , "r" ) as f:
lowerCamelCase__: Optional[int] =f.readlines()
lowerCamelCase__: List[str] =F"""class {class_name}("""
lowerCamelCase__: Any =F"""{4 * " "}def {test_name}("""
lowerCamelCase__: Dict =F"""{8 * " "}{correct_line.split()[0]}"""
lowerCamelCase__: Any =F"""{16 * " "}{correct_line.split()[0]}"""
lowerCamelCase__: Tuple =False
lowerCamelCase__: List[str] =False
lowerCamelCase__: List[Any] =False
lowerCamelCase__: int =False
lowerCamelCase__: Optional[int] =0
lowerCamelCase__: Optional[Any] =0
lowerCamelCase__: List[str] =[]
for line in lines:
if line.startswith(__a ):
lowerCamelCase__: List[str] =True
elif in_class and line.startswith(__a ):
lowerCamelCase__: Dict =True
elif in_class and in_func and (line.startswith(__a ) or line.startswith(__a )):
lowerCamelCase__: int =len(line.split(correct_line.split()[0] )[0] )
count += 1
if count == done_test[_id]:
lowerCamelCase__: Dict =True
if in_class and in_func and in_line:
if ")" not in line:
continue
else:
lowerCamelCase__: Union[str, Any] =True
if in_class and in_func and in_line and insert_line:
new_lines.append(F"""{spaces * " "}{correct_line}""" )
lowerCamelCase__: Any =False
else:
new_lines.append(__a )
with open(__a , "w" ) as f:
for line in new_lines:
f.write(__a )
def lowerCAmelCase_ ( __a , __a=None ) -> int:
"""simple docstring"""
if fail is not None:
with open(__a , "r" ) as f:
lowerCamelCase__: str ={l.strip() for l in f.readlines()}
else:
lowerCamelCase__: List[str] =None
with open(__a , "r" ) as f:
lowerCamelCase__: Any =f.readlines()
lowerCamelCase__: str =defaultdict(__a )
for line in correct_lines:
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[Any] =line.split(";" )
if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures:
overwrite_file(__a , __a , __a , __a , __a )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
parser.add_argument("--correct_filename", help="filename of tests with expected result")
parser.add_argument("--fail_filename", help="filename of test failures", type=str, default=None)
__A = parser.parse_args()
main(args.correct_filename, args.fail_filename)
| 59 |
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
__A = logging.getLogger(__name__)
def lowerCAmelCase_ ( __a , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = False , ) -> str:
"""simple docstring"""
lowerCamelCase__: int =bnb_quantization_config.load_in_abit
lowerCamelCase__: Any =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." )
lowerCamelCase__: List[Any] =[]
# custom device map
if isinstance(__a , __a ) and len(device_map.keys() ) > 1:
lowerCamelCase__: Optional[int] =[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:
lowerCamelCase__: Any =get_keys_to_not_convert(__a )
# add cpu modules to skip modules only for 4-bit modules
if load_in_abit:
bnb_quantization_config.skip_modules.extend(__a )
lowerCamelCase__: List[str] =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:
lowerCamelCase__: List[Any] =[]
lowerCamelCase__: int =bnb_quantization_config.keep_in_fpaa_modules
modules_to_not_convert.extend(__a )
# compatibility with peft
lowerCamelCase__: List[str] =load_in_abit
lowerCamelCase__: int =load_in_abit
lowerCamelCase__: Tuple =get_parameter_device(__a )
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." )
lowerCamelCase__: Tuple =replace_with_bnb_layers(__a , __a , modules_to_not_convert=__a )
# convert param to the right dtype
lowerCamelCase__: Dict =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:
lowerCamelCase__: str =name.replace(".weight" , "" ).replace(".bias" , "" )
lowerCamelCase__: Optional[Any] =getattr(__a , __a , __a )
if param is not None:
param.to(torch.floataa )
elif torch.is_floating_point(__a ):
param.to(__a )
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():
lowerCamelCase__: str =replace_with_bnb_layers(
__a , __a , modules_to_not_convert=__a )
lowerCamelCase__: Optional[Any] =get_quantized_model_device_map(
__a , __a , __a , max_memory=__a , no_split_module_classes=__a , )
if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
lowerCamelCase__: Any =True
lowerCamelCase__: List[str] =any(x in list(device_map.values() ) for x in ["cpu", "disk"] )
load_checkpoint_in_model(
__a , __a , __a , dtype=bnb_quantization_config.torch_dtype , offload_folder=__a , offload_state_dict=__a , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , )
return dispatch_model(__a , device_map=__a , offload_dir=__a )
def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , __a=None ) -> str:
"""simple docstring"""
if device_map is None:
if torch.cuda.is_available():
lowerCamelCase__: str ={"": 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(__a , __a ):
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'." )
lowerCamelCase__: Optional[int] ={}
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 )
} )
lowerCamelCase__: Optional[Any] ={}
lowerCamelCase__: str =special_dtypes
lowerCamelCase__: List[str] =no_split_module_classes
lowerCamelCase__: Dict =bnb_quantization_config.target_dtype
# get max_memory for each device.
if device_map != "sequential":
lowerCamelCase__: Optional[Any] =get_balanced_memory(
__a , low_zero=(device_map == "balanced_low_0") , max_memory=__a , **__a , )
lowerCamelCase__: Union[str, Any] =max_memory
lowerCamelCase__: Dict =infer_auto_device_map(__a , **__a )
if isinstance(__a , __a ):
# check if don't have any quantized module on the cpu
lowerCamelCase__: Union[str, Any] =bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules
lowerCamelCase__: List[Any] ={
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(
"\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n " )
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 lowerCAmelCase_ ( __a , __a , __a=None , __a=None ) -> Optional[Any]:
"""simple docstring"""
if modules_to_not_convert is None:
lowerCamelCase__: List[Any] =[]
lowerCamelCase__ , lowerCamelCase__: Any =_replace_with_bnb_layers(
__a , __a , __a , __a )
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 lowerCAmelCase_ ( __a , __a , __a=None , __a=None , ) -> List[Any]:
"""simple docstring"""
lowerCamelCase__: Optional[int] =False
for name, module in model.named_children():
if current_key_name is None:
lowerCamelCase__: Optional[Any] =[]
current_key_name.append(__a )
if isinstance(__a , nn.Linear ) and name not in modules_to_not_convert:
# Check if the current key is not in the `modules_to_not_convert`
lowerCamelCase__: List[str] =".".join(__a )
lowerCamelCase__: Optional[Any] =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:
lowerCamelCase__: int =False
break
if proceed:
# Load bnb module with empty weight and replace ``nn.Linear` module
if bnb_quantization_config.load_in_abit:
lowerCamelCase__: Optional[int] =bnb.nn.LinearabitLt(
module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=__a , threshold=bnb_quantization_config.llm_inta_threshold , )
elif bnb_quantization_config.load_in_abit:
lowerCamelCase__: Dict =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" )
lowerCamelCase__: Dict =module.weight.data
if module.bias is not None:
lowerCamelCase__: List[Any] =module.bias.data
bnb_module.requires_grad_(__a )
setattr(__a , __a , __a )
lowerCamelCase__: int =True
if len(list(module.children() ) ) > 0:
lowerCamelCase__ , lowerCamelCase__: List[str] =_replace_with_bnb_layers(
__a , __a , __a , __a )
lowerCamelCase__: Union[str, Any] =has_been_replaced | _has_been_replaced
# Remove the last key for recursion
current_key_name.pop(-1 )
return model, has_been_replaced
def lowerCAmelCase_ ( __a ) -> List[Any]:
"""simple docstring"""
with init_empty_weights():
lowerCamelCase__: Any =deepcopy(__a ) # this has 0 cost since it is done inside `init_empty_weights` context manager`
lowerCamelCase__: str =find_tied_parameters(__a )
# For compatibility with Accelerate < 0.18
if isinstance(__a , __a ):
lowerCamelCase__: int =sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() )
else:
lowerCamelCase__: str =sum(__a , [] )
lowerCamelCase__: str =len(__a ) > 0
# Check if it is a base model
lowerCamelCase__: Optional[Any] =False
if hasattr(__a , "base_model_prefix" ):
lowerCamelCase__: Union[str, Any] =not hasattr(__a , 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
lowerCamelCase__: Optional[int] =list(model.named_children() )
lowerCamelCase__: Optional[int] =[list_modules[-1][0]]
# add last module together with tied weights
lowerCamelCase__: Union[str, Any] =set(__a ) - set(__a )
lowerCamelCase__: List[str] =list(set(__a ) ) + list(__a )
# remove ".weight" from the keys
lowerCamelCase__: List[Any] =[".weight", ".bias"]
lowerCamelCase__: Tuple =[]
for name in list_untouched:
for name_to_remove in names_to_remove:
if name_to_remove in name:
lowerCamelCase__: Optional[Any] =name.replace(__a , "" )
filtered_module_names.append(__a )
return filtered_module_names
def lowerCAmelCase_ ( __a ) -> Tuple:
"""simple docstring"""
for m in model.modules():
if isinstance(__a , bnb.nn.Linearabit ):
return True
return False
def lowerCAmelCase_ ( __a ) -> List[str]:
"""simple docstring"""
return next(parameter.parameters() ).device
def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a , __a ) -> Any:
"""simple docstring"""
if fpaa_statistics is None:
set_module_tensor_to_device(__a , __a , 0 , dtype=__a , value=__a )
lowerCamelCase__: Dict =param_name
lowerCamelCase__: Tuple =model
if "." in tensor_name:
lowerCamelCase__: Any =tensor_name.split("." )
for split in splits[:-1]:
lowerCamelCase__: Any =getattr(__a , __a )
if new_module is None:
raise ValueError(F"""{module} has no attribute {split}.""" )
lowerCamelCase__: str =new_module
lowerCamelCase__: int =splits[-1]
# offload weights
lowerCamelCase__: str =False
offload_weight(module._parameters[tensor_name] , __a , __a , index=__a )
if hasattr(module._parameters[tensor_name] , "SCB" ):
offload_weight(
module._parameters[tensor_name].SCB , param_name.replace("weight" , "SCB" ) , __a , index=__a , )
else:
offload_weight(__a , __a , __a , index=__a )
offload_weight(__a , param_name.replace("weight" , "SCB" ) , __a , index=__a )
set_module_tensor_to_device(__a , __a , "meta" , dtype=__a , value=torch.empty(*param.size() ) )
| 59 | 1 |
from __future__ import annotations
import unittest
from transformers import is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
if is_tf_available():
import numpy as np
import tensorflow as tf
from transformers import TFCamembertModel
@require_tf
@require_sentencepiece
@require_tokenizers
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
@slow
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =TFCamembertModel.from_pretrained("jplu/tf-camembert-base")
lowerCamelCase__: Any =tf.convert_to_tensor(
[[5, 121, 11, 660, 16, 730, 25_543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !"
lowerCamelCase__: Union[str, Any] =model(UpperCAmelCase_)["last_hidden_state"]
lowerCamelCase__: Optional[int] =tf.TensorShape((1, 10, 768))
self.assertEqual(output.shape , UpperCAmelCase_)
# compare the actual values for a slice.
lowerCamelCase__: str =tf.convert_to_tensor(
[[[-0.0254, 0.0235, 0.1027], [0.0606, -0.1811, -0.0418], [-0.1561, -0.1127, 0.2687]]] , 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))
| 59 |
from __future__ import annotations
from math import pi
def lowerCAmelCase_ ( __a , __a , __a ) -> dict[str, float]:
"""simple docstring"""
if (inductance, frequency, reactance).count(0 ) != 1:
raise ValueError("One and only one argument must be 0" )
if inductance < 0:
raise ValueError("Inductance cannot be negative" )
if frequency < 0:
raise ValueError("Frequency cannot be negative" )
if reactance < 0:
raise ValueError("Inductive reactance cannot be negative" )
if inductance == 0:
return {"inductance": reactance / (2 * pi * frequency)}
elif frequency == 0:
return {"frequency": reactance / (2 * pi * inductance)}
elif reactance == 0:
return {"reactance": 2 * pi * frequency * inductance}
else:
raise ValueError("Exactly one argument must be 0" )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 59 | 1 |
import json
from typing import List, Optional, Tuple
from tokenizers import pre_tokenizers, processors
from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bart import BartTokenizer
__A = logging.get_logger(__name__)
__A = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
# See all BART models at https://huggingface.co/models?filter=bart
__A = {
"vocab_file": {
"facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json",
"facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json",
"facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json",
"facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json",
"facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json",
"yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json",
},
"merges_file": {
"facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt",
"facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt",
"facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt",
"facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt",
"facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt",
"yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt",
},
"tokenizer_file": {
"facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json",
"facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json",
"facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json",
"facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json",
"facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json",
"yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json",
},
}
__A = {
"facebook/bart-base": 1024,
"facebook/bart-large": 1024,
"facebook/bart-large-mnli": 1024,
"facebook/bart-large-cnn": 1024,
"facebook/bart-large-xsum": 1024,
"yjernite/bart_eli5": 1024,
}
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = VOCAB_FILES_NAMES
lowercase_ = PRETRAINED_VOCAB_FILES_MAP
lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowercase_ = ["input_ids", "attention_mask"]
lowercase_ = BartTokenizer
def __init__(self : List[Any] , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : List[str]="replace" , UpperCAmelCase_ : List[Any]="<s>" , UpperCAmelCase_ : Dict="</s>" , UpperCAmelCase_ : Optional[Any]="</s>" , UpperCAmelCase_ : List[str]="<s>" , UpperCAmelCase_ : List[Any]="<unk>" , UpperCAmelCase_ : Any="<pad>" , UpperCAmelCase_ : Optional[Any]="<mask>" , UpperCAmelCase_ : List[Any]=False , UpperCAmelCase_ : Union[str, Any]=True , **UpperCAmelCase_ : Dict , ) ->Optional[int]:
'''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_ , )
lowerCamelCase__: List[str] =json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
if pre_tok_state.get("add_prefix_space" , UpperCAmelCase_) != add_prefix_space:
lowerCamelCase__: Dict =getattr(UpperCAmelCase_ , pre_tok_state.pop("type"))
lowerCamelCase__: str =add_prefix_space
lowerCamelCase__: Optional[Any] =pre_tok_class(**UpperCAmelCase_)
lowerCamelCase__: str =add_prefix_space
# the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
lowerCamelCase__: Dict ="post_processor"
lowerCamelCase__: Optional[Any] =getattr(self.backend_tokenizer , UpperCAmelCase_ , UpperCAmelCase_)
if tokenizer_component_instance:
lowerCamelCase__: List[str] =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:
lowerCamelCase__: Optional[Any] =tuple(state["sep"])
if "cls" in state:
lowerCamelCase__: List[Any] =tuple(state["cls"])
lowerCamelCase__: List[Any] =False
if state.get("add_prefix_space" , UpperCAmelCase_) != add_prefix_space:
lowerCamelCase__: Optional[int] =add_prefix_space
lowerCamelCase__: Optional[int] =True
if state.get("trim_offsets" , UpperCAmelCase_) != trim_offsets:
lowerCamelCase__: Union[str, Any] =trim_offsets
lowerCamelCase__: Optional[Any] =True
if changes_to_apply:
lowerCamelCase__: Dict =getattr(UpperCAmelCase_ , state.pop("type"))
lowerCamelCase__: Any =component_class(**UpperCAmelCase_)
setattr(self.backend_tokenizer , UpperCAmelCase_ , UpperCAmelCase_)
@property
def SCREAMING_SNAKE_CASE_ (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 SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : int) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_) if isinstance(UpperCAmelCase_ , UpperCAmelCase_) else value
lowerCamelCase__: str =value
def SCREAMING_SNAKE_CASE_ (self : Tuple , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Optional[Any]) ->BatchEncoding:
'''simple docstring'''
lowerCamelCase__: Any =kwargs.get("is_split_into_words" , UpperCAmelCase_)
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(*UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : Optional[Any]) ->BatchEncoding:
'''simple docstring'''
lowerCamelCase__: str =kwargs.get("is_split_into_words" , UpperCAmelCase_)
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(*UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None) ->Tuple[str]:
'''simple docstring'''
lowerCamelCase__: Optional[int] =self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_)
return tuple(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[Any]=None) ->str:
'''simple docstring'''
lowerCamelCase__: str =[self.bos_token_id] + token_ids_a + [self.eos_token_id]
if token_ids_a is None:
return output
return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None) ->List[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =[self.sep_token_id]
lowerCamelCase__: List[str] =[self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep) * [0]
| 59 |
import pyarrow.parquet as pq
import pytest
from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config
from datasets.features.image import Image
from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size
from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases
def lowerCAmelCase_ ( __a , __a ) -> List[Any]:
"""simple docstring"""
assert isinstance(__a , __a )
assert dataset.num_rows == 4
assert dataset.num_columns == 3
assert dataset.column_names == ["col_1", "col_2", "col_3"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("keep_in_memory" , [False, True] )
def lowerCAmelCase_ ( __a , __a , __a ) -> Any:
"""simple docstring"""
lowerCamelCase__: Any =tmp_path / "cache"
lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
lowerCamelCase__: Tuple =ParquetDatasetReader(__a , cache_dir=__a , keep_in_memory=__a ).read()
_check_parquet_dataset(__a , __a )
@pytest.mark.parametrize(
"features" , [
None,
{"col_1": "string", "col_2": "int64", "col_3": "float64"},
{"col_1": "string", "col_2": "string", "col_3": "string"},
{"col_1": "int32", "col_2": "int32", "col_3": "int32"},
{"col_1": "float32", "col_2": "float32", "col_3": "float32"},
] , )
def lowerCAmelCase_ ( __a , __a , __a ) -> List[str]:
"""simple docstring"""
lowerCamelCase__: int =tmp_path / "cache"
lowerCamelCase__: Tuple ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
lowerCamelCase__: Union[str, Any] =features.copy() if features else default_expected_features
lowerCamelCase__: Optional[int] =(
Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None
)
lowerCamelCase__: int =ParquetDatasetReader(__a , features=__a , cache_dir=__a ).read()
_check_parquet_dataset(__a , __a )
@pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] )
def lowerCAmelCase_ ( __a , __a , __a ) -> Any:
"""simple docstring"""
lowerCamelCase__: Any =tmp_path / "cache"
lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
lowerCamelCase__: Optional[Any] =ParquetDatasetReader(__a , cache_dir=__a , split=__a ).read()
_check_parquet_dataset(__a , __a )
assert dataset.split == split if split else "train"
@pytest.mark.parametrize("path_type" , [str, list] )
def lowerCAmelCase_ ( __a , __a , __a ) -> int:
"""simple docstring"""
if issubclass(__a , __a ):
lowerCamelCase__: List[Any] =parquet_path
elif issubclass(__a , __a ):
lowerCamelCase__: str =[parquet_path]
lowerCamelCase__: Tuple =tmp_path / "cache"
lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read()
_check_parquet_dataset(__a , __a )
def lowerCAmelCase_ ( __a , __a , __a=("train",) ) -> Dict:
"""simple docstring"""
assert isinstance(__a , __a )
for split in splits:
lowerCamelCase__: Tuple =dataset_dict[split]
assert dataset.num_rows == 4
assert dataset.num_columns == 3
assert dataset.column_names == ["col_1", "col_2", "col_3"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("keep_in_memory" , [False, True] )
def lowerCAmelCase_ ( __a , __a , __a ) -> Any:
"""simple docstring"""
lowerCamelCase__: List[Any] =tmp_path / "cache"
lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
lowerCamelCase__: Tuple =ParquetDatasetReader(
{"train": parquet_path} , cache_dir=__a , keep_in_memory=__a ).read()
_check_parquet_datasetdict(__a , __a )
@pytest.mark.parametrize(
"features" , [
None,
{"col_1": "string", "col_2": "int64", "col_3": "float64"},
{"col_1": "string", "col_2": "string", "col_3": "string"},
{"col_1": "int32", "col_2": "int32", "col_3": "int32"},
{"col_1": "float32", "col_2": "float32", "col_3": "float32"},
] , )
def lowerCAmelCase_ ( __a , __a , __a ) -> Optional[Any]:
"""simple docstring"""
lowerCamelCase__: Tuple =tmp_path / "cache"
lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
lowerCamelCase__: List[Any] =features.copy() if features else default_expected_features
lowerCamelCase__: int =(
Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None
)
lowerCamelCase__: Optional[Any] =ParquetDatasetReader({"train": parquet_path} , features=__a , cache_dir=__a ).read()
_check_parquet_datasetdict(__a , __a )
@pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] )
def lowerCAmelCase_ ( __a , __a , __a ) -> Union[str, Any]:
"""simple docstring"""
if split:
lowerCamelCase__: Any ={split: parquet_path}
else:
lowerCamelCase__: int ="train"
lowerCamelCase__: Any ={"train": parquet_path, "test": parquet_path}
lowerCamelCase__: str =tmp_path / "cache"
lowerCamelCase__: Any ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read()
_check_parquet_datasetdict(__a , __a , splits=list(path.keys() ) )
assert all(dataset[split].split == split for split in path.keys() )
def lowerCAmelCase_ ( __a , __a ) -> int:
"""simple docstring"""
lowerCamelCase__: List[str] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" )
assert writer.write() > 0
lowerCamelCase__: List[str] =pq.ParquetFile(tmp_path / "foo.parquet" )
lowerCamelCase__: List[str] =pf.read()
assert dataset.data.table == output_table
def lowerCAmelCase_ ( __a , __a ) -> List[str]:
"""simple docstring"""
lowerCamelCase__: List[str] =str(shared_datadir / "test_image_rgb.jpg" )
lowerCamelCase__: Union[str, Any] ={"image": [image_path]}
lowerCamelCase__: Optional[Any] =Features({"image": Image()} )
lowerCamelCase__: Optional[int] =Dataset.from_dict(__a , features=__a )
lowerCamelCase__: Optional[int] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" )
assert writer.write() > 0
lowerCamelCase__: Dict =Dataset.from_parquet(str(tmp_path / "foo.parquet" ) )
assert dataset.features == reloaded_dataset.features
lowerCamelCase__: Optional[Any] =ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=__a ).read()
assert dataset.features == reloaded_iterable_dataset.features
@pytest.mark.parametrize(
"feature, expected" , [
(Features({"foo": Value("int32" )} ), None),
(Features({"image": Image(), "foo": Value("int32" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS),
(Features({"nested": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS),
] , )
def lowerCAmelCase_ ( __a , __a ) -> Optional[Any]:
"""simple docstring"""
assert get_writer_batch_size(__a ) == expected
| 59 | 1 |
import json
import os
import unittest
from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast
from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES
from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ):
'''simple docstring'''
lowercase_ = OpenAIGPTTokenizer
lowercase_ = OpenAIGPTTokenizerFast
lowercase_ = True
lowercase_ = False
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Optional[Any]:
'''simple docstring'''
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
lowerCamelCase__: int =[
"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>",
]
lowerCamelCase__: str =dict(zip(UpperCAmelCase_ , range(len(UpperCAmelCase_))))
lowerCamelCase__: Optional[Any] =["#version: 0.2", "l o", "lo w", "e r</w>", ""]
lowerCamelCase__: List[str] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"])
lowerCamelCase__: Optional[int] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"])
with open(self.vocab_file , "w") as fp:
fp.write(json.dumps(UpperCAmelCase_))
with open(self.merges_file , "w") as fp:
fp.write("\n".join(UpperCAmelCase_))
def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Optional[Any]) ->Union[str, Any]:
'''simple docstring'''
return "lower newer", "lower newer"
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->int:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =OpenAIGPTTokenizer(self.vocab_file , self.merges_file)
lowerCamelCase__: Any ="lower"
lowerCamelCase__: Union[str, Any] =["low", "er</w>"]
lowerCamelCase__: Any =tokenizer.tokenize(UpperCAmelCase_)
self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: str =tokens + ["<unk>"]
lowerCamelCase__: int =[14, 15, 20]
self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_) , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : Union[str, Any]=15) ->List[str]:
'''simple docstring'''
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""):
lowerCamelCase__: List[Any] =self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_ , **UpperCAmelCase_)
# Simple input
lowerCamelCase__: str ="This is a simple input"
lowerCamelCase__: str =["This is a simple input 1", "This is a simple input 2"]
lowerCamelCase__: Any =("This is a simple input", "This is a pair")
lowerCamelCase__: List[Any] =[
("This is a simple input 1", "This is a simple input 2"),
("This is a simple pair 1", "This is a simple pair 2"),
]
# Simple input tests
self.assertRaises(UpperCAmelCase_ , tokenizer_r.encode , UpperCAmelCase_ , max_length=UpperCAmelCase_ , padding="max_length")
# Simple input
self.assertRaises(UpperCAmelCase_ , tokenizer_r.encode_plus , UpperCAmelCase_ , max_length=UpperCAmelCase_ , padding="max_length")
# Simple input
self.assertRaises(
UpperCAmelCase_ , tokenizer_r.batch_encode_plus , UpperCAmelCase_ , max_length=UpperCAmelCase_ , padding="max_length" , )
# Pair input
self.assertRaises(UpperCAmelCase_ , tokenizer_r.encode , UpperCAmelCase_ , max_length=UpperCAmelCase_ , padding="max_length")
# Pair input
self.assertRaises(UpperCAmelCase_ , tokenizer_r.encode_plus , UpperCAmelCase_ , max_length=UpperCAmelCase_ , padding="max_length")
# Pair input
self.assertRaises(
UpperCAmelCase_ , tokenizer_r.batch_encode_plus , UpperCAmelCase_ , max_length=UpperCAmelCase_ , padding="max_length" , )
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Dict:
'''simple docstring'''
pass
@require_ftfy
@require_spacy
@require_tokenizers
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
pass
| 59 |
import unittest
from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin
__A = get_tests_dir("fixtures/test_sentencepiece.model")
@require_sentencepiece
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ):
'''simple docstring'''
lowercase_ = XLMProphetNetTokenizer
lowercase_ = False
lowercase_ = True
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[Any]:
'''simple docstring'''
super().setUp()
# We have a SentencePiece fixture for testing
lowerCamelCase__: Any =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_)
tokenizer.save_pretrained(self.tmpdirname)
def SCREAMING_SNAKE_CASE_ (self : str) ->str:
'''simple docstring'''
lowerCamelCase__: List[Any] ="[PAD]"
lowerCamelCase__: Tuple =0
self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_) , UpperCAmelCase_)
self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_) , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Dict) ->int:
'''simple docstring'''
lowerCamelCase__: List[Any] =list(self.get_tokenizer().get_vocab().keys())
self.assertEqual(vocab_keys[0] , "[PAD]")
self.assertEqual(vocab_keys[1] , "[CLS]")
self.assertEqual(vocab_keys[-1] , "j")
self.assertEqual(len(UpperCAmelCase_) , 1_012)
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]:
'''simple docstring'''
self.assertEqual(self.get_tokenizer().vocab_size , 1_012)
def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_)
lowerCamelCase__: Tuple =tokenizer.tokenize("This is a test")
self.assertListEqual(UpperCAmelCase_ , ["▁This", "▁is", "▁a", "▁t", "est"])
self.assertListEqual(
tokenizer.convert_tokens_to_ids(UpperCAmelCase_) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , )
lowerCamelCase__: Optional[Any] =tokenizer.tokenize("I was born in 92000, and this is falsé.")
self.assertListEqual(
UpperCAmelCase_ , [
SPIECE_UNDERLINE + "I",
SPIECE_UNDERLINE + "was",
SPIECE_UNDERLINE + "b",
"or",
"n",
SPIECE_UNDERLINE + "in",
SPIECE_UNDERLINE + "",
"9",
"2",
"0",
"0",
"0",
",",
SPIECE_UNDERLINE + "and",
SPIECE_UNDERLINE + "this",
SPIECE_UNDERLINE + "is",
SPIECE_UNDERLINE + "f",
"al",
"s",
"é",
".",
] , )
lowerCamelCase__: Any =tokenizer.convert_tokens_to_ids(UpperCAmelCase_)
self.assertListEqual(
UpperCAmelCase_ , [
value + tokenizer.fairseq_offset
for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4]
] , )
lowerCamelCase__: Any =tokenizer.convert_ids_to_tokens(UpperCAmelCase_)
self.assertListEqual(
UpperCAmelCase_ , [
SPIECE_UNDERLINE + "I",
SPIECE_UNDERLINE + "was",
SPIECE_UNDERLINE + "b",
"or",
"n",
SPIECE_UNDERLINE + "in",
SPIECE_UNDERLINE + "",
"[UNK]",
"2",
"0",
"0",
"0",
",",
SPIECE_UNDERLINE + "and",
SPIECE_UNDERLINE + "this",
SPIECE_UNDERLINE + "is",
SPIECE_UNDERLINE + "f",
"al",
"s",
"[UNK]",
".",
] , )
@cached_property
def SCREAMING_SNAKE_CASE_ (self : Any) ->int:
'''simple docstring'''
return XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased")
@slow
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[str]:
'''simple docstring'''
lowerCamelCase__: Optional[int] ="Hello World!"
lowerCamelCase__: Dict =[35_389, 6_672, 49, 2]
self.assertListEqual(UpperCAmelCase_ , self.big_tokenizer.encode(UpperCAmelCase_))
@slow
def SCREAMING_SNAKE_CASE_ (self : int) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__: Any ={"input_ids": [[11_073, 82_783, 18, 26, 82_783, 549, 51_540, 248, 17_209, 1_301, 217, 20, 215_186, 1_325, 147, 17_209, 1_301, 217, 20, 56_370, 53, 122_020, 20, 16_477, 27, 87_355, 4_548, 20, 4_728, 78_392, 17, 159_969, 18, 26, 24_491, 629, 15, 538, 22_704, 5_439, 15, 2_788, 24_491, 9_885, 15, 43_534, 605, 15, 814, 18_403, 33_200, 29, 15, 43_534, 24_458, 12_410, 111, 24_966, 83_669, 9_637, 144_068, 26, 850, 22_346, 27, 147, 24_966, 83_669, 83_490, 26, 39_113, 735, 27, 689, 656, 2_800, 1_339, 4_600, 53, 122_020, 115_785, 34, 816, 1_339, 46_887, 18, 147, 53_905, 1_951, 42_238, 41_170, 17_732, 834, 436, 15, 27_523, 98_733, 217, 147, 5_542, 4_981, 930, 17_347, 16, 2], [20_091, 629, 94, 82_786, 58, 490, 20, 1_528, 84, 53_905, 344, 80_592, 110_128, 18_822, 5_267, 1_306, 62, 152_537, 308, 7_997, 401, 124_427, 549, 35_442, 225, 109, 15_055, 25_748, 147, 7_119, 43_712, 34, 767, 135_366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63_784, 119_466, 17, 147_808, 88_214, 18, 656, 81, 32, 3_296, 10_280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=UpperCAmelCase_ , model_name="microsoft/xprophetnet-large-wiki100-cased" , revision="1acad1643ddd54a44df6a1b797ada8373685d90e" , )
| 59 | 1 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
__A = {
"configuration_pix2struct": [
"PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP",
"Pix2StructConfig",
"Pix2StructTextConfig",
"Pix2StructVisionConfig",
],
"processing_pix2struct": ["Pix2StructProcessor"],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = ["Pix2StructImageProcessor"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
"PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST",
"Pix2StructPreTrainedModel",
"Pix2StructForConditionalGeneration",
"Pix2StructVisionModel",
"Pix2StructTextModel",
]
if TYPE_CHECKING:
from .configuration_pixastruct import (
PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP,
PixaStructConfig,
PixaStructTextConfig,
PixaStructVisionConfig,
)
from .processing_pixastruct import PixaStructProcessor
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .image_processing_pixastruct import PixaStructImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_pixastruct import (
PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST,
PixaStructForConditionalGeneration,
PixaStructPreTrainedModel,
PixaStructTextModel,
PixaStructVisionModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 59 |
import os
import shutil
import tempfile
import unittest
import numpy as np
from transformers import AutoTokenizer, BarkProcessor
from transformers.testing_utils import require_torch, slow
@require_torch
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->str:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] ="ylacombe/bark-small"
lowerCamelCase__: Tuple =tempfile.mkdtemp()
lowerCamelCase__: Tuple ="en_speaker_1"
lowerCamelCase__: Optional[int] ="This is a test string"
lowerCamelCase__: List[str] ="speaker_embeddings_path.json"
lowerCamelCase__: int ="speaker_embeddings"
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , **UpperCAmelCase_ : Any) ->Tuple:
'''simple docstring'''
return AutoTokenizer.from_pretrained(self.checkpoint , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Union[str, Any]:
'''simple docstring'''
shutil.rmtree(self.tmpdirname)
def SCREAMING_SNAKE_CASE_ (self : int) ->Any:
'''simple docstring'''
lowerCamelCase__: List[Any] =self.get_tokenizer()
lowerCamelCase__: List[str] =BarkProcessor(tokenizer=UpperCAmelCase_)
processor.save_pretrained(self.tmpdirname)
lowerCamelCase__: Dict =BarkProcessor.from_pretrained(self.tmpdirname)
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab())
@slow
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Tuple =BarkProcessor.from_pretrained(
pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , )
processor.save_pretrained(
self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , )
lowerCamelCase__: Dict =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)")
lowerCamelCase__: Any =BarkProcessor.from_pretrained(
self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="(BOS)" , eos_token="(EOS)" , )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab())
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->int:
'''simple docstring'''
lowerCamelCase__: Any =BarkProcessor.from_pretrained(
pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , )
lowerCamelCase__: List[str] =35
lowerCamelCase__: Optional[Any] =2
lowerCamelCase__: Optional[Any] =8
lowerCamelCase__: Optional[int] ={
"semantic_prompt": np.ones(UpperCAmelCase_),
"coarse_prompt": np.ones((nb_codebooks_coarse, seq_len)),
"fine_prompt": np.ones((nb_codebooks_total, seq_len)),
}
# test providing already loaded voice_preset
lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=UpperCAmelCase_)
lowerCamelCase__: int =inputs["history_prompt"]
for key in voice_preset:
self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist())
# test loading voice preset from npz file
lowerCamelCase__: Union[str, Any] =os.path.join(self.tmpdirname , "file.npz")
np.savez(UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: Tuple =processor(text=self.input_string , voice_preset=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =inputs["history_prompt"]
for key in voice_preset:
self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist())
# test loading voice preset from the hub
lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=self.voice_preset)
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__: str =self.get_tokenizer()
lowerCamelCase__: Dict =BarkProcessor(tokenizer=UpperCAmelCase_)
lowerCamelCase__: List[Any] =processor(text=self.input_string)
lowerCamelCase__: Optional[int] =tokenizer(
self.input_string , padding="max_length" , max_length=256 , add_special_tokens=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist())
| 59 | 1 |
from __future__ import annotations
import unittest
from transformers import DistilBertConfig, is_tf_available
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers.models.distilbert.modeling_tf_distilbert import (
TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFDistilBertForMaskedLM,
TFDistilBertForMultipleChoice,
TFDistilBertForQuestionAnswering,
TFDistilBertForSequenceClassification,
TFDistilBertForTokenClassification,
TFDistilBertModel,
)
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__(self : Tuple , UpperCAmelCase_ : List[Any] , ) ->str:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =parent
lowerCamelCase__: Optional[Any] =13
lowerCamelCase__: List[str] =7
lowerCamelCase__: Any =True
lowerCamelCase__: List[Any] =True
lowerCamelCase__: Optional[int] =False
lowerCamelCase__: int =True
lowerCamelCase__: Optional[int] =99
lowerCamelCase__: Any =32
lowerCamelCase__: Tuple =2
lowerCamelCase__: Union[str, Any] =4
lowerCamelCase__: Union[str, Any] =37
lowerCamelCase__: List[Any] ="gelu"
lowerCamelCase__: Optional[int] =0.1
lowerCamelCase__: Optional[Any] =0.1
lowerCamelCase__: Optional[Any] =512
lowerCamelCase__: str =16
lowerCamelCase__: int =2
lowerCamelCase__: List[Any] =0.02
lowerCamelCase__: Optional[int] =3
lowerCamelCase__: Dict =4
lowerCamelCase__: Tuple =None
def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]:
'''simple docstring'''
lowerCamelCase__: List[str] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
lowerCamelCase__: List[Any] =None
if self.use_input_mask:
lowerCamelCase__: List[str] =random_attention_mask([self.batch_size, self.seq_length])
lowerCamelCase__: Optional[int] =None
lowerCamelCase__: Optional[int] =None
lowerCamelCase__: int =None
if self.use_labels:
lowerCamelCase__: List[str] =ids_tensor([self.batch_size] , self.type_sequence_label_size)
lowerCamelCase__: List[Any] =ids_tensor([self.batch_size, self.seq_length] , self.num_labels)
lowerCamelCase__: Optional[int] =ids_tensor([self.batch_size] , self.num_choices)
lowerCamelCase__: str =DistilBertConfig(
vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , )
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Any) ->Dict:
'''simple docstring'''
lowerCamelCase__: List[Any] =TFDistilBertModel(config=UpperCAmelCase_)
lowerCamelCase__: Optional[int] ={"input_ids": input_ids, "attention_mask": input_mask}
lowerCamelCase__: List[str] =model(UpperCAmelCase_)
lowerCamelCase__: List[Any] =[input_ids, input_mask]
lowerCamelCase__: Any =model(UpperCAmelCase_)
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_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Any) ->Tuple:
'''simple docstring'''
lowerCamelCase__: List[str] =TFDistilBertForMaskedLM(config=UpperCAmelCase_)
lowerCamelCase__: Dict ={"input_ids": input_ids, "attention_mask": input_mask}
lowerCamelCase__: List[Any] =model(UpperCAmelCase_)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size))
def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Tuple) ->Tuple:
'''simple docstring'''
lowerCamelCase__: List[str] =TFDistilBertForQuestionAnswering(config=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] ={
"input_ids": input_ids,
"attention_mask": input_mask,
}
lowerCamelCase__: int =model(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 SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Dict) ->int:
'''simple docstring'''
lowerCamelCase__: Optional[int] =self.num_labels
lowerCamelCase__: Optional[Any] =TFDistilBertForSequenceClassification(UpperCAmelCase_)
lowerCamelCase__: Optional[int] ={"input_ids": input_ids, "attention_mask": input_mask}
lowerCamelCase__: Union[str, Any] =model(UpperCAmelCase_)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels))
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int]) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__: Dict =self.num_choices
lowerCamelCase__: Any =TFDistilBertForMultipleChoice(UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =tf.tile(tf.expand_dims(UpperCAmelCase_ , 1) , (1, self.num_choices, 1))
lowerCamelCase__: Tuple =tf.tile(tf.expand_dims(UpperCAmelCase_ , 1) , (1, self.num_choices, 1))
lowerCamelCase__: Dict ={
"input_ids": multiple_choice_inputs_ids,
"attention_mask": multiple_choice_input_mask,
}
lowerCamelCase__: Tuple =model(UpperCAmelCase_)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices))
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any]) ->str:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =self.num_labels
lowerCamelCase__: List[str] =TFDistilBertForTokenClassification(UpperCAmelCase_)
lowerCamelCase__: str ={"input_ids": input_ids, "attention_mask": input_mask}
lowerCamelCase__: Optional[int] =model(UpperCAmelCase_)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels))
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->List[Any]:
'''simple docstring'''
lowerCamelCase__: List[Any] =self.prepare_config_and_inputs()
((lowerCamelCase__) , (lowerCamelCase__) , (lowerCamelCase__) , (lowerCamelCase__) , (lowerCamelCase__) , (lowerCamelCase__)): int =config_and_inputs
lowerCamelCase__: Optional[int] ={"input_ids": input_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_tf
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ):
'''simple docstring'''
lowercase_ = (
(
TFDistilBertModel,
TFDistilBertForMaskedLM,
TFDistilBertForQuestionAnswering,
TFDistilBertForSequenceClassification,
TFDistilBertForTokenClassification,
TFDistilBertForMultipleChoice,
)
if is_tf_available()
else None
)
lowercase_ = (
{
"feature-extraction": TFDistilBertModel,
"fill-mask": TFDistilBertForMaskedLM,
"question-answering": TFDistilBertForQuestionAnswering,
"text-classification": TFDistilBertForSequenceClassification,
"token-classification": TFDistilBertForTokenClassification,
"zero-shot": TFDistilBertForSequenceClassification,
}
if is_tf_available()
else {}
)
lowercase_ = False
lowercase_ = False
def SCREAMING_SNAKE_CASE_ (self : int) ->Any:
'''simple docstring'''
lowerCamelCase__: Tuple =TFDistilBertModelTester(self)
lowerCamelCase__: Dict =ConfigTester(self , config_class=UpperCAmelCase_ , dim=37)
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Tuple:
'''simple docstring'''
self.config_tester.run_common_tests()
def SCREAMING_SNAKE_CASE_ (self : Any) ->int:
'''simple docstring'''
lowerCamelCase__: Any =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_model(*UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Dict:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_masked_lm(*UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->int:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_question_answering(*UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Tuple:
'''simple docstring'''
lowerCamelCase__: List[Any] =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_sequence_classification(*UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : str) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Tuple =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_multiple_choice(*UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : str) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: int =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_token_classification(*UpperCAmelCase_)
@slow
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Dict:
'''simple docstring'''
for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]):
lowerCamelCase__: str =TFDistilBertModel.from_pretrained(UpperCAmelCase_)
self.assertIsNotNone(UpperCAmelCase_)
@require_tf
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
@slow
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Dict:
'''simple docstring'''
lowerCamelCase__: List[str] =TFDistilBertModel.from_pretrained("distilbert-base-uncased")
lowerCamelCase__: Any =tf.constant([[0, 1, 2, 3, 4, 5]])
lowerCamelCase__: Union[str, Any] =model(UpperCAmelCase_)[0]
lowerCamelCase__: Optional[int] =[1, 6, 768]
self.assertEqual(output.shape , UpperCAmelCase_)
lowerCamelCase__: List[Any] =tf.constant(
[
[
[0.1926_1885, -0.1373_2955, 0.411_9799],
[0.2215_0156, -0.0742_2661, 0.3903_7204],
[0.2275_6018, -0.089_6414, 0.370_1467],
]
])
tf.debugging.assert_near(output[:, :3, :3] , UpperCAmelCase_ , atol=1E-4)
| 59 |
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = ["image_processor", "tokenizer"]
lowercase_ = "CLIPImageProcessor"
lowercase_ = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast")
def __init__(self : List[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : List[str]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =None
if "feature_extractor" in kwargs:
warnings.warn(
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
" instead." , UpperCAmelCase_ , )
lowerCamelCase__: int =kwargs.pop("feature_extractor")
lowerCamelCase__: int =image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError("You need to specify an `image_processor`.")
if tokenizer is None:
raise ValueError("You need to specify a `tokenizer`.")
super().__init__(UpperCAmelCase_ , UpperCAmelCase_)
def __call__(self : List[Any] , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : int=None , **UpperCAmelCase_ : Any) ->Union[str, Any]:
'''simple docstring'''
if text is None and images is None:
raise ValueError("You have to specify either text or images. Both cannot be none.")
if text is not None:
lowerCamelCase__: List[Any] =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if images is not None:
lowerCamelCase__: int =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if text is not None and images is not None:
lowerCamelCase__: str =image_features.pixel_values
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[Any]) ->Dict:
'''simple docstring'''
return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Any) ->Optional[Any]:
'''simple docstring'''
return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_)
@property
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =self.tokenizer.model_input_names
lowerCamelCase__: str =self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
| 59 | 1 |
import copy
from typing import Any, Dict, List, Optional, Union
import numpy as np
import torch
from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging
__A = logging.get_logger(__name__)
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = ["input_features", "is_longer"]
def __init__(self : int , UpperCAmelCase_ : List[str]=64 , UpperCAmelCase_ : Any=48_000 , UpperCAmelCase_ : List[str]=480 , UpperCAmelCase_ : List[str]=10 , UpperCAmelCase_ : Tuple=1_024 , UpperCAmelCase_ : int=0.0 , UpperCAmelCase_ : Union[str, Any]=False , UpperCAmelCase_ : float = 0 , UpperCAmelCase_ : float = 14_000 , UpperCAmelCase_ : int = None , UpperCAmelCase_ : str = "fusion" , UpperCAmelCase_ : str = "repeatpad" , **UpperCAmelCase_ : Union[str, Any] , ) ->Union[str, Any]:
'''simple docstring'''
super().__init__(
feature_size=UpperCAmelCase_ , sampling_rate=UpperCAmelCase_ , padding_value=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , **UpperCAmelCase_ , )
lowerCamelCase__: int =top_db
lowerCamelCase__: List[Any] =truncation
lowerCamelCase__: Any =padding
lowerCamelCase__: Any =fft_window_size
lowerCamelCase__: Optional[Any] =(fft_window_size >> 1) + 1
lowerCamelCase__: Union[str, Any] =hop_length
lowerCamelCase__: Union[str, Any] =max_length_s
lowerCamelCase__: Dict =max_length_s * sampling_rate
lowerCamelCase__: int =sampling_rate
lowerCamelCase__: Any =frequency_min
lowerCamelCase__: Optional[int] =frequency_max
lowerCamelCase__: Tuple =mel_filter_bank(
num_frequency_bins=self.nb_frequency_bins , num_mel_filters=UpperCAmelCase_ , min_frequency=UpperCAmelCase_ , max_frequency=UpperCAmelCase_ , sampling_rate=UpperCAmelCase_ , norm=UpperCAmelCase_ , mel_scale="htk" , )
lowerCamelCase__: Optional[int] =mel_filter_bank(
num_frequency_bins=self.nb_frequency_bins , num_mel_filters=UpperCAmelCase_ , min_frequency=UpperCAmelCase_ , max_frequency=UpperCAmelCase_ , sampling_rate=UpperCAmelCase_ , norm="slaney" , mel_scale="slaney" , )
def SCREAMING_SNAKE_CASE_ (self : int) ->Dict[str, Any]:
'''simple docstring'''
lowerCamelCase__: int =copy.deepcopy(self.__dict__)
lowerCamelCase__: List[Any] =self.__class__.__name__
if "mel_filters" in output:
del output["mel_filters"]
if "mel_filters_slaney" in output:
del output["mel_filters_slaney"]
return output
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : np.array , UpperCAmelCase_ : Optional[np.array] = None) ->np.ndarray:
'''simple docstring'''
lowerCamelCase__: Dict =spectrogram(
UpperCAmelCase_ , window_function(self.fft_window_size , "hann") , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=UpperCAmelCase_ , log_mel="dB" , )
return log_mel_spectrogram.T
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Any , UpperCAmelCase_ : Any) ->List[str]:
'''simple docstring'''
lowerCamelCase__: List[Any] =np.array_split(list(range(0 , total_frames - chunk_frames + 1)) , 3)
if len(ranges[1]) == 0:
# if the audio is too short, we just use the first chunk
lowerCamelCase__: Optional[int] =[0]
if len(ranges[2]) == 0:
# if the audio is too short, we just use the first chunk
lowerCamelCase__: Union[str, Any] =[0]
# randomly choose index for each part
lowerCamelCase__: Any =np.random.choice(ranges[0])
lowerCamelCase__: int =np.random.choice(ranges[1])
lowerCamelCase__: Optional[int] =np.random.choice(ranges[2])
lowerCamelCase__: Optional[int] =mel[idx_front : idx_front + chunk_frames, :]
lowerCamelCase__: Any =mel[idx_middle : idx_middle + chunk_frames, :]
lowerCamelCase__: Optional[int] =mel[idx_back : idx_back + chunk_frames, :]
lowerCamelCase__: List[str] =torch.tensor(mel[None, None, :])
lowerCamelCase__: List[Any] =torch.nn.functional.interpolate(
UpperCAmelCase_ , size=[chunk_frames, 64] , mode="bilinear" , align_corners=UpperCAmelCase_)
lowerCamelCase__: Optional[int] =mel_shrink[0][0].numpy()
lowerCamelCase__: Optional[Any] =np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0)
return mel_fusion
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : np.array , UpperCAmelCase_ : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Tuple) ->np.array:
'''simple docstring'''
if waveform.shape[0] > max_length:
if truncation == "rand_trunc":
lowerCamelCase__: str =True
# random crop to max_length (for compatibility) -> this should be handled by self.pad
lowerCamelCase__: Optional[int] =len(UpperCAmelCase_) - max_length
lowerCamelCase__: int =np.random.randint(0 , overflow + 1)
lowerCamelCase__: Dict =waveform[idx : idx + max_length]
lowerCamelCase__: Dict =self._np_extract_fbank_features(UpperCAmelCase_ , self.mel_filters_slaney)[None, :]
elif truncation == "fusion":
lowerCamelCase__: List[Any] =self._np_extract_fbank_features(UpperCAmelCase_ , self.mel_filters)
lowerCamelCase__: str =max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed
lowerCamelCase__: Optional[Any] =mel.shape[0]
if chunk_frames == total_frames:
# there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length.
# In this case, we just use the whole audio.
lowerCamelCase__: Dict =np.stack([mel, mel, mel, mel] , axis=0)
lowerCamelCase__: List[Any] =False
else:
lowerCamelCase__: str =self._random_mel_fusion(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Any =True
else:
raise NotImplementedError(F"""data_truncating {truncation} not implemented""")
else:
lowerCamelCase__: List[str] =False
# only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding
if waveform.shape[0] < max_length:
if padding == "repeat":
lowerCamelCase__: str =int(max_length / len(UpperCAmelCase_))
lowerCamelCase__: List[Any] =np.stack(np.tile(UpperCAmelCase_ , n_repeat + 1))[:max_length]
if padding == "repeatpad":
lowerCamelCase__: Tuple =int(max_length / len(UpperCAmelCase_))
lowerCamelCase__: List[Any] =np.stack(np.tile(UpperCAmelCase_ , UpperCAmelCase_))
lowerCamelCase__: Tuple =np.pad(UpperCAmelCase_ , (0, max_length - waveform.shape[0]) , mode="constant" , constant_values=0)
if truncation == "fusion":
lowerCamelCase__: List[str] =self._np_extract_fbank_features(UpperCAmelCase_ , self.mel_filters)
lowerCamelCase__: List[str] =np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0)
else:
lowerCamelCase__: Union[str, Any] =self._np_extract_fbank_features(UpperCAmelCase_ , self.mel_filters_slaney)[None, :]
return input_mel, longer
def __call__(self : str , UpperCAmelCase_ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , UpperCAmelCase_ : str = None , UpperCAmelCase_ : Optional[str] = None , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : Optional[Union[str, TensorType]] = None , **UpperCAmelCase_ : List[Any] , ) ->BatchFeature:
'''simple docstring'''
lowerCamelCase__: Tuple =truncation if truncation is not None else self.truncation
lowerCamelCase__: List[str] =padding if padding else self.padding
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
F"""The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a"""
F""" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input"""
F""" was sampled with {self.sampling_rate} and not {sampling_rate}.""")
else:
logger.warning(
"It is strongly recommended to pass the `sampling_rate` argument to this function. "
"Failing to do so can result in silent errors that might be hard to debug.")
lowerCamelCase__: int =isinstance(UpperCAmelCase_ , 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}""")
lowerCamelCase__: List[str] =is_batched_numpy or (
isinstance(UpperCAmelCase_ , (list, tuple)) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list)))
)
if is_batched:
lowerCamelCase__: List[str] =[np.asarray(UpperCAmelCase_ , dtype=np.floataa) for speech in raw_speech]
elif not is_batched and not isinstance(UpperCAmelCase_ , np.ndarray):
lowerCamelCase__: Optional[int] =np.asarray(UpperCAmelCase_ , dtype=np.floataa)
elif isinstance(UpperCAmelCase_ , np.ndarray) and raw_speech.dtype is np.dtype(np.floataa):
lowerCamelCase__: Optional[Any] =raw_speech.astype(np.floataa)
# always return batch
if not is_batched:
lowerCamelCase__: List[str] =[np.asarray(UpperCAmelCase_)]
# convert to mel spectrogram, truncate and pad if needed.
lowerCamelCase__: List[Any] =[
self._get_input_mel(UpperCAmelCase_ , max_length if max_length else self.nb_max_samples , UpperCAmelCase_ , UpperCAmelCase_)
for waveform in raw_speech
]
lowerCamelCase__: List[str] =[]
lowerCamelCase__: Optional[Any] =[]
for mel, longer in padded_inputs:
input_mel.append(UpperCAmelCase_)
is_longer.append(UpperCAmelCase_)
if truncation == "fusion" and sum(UpperCAmelCase_) == 0:
# if no audio is longer than 10s, then randomly select one audio to be longer
lowerCamelCase__: Any =np.random.randint(0 , len(UpperCAmelCase_))
lowerCamelCase__: str =True
if isinstance(input_mel[0] , UpperCAmelCase_):
lowerCamelCase__: Optional[Any] =[np.asarray(UpperCAmelCase_ , dtype=np.floataa) for feature in input_mel]
# is_longer is a list of bool
lowerCamelCase__: Tuple =[[longer] for longer in is_longer]
lowerCamelCase__: List[str] ={"input_features": input_mel, "is_longer": is_longer}
lowerCamelCase__: str =BatchFeature(UpperCAmelCase_)
if return_tensors is not None:
lowerCamelCase__: Any =input_features.convert_to_tensors(UpperCAmelCase_)
return input_features
| 59 |
from datetime import datetime
import matplotlib.pyplot as plt
import torch
def lowerCAmelCase_ ( __a ) -> Any:
"""simple docstring"""
for param in module.parameters():
lowerCamelCase__: Tuple =False
def lowerCAmelCase_ ( ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase__: List[str] ="cuda" if torch.cuda.is_available() else "cpu"
if torch.backends.mps.is_available() and torch.backends.mps.is_built():
lowerCamelCase__: str ="mps"
if device == "mps":
print(
"WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch"
" errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues"
" with generations." )
return device
def lowerCAmelCase_ ( __a ) -> List[str]:
"""simple docstring"""
lowerCamelCase__: Union[str, Any] =plt.imshow(__a )
fig.axes.get_xaxis().set_visible(__a )
fig.axes.get_yaxis().set_visible(__a )
plt.show()
def lowerCAmelCase_ ( ) -> Optional[Any]:
"""simple docstring"""
lowerCamelCase__: List[str] =datetime.now()
lowerCamelCase__: str =current_time.strftime("%H:%M:%S" )
return timestamp
| 59 | 1 |
import math
from numpy import inf
from scipy.integrate import quad
def lowerCAmelCase_ ( __a ) -> float:
"""simple docstring"""
if num <= 0:
raise ValueError("math domain error" )
return quad(__a , 0 , __a , args=(__a) )[0]
def lowerCAmelCase_ ( __a , __a ) -> float:
"""simple docstring"""
return math.pow(__a , z - 1 ) * math.exp(-x )
if __name__ == "__main__":
from doctest import testmod
testmod()
| 59 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
__A = {
"configuration_pix2struct": [
"PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP",
"Pix2StructConfig",
"Pix2StructTextConfig",
"Pix2StructVisionConfig",
],
"processing_pix2struct": ["Pix2StructProcessor"],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = ["Pix2StructImageProcessor"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
"PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST",
"Pix2StructPreTrainedModel",
"Pix2StructForConditionalGeneration",
"Pix2StructVisionModel",
"Pix2StructTextModel",
]
if TYPE_CHECKING:
from .configuration_pixastruct import (
PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP,
PixaStructConfig,
PixaStructTextConfig,
PixaStructVisionConfig,
)
from .processing_pixastruct import PixaStructProcessor
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .image_processing_pixastruct import PixaStructImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_pixastruct import (
PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST,
PixaStructForConditionalGeneration,
PixaStructPreTrainedModel,
PixaStructTextModel,
PixaStructVisionModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 59 | 1 |
import tempfile
import unittest
import numpy as np
from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError
from transformers import BertConfig, is_flax_available
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax
if is_flax_available():
import os
from flax.core.frozen_dict import unfreeze
from flax.traverse_util import flatten_dict
from transformers import FlaxBertModel
__A = "0.12" # assumed parallelism: 8
@require_flax
@is_staging_test
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
@classmethod
def SCREAMING_SNAKE_CASE_ (cls : str) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Optional[int] =TOKEN
HfFolder.save_token(UpperCAmelCase_)
@classmethod
def SCREAMING_SNAKE_CASE_ (cls : Optional[Any]) ->int:
'''simple docstring'''
try:
delete_repo(token=cls._token , repo_id="test-model-flax")
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id="valid_org/test-model-flax-org")
except HTTPError:
pass
def SCREAMING_SNAKE_CASE_ (self : Any) ->Tuple:
'''simple docstring'''
lowerCamelCase__: str =BertConfig(
vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37)
lowerCamelCase__: Dict =FlaxBertModel(UpperCAmelCase_)
model.push_to_hub("test-model-flax" , use_auth_token=self._token)
lowerCamelCase__: Union[str, Any] =FlaxBertModel.from_pretrained(F"""{USER}/test-model-flax""")
lowerCamelCase__: str =flatten_dict(unfreeze(model.params))
lowerCamelCase__: Union[str, Any] =flatten_dict(unfreeze(new_model.params))
for key in base_params.keys():
lowerCamelCase__: List[str] =(base_params[key] - new_params[key]).sum().item()
self.assertLessEqual(UpperCAmelCase_ , 1E-3 , msg=F"""{key} not identical""")
# Reset repo
delete_repo(token=self._token , repo_id="test-model-flax")
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
model.save_pretrained(UpperCAmelCase_ , repo_id="test-model-flax" , push_to_hub=UpperCAmelCase_ , use_auth_token=self._token)
lowerCamelCase__: Tuple =FlaxBertModel.from_pretrained(F"""{USER}/test-model-flax""")
lowerCamelCase__: Optional[int] =flatten_dict(unfreeze(model.params))
lowerCamelCase__: List[str] =flatten_dict(unfreeze(new_model.params))
for key in base_params.keys():
lowerCamelCase__: List[Any] =(base_params[key] - new_params[key]).sum().item()
self.assertLessEqual(UpperCAmelCase_ , 1E-3 , msg=F"""{key} not identical""")
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->str:
'''simple docstring'''
lowerCamelCase__: Any =BertConfig(
vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37)
lowerCamelCase__: List[str] =FlaxBertModel(UpperCAmelCase_)
model.push_to_hub("valid_org/test-model-flax-org" , use_auth_token=self._token)
lowerCamelCase__: Optional[int] =FlaxBertModel.from_pretrained("valid_org/test-model-flax-org")
lowerCamelCase__: int =flatten_dict(unfreeze(model.params))
lowerCamelCase__: Any =flatten_dict(unfreeze(new_model.params))
for key in base_params.keys():
lowerCamelCase__: List[str] =(base_params[key] - new_params[key]).sum().item()
self.assertLessEqual(UpperCAmelCase_ , 1E-3 , msg=F"""{key} not identical""")
# Reset repo
delete_repo(token=self._token , repo_id="valid_org/test-model-flax-org")
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
model.save_pretrained(
UpperCAmelCase_ , repo_id="valid_org/test-model-flax-org" , push_to_hub=UpperCAmelCase_ , use_auth_token=self._token)
lowerCamelCase__: int =FlaxBertModel.from_pretrained("valid_org/test-model-flax-org")
lowerCamelCase__: Union[str, Any] =flatten_dict(unfreeze(model.params))
lowerCamelCase__: Union[str, Any] =flatten_dict(unfreeze(new_model.params))
for key in base_params.keys():
lowerCamelCase__: Tuple =(base_params[key] - new_params[key]).sum().item()
self.assertLessEqual(UpperCAmelCase_ , 1E-3 , msg=F"""{key} not identical""")
def lowerCAmelCase_ ( __a , __a ) -> Union[str, Any]:
"""simple docstring"""
lowerCamelCase__: int =True
lowerCamelCase__: Any =flatten_dict(modela.params )
lowerCamelCase__: Any =flatten_dict(modela.params )
for key in flat_params_a.keys():
if np.sum(np.abs(flat_params_a[key] - flat_params_a[key] ) ) > 1e-4:
lowerCamelCase__: Dict =False
return models_are_equal
@require_flax
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : str) ->Any:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =BertConfig.from_pretrained("hf-internal-testing/tiny-bert-flax-only")
lowerCamelCase__: str =FlaxBertModel(UpperCAmelCase_)
lowerCamelCase__: int ="bert"
with tempfile.TemporaryDirectory() as tmp_dir:
model.save_pretrained(os.path.join(UpperCAmelCase_ , UpperCAmelCase_))
with self.assertRaises(UpperCAmelCase_):
lowerCamelCase__: Tuple =FlaxBertModel.from_pretrained(UpperCAmelCase_)
lowerCamelCase__: Optional[int] =FlaxBertModel.from_pretrained(UpperCAmelCase_ , subfolder=UpperCAmelCase_)
self.assertTrue(check_models_equal(UpperCAmelCase_ , UpperCAmelCase_))
def SCREAMING_SNAKE_CASE_ (self : Any) ->Any:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =BertConfig.from_pretrained("hf-internal-testing/tiny-bert-flax-only")
lowerCamelCase__: List[Any] =FlaxBertModel(UpperCAmelCase_)
lowerCamelCase__: int ="bert"
with tempfile.TemporaryDirectory() as tmp_dir:
model.save_pretrained(os.path.join(UpperCAmelCase_ , UpperCAmelCase_) , max_shard_size="10KB")
with self.assertRaises(UpperCAmelCase_):
lowerCamelCase__: Dict =FlaxBertModel.from_pretrained(UpperCAmelCase_)
lowerCamelCase__: str =FlaxBertModel.from_pretrained(UpperCAmelCase_ , subfolder=UpperCAmelCase_)
self.assertTrue(check_models_equal(UpperCAmelCase_ , UpperCAmelCase_))
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: str ="bert"
lowerCamelCase__: Optional[Any] ="hf-internal-testing/tiny-random-bert-subfolder"
with self.assertRaises(UpperCAmelCase_):
lowerCamelCase__: Union[str, Any] =FlaxBertModel.from_pretrained(UpperCAmelCase_)
lowerCamelCase__: Tuple =FlaxBertModel.from_pretrained(UpperCAmelCase_ , subfolder=UpperCAmelCase_)
self.assertIsNotNone(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__: List[str] ="bert"
lowerCamelCase__: Optional[int] ="hf-internal-testing/tiny-random-bert-sharded-subfolder"
with self.assertRaises(UpperCAmelCase_):
lowerCamelCase__: Dict =FlaxBertModel.from_pretrained(UpperCAmelCase_)
lowerCamelCase__: Any =FlaxBertModel.from_pretrained(UpperCAmelCase_ , subfolder=UpperCAmelCase_)
self.assertIsNotNone(UpperCAmelCase_)
| 59 |
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_distilbert import DistilBertTokenizer
__A = logging.get_logger(__name__)
__A = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
__A = {
"vocab_file": {
"distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt",
"distilbert-base-uncased-distilled-squad": (
"https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt"
),
"distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt",
"distilbert-base-cased-distilled-squad": (
"https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt"
),
"distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt",
"distilbert-base-multilingual-cased": (
"https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt"
),
},
"tokenizer_file": {
"distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json",
"distilbert-base-uncased-distilled-squad": (
"https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json"
),
"distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json",
"distilbert-base-cased-distilled-squad": (
"https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json"
),
"distilbert-base-german-cased": (
"https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json"
),
"distilbert-base-multilingual-cased": (
"https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json"
),
},
}
__A = {
"distilbert-base-uncased": 512,
"distilbert-base-uncased-distilled-squad": 512,
"distilbert-base-cased": 512,
"distilbert-base-cased-distilled-squad": 512,
"distilbert-base-german-cased": 512,
"distilbert-base-multilingual-cased": 512,
}
__A = {
"distilbert-base-uncased": {"do_lower_case": True},
"distilbert-base-uncased-distilled-squad": {"do_lower_case": True},
"distilbert-base-cased": {"do_lower_case": False},
"distilbert-base-cased-distilled-squad": {"do_lower_case": False},
"distilbert-base-german-cased": {"do_lower_case": False},
"distilbert-base-multilingual-cased": {"do_lower_case": False},
}
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = VOCAB_FILES_NAMES
lowercase_ = PRETRAINED_VOCAB_FILES_MAP
lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowercase_ = PRETRAINED_INIT_CONFIGURATION
lowercase_ = ["input_ids", "attention_mask"]
lowercase_ = DistilBertTokenizer
def __init__(self : Tuple , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[Any]="[UNK]" , UpperCAmelCase_ : Dict="[SEP]" , UpperCAmelCase_ : Dict="[PAD]" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[str]=None , **UpperCAmelCase_ : List[str] , ) ->str:
'''simple docstring'''
super().__init__(
UpperCAmelCase_ , tokenizer_file=UpperCAmelCase_ , do_lower_case=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , tokenize_chinese_chars=UpperCAmelCase_ , strip_accents=UpperCAmelCase_ , **UpperCAmelCase_ , )
lowerCamelCase__: Union[str, Any] =json.loads(self.backend_tokenizer.normalizer.__getstate__())
if (
normalizer_state.get("lowercase" , UpperCAmelCase_) != do_lower_case
or normalizer_state.get("strip_accents" , UpperCAmelCase_) != strip_accents
or normalizer_state.get("handle_chinese_chars" , UpperCAmelCase_) != tokenize_chinese_chars
):
lowerCamelCase__: List[str] =getattr(UpperCAmelCase_ , normalizer_state.pop("type"))
lowerCamelCase__: Optional[int] =do_lower_case
lowerCamelCase__: int =strip_accents
lowerCamelCase__: Any =tokenize_chinese_chars
lowerCamelCase__: Any =normalizer_class(**UpperCAmelCase_)
lowerCamelCase__: str =do_lower_case
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any]=None) ->Dict:
'''simple docstring'''
lowerCamelCase__: str =[self.cls_token_id] + token_ids_a + [self.sep_token_id]
if token_ids_a:
output += token_ids_a + [self.sep_token_id]
return output
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None) ->List[int]:
'''simple docstring'''
lowerCamelCase__: str =[self.sep_token_id]
lowerCamelCase__: str =[self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep) * [0]
return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1]
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None) ->Tuple[str]:
'''simple docstring'''
lowerCamelCase__: str =self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_)
return tuple(UpperCAmelCase_)
| 59 | 1 |
from itertools import product
from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey
from numpy import dot, exp, mgrid, pi, ravel, square, uinta, zeros
def lowerCAmelCase_ ( __a , __a ) -> Any:
"""simple docstring"""
lowerCamelCase__: Dict =k_size // 2
lowerCamelCase__ , lowerCamelCase__: Any =mgrid[0 - center : k_size - center, 0 - center : k_size - center]
lowerCamelCase__: Dict =1 / (2 * pi * sigma) * exp(-(square(__a ) + square(__a )) / (2 * square(__a )) )
return g
def lowerCAmelCase_ ( __a , __a , __a ) -> Tuple:
"""simple docstring"""
lowerCamelCase__ , lowerCamelCase__: str =image.shape[0], image.shape[1]
# dst image height and width
lowerCamelCase__: Dict =height - k_size + 1
lowerCamelCase__: Tuple =width - k_size + 1
# im2col, turn the k_size*k_size pixels into a row and np.vstack all rows
lowerCamelCase__: Optional[int] =zeros((dst_height * dst_width, k_size * k_size) )
lowerCamelCase__: Dict =0
for i, j in product(range(__a ) , range(__a ) ):
lowerCamelCase__: Dict =ravel(image[i : i + k_size, j : j + k_size] )
lowerCamelCase__: Optional[int] =window
row += 1
# turn the kernel into shape(k*k, 1)
lowerCamelCase__: List[Any] =gen_gaussian_kernel(__a , __a )
lowerCamelCase__: str =ravel(__a )
# reshape and get the dst image
lowerCamelCase__: Dict =dot(__a , __a ).reshape(__a , __a ).astype(__a )
return dst
if __name__ == "__main__":
# read original image
__A = imread(R"../image_data/lena.jpg")
# turn image in gray scale value
__A = cvtColor(img, COLOR_BGR2GRAY)
# get values with two different mask size
__A = gaussian_filter(gray, 3, sigma=1)
__A = gaussian_filter(gray, 5, sigma=0.8)
# show result images
imshow("gaussian filter with 3x3 mask", gaussianaxa)
imshow("gaussian filter with 5x5 mask", gaussianaxa)
waitKey()
| 59 |
import operator as op
def lowerCAmelCase_ ( __a ) -> Tuple:
"""simple docstring"""
lowerCamelCase__: Optional[Any] =[]
lowerCamelCase__: Tuple =lambda __a , __a : int(x / y ) # noqa: E731 integer division operation
lowerCamelCase__: Tuple ={
"^": op.pow,
"*": op.mul,
"/": div,
"+": op.add,
"-": op.sub,
} # operators & their respective operation
# print table header
print("Symbol".center(8 ) , "Action".center(12 ) , "Stack" , sep=" | " )
print("-" * (30 + len(__a )) )
for x in post_fix:
if x.isdigit(): # if x in digit
stack.append(__a ) # append x to stack
# output in tabular format
print(x.rjust(8 ) , ("push(" + x + ")").ljust(12 ) , ",".join(__a ) , sep=" | " )
else:
lowerCamelCase__: List[Any] =stack.pop() # pop stack
# output in tabular format
print("".rjust(8 ) , ("pop(" + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " )
lowerCamelCase__: Optional[Any] =stack.pop() # pop stack
# output in tabular format
print("".rjust(8 ) , ("pop(" + a + ")").ljust(12 ) , ",".join(__a ) , sep=" | " )
stack.append(
str(opr[x](int(__a ) , int(__a ) ) ) ) # evaluate the 2 values popped from stack & push result to stack
# output in tabular format
print(
x.rjust(8 ) , ("push(" + a + x + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " , )
return int(stack[0] )
if __name__ == "__main__":
__A = input("\n\nEnter a Postfix Equation (space separated) = ").split(" ")
print("\n\tResult = ", solve(Postfix))
| 59 | 1 |
from ...utils import is_note_seq_available, is_transformers_available, is_torch_available
from ...utils import OptionalDependencyNotAvailable
try:
if not (is_transformers_available() and is_torch_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_torch_and_transformers_objects import * # noqa F403
else:
from .notes_encoder import SpectrogramNotesEncoder
from .continous_encoder import SpectrogramContEncoder
from .pipeline_spectrogram_diffusion import (
SpectrogramContEncoder,
SpectrogramDiffusionPipeline,
TaFilmDecoder,
)
try:
if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403
else:
from .midi_utils import MidiProcessor
| 59 |
from collections import defaultdict
from typing import Optional
from ..image_utils import load_image
from ..utils import (
add_end_docstrings,
is_torch_available,
logging,
requires_backends,
)
from .base import PIPELINE_INIT_ARGS, ChunkPipeline
if is_torch_available():
import torch
from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING
__A = logging.get_logger(__name__)
@add_end_docstrings(__SCREAMING_SNAKE_CASE )
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__(self : List[Any] , **UpperCAmelCase_ : Any) ->Any:
'''simple docstring'''
super().__init__(**UpperCAmelCase_)
requires_backends(self , "vision")
requires_backends(self , "torch")
if self.framework != "pt":
raise ValueError(F"""The {self.__class__} is only available in PyTorch.""")
self.check_model_type(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Tuple , **UpperCAmelCase_ : List[Any]) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Optional[int] ={}
lowerCamelCase__: Tuple ={}
lowerCamelCase__: str ={}
# preprocess args
if "points_per_batch" in kwargs:
lowerCamelCase__: Optional[Any] =kwargs["points_per_batch"]
if "points_per_crop" in kwargs:
lowerCamelCase__: int =kwargs["points_per_crop"]
if "crops_n_layers" in kwargs:
lowerCamelCase__: Any =kwargs["crops_n_layers"]
if "crop_overlap_ratio" in kwargs:
lowerCamelCase__: Tuple =kwargs["crop_overlap_ratio"]
if "crop_n_points_downscale_factor" in kwargs:
lowerCamelCase__: List[Any] =kwargs["crop_n_points_downscale_factor"]
# postprocess args
if "pred_iou_thresh" in kwargs:
lowerCamelCase__: List[str] =kwargs["pred_iou_thresh"]
if "stability_score_offset" in kwargs:
lowerCamelCase__: int =kwargs["stability_score_offset"]
if "mask_threshold" in kwargs:
lowerCamelCase__: Optional[int] =kwargs["mask_threshold"]
if "stability_score_thresh" in kwargs:
lowerCamelCase__: str =kwargs["stability_score_thresh"]
if "crops_nms_thresh" in kwargs:
lowerCamelCase__: Any =kwargs["crops_nms_thresh"]
if "output_rle_mask" in kwargs:
lowerCamelCase__: List[Any] =kwargs["output_rle_mask"]
if "output_bboxes_mask" in kwargs:
lowerCamelCase__: List[str] =kwargs["output_bboxes_mask"]
return preprocess_kwargs, forward_params, postprocess_kwargs
def __call__(self : int , UpperCAmelCase_ : Dict , *UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[Any]:
'''simple docstring'''
return super().__call__(UpperCAmelCase_ , *UpperCAmelCase_ , num_workers=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any]=64 , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : float = 512 / 1_500 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 1 , ) ->Dict:
'''simple docstring'''
lowerCamelCase__: Dict =load_image(UpperCAmelCase_)
lowerCamelCase__: List[str] =self.image_processor.size["longest_edge"]
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =self.image_processor.generate_crop_boxes(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: str =self.image_processor(images=UpperCAmelCase_ , return_tensors="pt")
with self.device_placement():
if self.framework == "pt":
lowerCamelCase__: str =self.get_inference_context()
with inference_context():
lowerCamelCase__: Union[str, Any] =self._ensure_tensor_on_device(UpperCAmelCase_ , device=self.device)
lowerCamelCase__: Optional[Any] =self.model.get_image_embeddings(model_inputs.pop("pixel_values"))
lowerCamelCase__: str =image_embeddings
lowerCamelCase__: int =grid_points.shape[1]
lowerCamelCase__: int =points_per_batch if points_per_batch is not None else n_points
if points_per_batch <= 0:
raise ValueError(
"Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. "
"To return all points at once, set points_per_batch to None")
for i in range(0 , UpperCAmelCase_ , UpperCAmelCase_):
lowerCamelCase__: int =grid_points[:, i : i + points_per_batch, :, :]
lowerCamelCase__: Optional[Any] =input_labels[:, i : i + points_per_batch]
lowerCamelCase__: Dict =i == n_points - points_per_batch
yield {
"input_points": batched_points,
"input_labels": labels,
"input_boxes": crop_boxes,
"is_last": is_last,
**model_inputs,
}
def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=0.88 , UpperCAmelCase_ : Optional[Any]=0.95 , UpperCAmelCase_ : Tuple=0 , UpperCAmelCase_ : Any=1 , ) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Any =model_inputs.pop("input_boxes")
lowerCamelCase__: Dict =model_inputs.pop("is_last")
lowerCamelCase__: int =model_inputs.pop("original_sizes").tolist()
lowerCamelCase__: Union[str, Any] =model_inputs.pop("reshaped_input_sizes").tolist()
lowerCamelCase__: Union[str, Any] =self.model(**UpperCAmelCase_)
# post processing happens here in order to avoid CPU GPU copies of ALL the masks
lowerCamelCase__: Optional[int] =model_outputs["pred_masks"]
lowerCamelCase__: Union[str, Any] =self.image_processor.post_process_masks(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , binarize=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =model_outputs["iou_scores"]
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =self.image_processor.filter_masks(
masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , )
return {
"masks": masks,
"is_last": is_last,
"boxes": boxes,
"iou_scores": iou_scores,
}
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Optional[int]=0.7 , ) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Any =[]
lowerCamelCase__: Optional[int] =[]
lowerCamelCase__: List[str] =[]
for model_output in model_outputs:
all_scores.append(model_output.pop("iou_scores"))
all_masks.extend(model_output.pop("masks"))
all_boxes.append(model_output.pop("boxes"))
lowerCamelCase__: str =torch.cat(UpperCAmelCase_)
lowerCamelCase__: List[str] =torch.cat(UpperCAmelCase_)
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Dict =self.image_processor.post_process_for_mask_generation(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: List[str] =defaultdict(UpperCAmelCase_)
for output in model_outputs:
for k, v in output.items():
extra[k].append(UpperCAmelCase_)
lowerCamelCase__: Any ={}
if output_rle_mask:
lowerCamelCase__: Union[str, Any] =rle_mask
if output_bboxes_mask:
lowerCamelCase__: int =bounding_boxes
return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
| 59 | 1 |
import inspect
import unittest
from transformers import RegNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor
if is_flax_available():
import jax
import jax.numpy as jnp
from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def __init__(self : int , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple=3 , UpperCAmelCase_ : Dict=32 , UpperCAmelCase_ : Union[str, Any]=3 , UpperCAmelCase_ : Optional[Any]=10 , UpperCAmelCase_ : Optional[int]=[10, 20, 30, 40] , UpperCAmelCase_ : Optional[Any]=[1, 1, 2, 1] , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : Optional[int]="relu" , UpperCAmelCase_ : Any=3 , UpperCAmelCase_ : Optional[Any]=None , ) ->str:
'''simple docstring'''
lowerCamelCase__: str =parent
lowerCamelCase__: List[Any] =batch_size
lowerCamelCase__: List[str] =image_size
lowerCamelCase__: str =num_channels
lowerCamelCase__: int =embeddings_size
lowerCamelCase__: List[Any] =hidden_sizes
lowerCamelCase__: str =depths
lowerCamelCase__: List[Any] =is_training
lowerCamelCase__: Tuple =use_labels
lowerCamelCase__: Dict =hidden_act
lowerCamelCase__: Optional[int] =num_labels
lowerCamelCase__: Optional[Any] =scope
lowerCamelCase__: List[str] =len(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
lowerCamelCase__: Any =self.get_config()
return config, pixel_values
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->str:
'''simple docstring'''
return RegNetConfig(
num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , )
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Dict) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__: List[Any] =FlaxRegNetModel(config=UpperCAmelCase_)
lowerCamelCase__: Dict =model(UpperCAmelCase_)
# Output shape (b, c, h, w)
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , )
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int]) ->Any:
'''simple docstring'''
lowerCamelCase__: str =self.num_labels
lowerCamelCase__: int =FlaxRegNetForImageClassification(config=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =model(UpperCAmelCase_)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels))
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->int:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =self.prepare_config_and_inputs()
lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =config_and_inputs
lowerCamelCase__: Union[str, Any] ={"pixel_values": pixel_values}
return config, inputs_dict
@require_flax
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ):
'''simple docstring'''
lowercase_ = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()
lowercase_ = False
lowercase_ = False
lowercase_ = False
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->None:
'''simple docstring'''
lowerCamelCase__: List[Any] =FlaxRegNetModelTester(self)
lowerCamelCase__: List[Any] =ConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : int) ->int:
'''simple docstring'''
self.create_and_test_config_common_properties()
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->int:
'''simple docstring'''
return
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Dict:
'''simple docstring'''
lowerCamelCase__: Tuple =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->int:
'''simple docstring'''
lowerCamelCase__: Dict =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_)
@unittest.skip(reason="RegNet does not use inputs_embeds")
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str:
'''simple docstring'''
pass
@unittest.skip(reason="RegNet does not support input and output embeddings")
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Dict:
'''simple docstring'''
pass
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->List[str]:
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: List[Any] =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowerCamelCase__: Any =model_class(UpperCAmelCase_)
lowerCamelCase__: List[Any] =inspect.signature(model.__call__)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
lowerCamelCase__: str =[*signature.parameters.keys()]
lowerCamelCase__: Tuple =["pixel_values"]
self.assertListEqual(arg_names[:1] , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : int) ->Optional[int]:
'''simple docstring'''
def check_hidden_states_output(UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Any):
lowerCamelCase__: Optional[int] =model_class(UpperCAmelCase_)
lowerCamelCase__: Optional[int] =model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_))
lowerCamelCase__: int =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
lowerCamelCase__: Optional[int] =self.model_tester.num_stages
self.assertEqual(len(UpperCAmelCase_) , expected_num_stages + 1)
lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowerCamelCase__: List[str] =True
check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
lowerCamelCase__: Any =True
check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
with self.subTest(model_class.__name__):
lowerCamelCase__: int =self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Dict =model_class(UpperCAmelCase_)
@jax.jit
def model_jitted(UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : str):
return model(pixel_values=UpperCAmelCase_ , **UpperCAmelCase_)
with self.subTest("JIT Enabled"):
lowerCamelCase__: Optional[Any] =model_jitted(**UpperCAmelCase_).to_tuple()
with self.subTest("JIT Disabled"):
with jax.disable_jit():
lowerCamelCase__: Union[str, Any] =model_jitted(**UpperCAmelCase_).to_tuple()
self.assertEqual(len(UpperCAmelCase_) , len(UpperCAmelCase_))
for jitted_output, output in zip(UpperCAmelCase_ , UpperCAmelCase_):
self.assertEqual(jitted_output.shape , output.shape)
def lowerCAmelCase_ ( ) -> Any:
"""simple docstring"""
lowerCamelCase__: Any =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_flax
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
@cached_property
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->int:
'''simple docstring'''
return AutoImageProcessor.from_pretrained("facebook/regnet-y-040") if is_vision_available() else None
@slow
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->List[str]:
'''simple docstring'''
lowerCamelCase__: Any =FlaxRegNetForImageClassification.from_pretrained("facebook/regnet-y-040")
lowerCamelCase__: Optional[int] =self.default_image_processor
lowerCamelCase__: Any =prepare_img()
lowerCamelCase__: Any =image_processor(images=UpperCAmelCase_ , return_tensors="np")
lowerCamelCase__: Tuple =model(**UpperCAmelCase_)
# verify the logits
lowerCamelCase__: List[Any] =(1, 1_000)
self.assertEqual(outputs.logits.shape , UpperCAmelCase_)
lowerCamelCase__: str =jnp.array([-0.4180, -1.5051, -3.4836])
self.assertTrue(jnp.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4))
| 59 |
from transformers import BertTokenizerFast
from .custom_tokenization import CustomTokenizer
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = CustomTokenizer
pass
| 59 | 1 |
from typing import Optional, Union
import torch
from torch import nn
from ...configuration_utils import ConfigMixin, register_to_config
from ...models.modeling_utils import ModelMixin
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
@register_to_config
def __init__(self : Dict , UpperCAmelCase_ : int = 768 , ) ->List[str]:
'''simple docstring'''
super().__init__()
lowerCamelCase__: Any =nn.Parameter(torch.zeros(1 , UpperCAmelCase_))
lowerCamelCase__: List[str] =nn.Parameter(torch.ones(1 , UpperCAmelCase_))
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Optional[Union[str, torch.device]] = None , UpperCAmelCase_ : Optional[torch.dtype] = None , ) ->Any:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =nn.Parameter(self.mean.to(UpperCAmelCase_).to(UpperCAmelCase_))
lowerCamelCase__: Tuple =nn.Parameter(self.std.to(UpperCAmelCase_).to(UpperCAmelCase_))
return self
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Optional[int]) ->int:
'''simple docstring'''
lowerCamelCase__: int =(embeds - self.mean) * 1.0 / self.std
return embeds
def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Union[str, Any]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: List[str] =(embeds * self.std) + self.mean
return embeds
| 59 |
import inspect
import os
import unittest
import torch
import accelerate
from accelerate import Accelerator
from accelerate.test_utils import execute_subprocess_async, require_multi_gpu
from accelerate.utils import patch_environment
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: List[Any] =inspect.getfile(accelerate.test_utils)
lowerCamelCase__: List[Any] =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_script.py"])
lowerCamelCase__: Any =os.path.sep.join(
mod_file.split(os.path.sep)[:-1] + ["scripts", "test_distributed_data_loop.py"])
lowerCamelCase__: Tuple =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_ops.py"])
@require_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : str) ->str:
'''simple docstring'''
print(F"""Found {torch.cuda.device_count()} devices.""")
lowerCamelCase__: Union[str, Any] =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path]
with patch_environment(omp_num_threads=1):
execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy())
@require_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[Any]:
'''simple docstring'''
print(F"""Found {torch.cuda.device_count()} devices.""")
lowerCamelCase__: Dict =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path]
print(F"""Command: {cmd}""")
with patch_environment(omp_num_threads=1):
execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy())
@require_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Tuple:
'''simple docstring'''
lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__)]
with patch_environment(omp_num_threads=1):
execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy())
@require_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]:
'''simple docstring'''
print(F"""Found {torch.cuda.device_count()} devices, using 2 devices only""")
lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path]
with patch_environment(omp_num_threads=1 , cuda_visible_devices="0,1"):
execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy())
if __name__ == "__main__":
__A = Accelerator()
__A = (accelerator.state.process_index + 2, 10)
__A = torch.randint(0, 10, shape).to(accelerator.device)
__A = ""
__A = accelerator.pad_across_processes(tensor)
if tensora.shape[0] != accelerator.state.num_processes + 1:
error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0."
if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor):
error_msg += "Tensors have different values."
if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0):
error_msg += "Padding was not done with the right value (0)."
__A = accelerator.pad_across_processes(tensor, pad_first=True)
if tensora.shape[0] != accelerator.state.num_processes + 1:
error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0."
__A = accelerator.state.num_processes - accelerator.state.process_index - 1
if not torch.equal(tensora[index:], tensor):
error_msg += "Tensors have different values."
if not torch.all(tensora[:index] == 0):
error_msg += "Padding was not done with the right value (0)."
# Raise error at the end to make sure we don't stop at the first failure.
if len(error_msg) > 0:
raise ValueError(error_msg)
| 59 | 1 |
import logging
import torch
from accelerate import Accelerator
from arguments import EvaluationArguments
from datasets import load_dataset
from torch.utils.data import IterableDataset
from torch.utils.data.dataloader import DataLoader
from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__(self : Optional[int] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str=1_024 , UpperCAmelCase_ : List[str]=1_024 , UpperCAmelCase_ : List[Any]=3.6) ->Dict:
'''simple docstring'''
lowerCamelCase__: Optional[int] =tokenizer
lowerCamelCase__: Tuple =tokenizer.bos_token_id
lowerCamelCase__: Optional[Any] =dataset
lowerCamelCase__: str =seq_length
lowerCamelCase__: Union[str, Any] =seq_length * chars_per_token * num_of_sequences
def __iter__(self : List[str]) ->int:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =iter(self.dataset)
lowerCamelCase__: Dict =True
while more_examples:
lowerCamelCase__ , lowerCamelCase__: Optional[int] =[], 0
while True:
if buffer_len >= self.input_characters:
break
try:
buffer.append(next(UpperCAmelCase_)["content"])
buffer_len += len(buffer[-1])
except StopIteration:
lowerCamelCase__: Optional[int] =False
break
lowerCamelCase__: Dict =tokenizer(UpperCAmelCase_ , truncation=UpperCAmelCase_)["input_ids"]
lowerCamelCase__: Any =[]
for tokenized_input in tokenized_inputs:
all_token_ids.extend(tokenized_input + [self.concat_token_id])
for i in range(0 , len(UpperCAmelCase_) , self.seq_length):
lowerCamelCase__: str =all_token_ids[i : i + self.seq_length]
if len(UpperCAmelCase_) == self.seq_length:
yield torch.tensor(UpperCAmelCase_)
def lowerCAmelCase_ ( __a ) -> List[str]:
"""simple docstring"""
lowerCamelCase__: str ={"streaming": True}
lowerCamelCase__: Union[str, Any] =load_dataset(args.dataset_name , split="train" , **__a )
lowerCamelCase__: str =ConstantLengthDataset(__a , __a , seq_length=args.seq_length )
lowerCamelCase__: str =DataLoader(__a , batch_size=args.batch_size )
return eval_dataloader
def lowerCAmelCase_ ( __a ) -> Tuple:
"""simple docstring"""
model.eval()
lowerCamelCase__: int =[]
for step, batch in enumerate(__a ):
with torch.no_grad():
lowerCamelCase__: Tuple =model(__a , labels=__a )
lowerCamelCase__: Union[str, Any] =outputs.loss.repeat(args.batch_size )
losses.append(accelerator.gather(__a ) )
if args.max_eval_steps > 0 and step >= args.max_eval_steps:
break
lowerCamelCase__: Union[str, Any] =torch.mean(torch.cat(__a ) )
try:
lowerCamelCase__: Any =torch.exp(__a )
except OverflowError:
lowerCamelCase__: Optional[int] =float("inf" )
return loss.item(), perplexity.item()
# Setup Accelerator
__A = Accelerator()
# Parse configuration
__A = HfArgumentParser(EvaluationArguments)
__A = parser.parse_args()
set_seed(args.seed)
# Logging
__A = logging.getLogger(__name__)
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO
)
# Load model and tokenizer
__A = AutoModelForCausalLM.from_pretrained(args.model_ckpt)
__A = AutoTokenizer.from_pretrained(args.model_ckpt)
# Load dataset and dataloader
__A = create_dataloader(args)
# Prepare everything with our `accelerator`.
__A , __A = accelerator.prepare(model, eval_dataloader)
# Evaluate and save the last checkpoint
logger.info("Evaluating and saving model after training")
__A , __A = evaluate(args)
logger.info(f'loss/eval: {eval_loss}, perplexity: {perplexity}')
| 59 |
from typing import List, Optional, Tuple, Union
import PIL
import torch
from torchvision import transforms
from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
from diffusers.schedulers import DDIMScheduler
from diffusers.utils import randn_tensor
__A = transforms.Compose(
[
transforms.Resize((256, 256)),
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5]),
]
)
def lowerCAmelCase_ ( __a ) -> str:
"""simple docstring"""
if isinstance(__a , torch.Tensor ):
return image
elif isinstance(__a , PIL.Image.Image ):
lowerCamelCase__: Any =[image]
lowerCamelCase__: Optional[Any] =[trans(img.convert("RGB" ) ) for img in image]
lowerCamelCase__: Dict =torch.stack(__a )
return image
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__(self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple) ->int:
'''simple docstring'''
super().__init__()
# make sure scheduler can always be converted to DDIM
lowerCamelCase__: Tuple =DDIMScheduler.from_config(scheduler.config)
self.register_modules(unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Union[str, Any]) ->Dict:
'''simple docstring'''
if strength < 0 or strength > 1:
raise ValueError(F"""The value of strength should in [0.0, 1.0] but is {strength}""")
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple) ->Tuple:
'''simple docstring'''
lowerCamelCase__: int =min(int(num_inference_steps * strength) , UpperCAmelCase_)
lowerCamelCase__: str =max(num_inference_steps - init_timestep , 0)
lowerCamelCase__: int =self.scheduler.timesteps[t_start:]
return timesteps, num_inference_steps - t_start
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int]=None) ->Optional[int]:
'''simple docstring'''
if not isinstance(UpperCAmelCase_ , (torch.Tensor, PIL.Image.Image, list)):
raise ValueError(
F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(UpperCAmelCase_)}""")
lowerCamelCase__: Optional[int] =image.to(device=UpperCAmelCase_ , dtype=UpperCAmelCase_)
if isinstance(UpperCAmelCase_ , UpperCAmelCase_) and len(UpperCAmelCase_) != batch_size:
raise ValueError(
F"""You have passed a list of generators of length {len(UpperCAmelCase_)}, but requested an effective batch"""
F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""")
lowerCamelCase__: Dict =init_latents.shape
lowerCamelCase__: int =randn_tensor(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=UpperCAmelCase_)
# get latents
print("add noise to latents at timestep" , UpperCAmelCase_)
lowerCamelCase__: Union[str, Any] =self.scheduler.add_noise(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: int =init_latents
return latents
@torch.no_grad()
def __call__(self : Tuple , UpperCAmelCase_ : Union[torch.FloatTensor, PIL.Image.Image] = None , UpperCAmelCase_ : float = 0.8 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , ) ->Union[ImagePipelineOutput, Tuple]:
'''simple docstring'''
self.check_inputs(UpperCAmelCase_)
# 2. Preprocess image
lowerCamelCase__: Dict =preprocess(UpperCAmelCase_)
# 3. set timesteps
self.scheduler.set_timesteps(UpperCAmelCase_ , device=self.device)
lowerCamelCase__ , lowerCamelCase__: str =self.get_timesteps(UpperCAmelCase_ , UpperCAmelCase_ , self.device)
lowerCamelCase__: Optional[int] =timesteps[:1].repeat(UpperCAmelCase_)
# 4. Prepare latent variables
lowerCamelCase__: int =self.prepare_latents(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , self.unet.dtype , self.device , UpperCAmelCase_)
lowerCamelCase__: Tuple =latents
# 5. Denoising loop
for t in self.progress_bar(UpperCAmelCase_):
# 1. predict noise model_output
lowerCamelCase__: Dict =self.unet(UpperCAmelCase_ , UpperCAmelCase_).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
lowerCamelCase__: Optional[int] =self.scheduler.step(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , eta=UpperCAmelCase_ , use_clipped_model_output=UpperCAmelCase_ , generator=UpperCAmelCase_ , ).prev_sample
lowerCamelCase__: str =(image / 2 + 0.5).clamp(0 , 1)
lowerCamelCase__: Optional[Any] =image.cpu().permute(0 , 2 , 3 , 1).numpy()
if output_type == "pil":
lowerCamelCase__: Dict =self.numpy_to_pil(UpperCAmelCase_)
if not return_dict:
return (image, latent_timestep.item())
return ImagePipelineOutput(images=UpperCAmelCase_)
| 59 | 1 |
import operator as op
def lowerCAmelCase_ ( __a ) -> Tuple:
"""simple docstring"""
lowerCamelCase__: Optional[Any] =[]
lowerCamelCase__: Tuple =lambda __a , __a : int(x / y ) # noqa: E731 integer division operation
lowerCamelCase__: Tuple ={
"^": op.pow,
"*": op.mul,
"/": div,
"+": op.add,
"-": op.sub,
} # operators & their respective operation
# print table header
print("Symbol".center(8 ) , "Action".center(12 ) , "Stack" , sep=" | " )
print("-" * (30 + len(__a )) )
for x in post_fix:
if x.isdigit(): # if x in digit
stack.append(__a ) # append x to stack
# output in tabular format
print(x.rjust(8 ) , ("push(" + x + ")").ljust(12 ) , ",".join(__a ) , sep=" | " )
else:
lowerCamelCase__: List[Any] =stack.pop() # pop stack
# output in tabular format
print("".rjust(8 ) , ("pop(" + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " )
lowerCamelCase__: Optional[Any] =stack.pop() # pop stack
# output in tabular format
print("".rjust(8 ) , ("pop(" + a + ")").ljust(12 ) , ",".join(__a ) , sep=" | " )
stack.append(
str(opr[x](int(__a ) , int(__a ) ) ) ) # evaluate the 2 values popped from stack & push result to stack
# output in tabular format
print(
x.rjust(8 ) , ("push(" + a + x + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " , )
return int(stack[0] )
if __name__ == "__main__":
__A = input("\n\nEnter a Postfix Equation (space separated) = ").split(" ")
print("\n\tResult = ", solve(Postfix))
| 59 |
import argparse
import os
import pickle
import sys
import torch
from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl
from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils
from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
logging.set_verbosity_info()
# We do this to be able to load python 2 datasets pickles
# See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918
__A = data_utils.TransfoXLTokenizer
__A = data_utils.TransfoXLCorpus
__A = data_utils
__A = data_utils
def lowerCAmelCase_ ( __a , __a , __a , __a ) -> List[str]:
"""simple docstring"""
if transfo_xl_dataset_file:
# Convert a pre-processed corpus (see original TensorFlow repo)
with open(__a , "rb" ) as fp:
lowerCamelCase__: Optional[Any] =pickle.load(__a , encoding="latin1" )
# Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term)
lowerCamelCase__: Union[str, Any] =pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["pretrained_vocab_file"]
print(F"""Save vocabulary to {pytorch_vocab_dump_path}""" )
lowerCamelCase__: Any =corpus.vocab.__dict__
torch.save(__a , __a )
lowerCamelCase__: Dict =corpus.__dict__
corpus_dict_no_vocab.pop("vocab" , __a )
lowerCamelCase__: List[str] =pytorch_dump_folder_path + "/" + CORPUS_NAME
print(F"""Save dataset to {pytorch_dataset_dump_path}""" )
torch.save(__a , __a )
if tf_checkpoint_path:
# Convert a pre-trained TensorFlow model
lowerCamelCase__: Optional[Any] =os.path.abspath(__a )
lowerCamelCase__: Dict =os.path.abspath(__a )
print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" )
# Initialise PyTorch model
if transfo_xl_config_file == "":
lowerCamelCase__: int =TransfoXLConfig()
else:
lowerCamelCase__: Any =TransfoXLConfig.from_json_file(__a )
print(F"""Building PyTorch model from configuration: {config}""" )
lowerCamelCase__: List[Any] =TransfoXLLMHeadModel(__a )
lowerCamelCase__: List[str] =load_tf_weights_in_transfo_xl(__a , __a , __a )
# Save pytorch-model
lowerCamelCase__: List[str] =os.path.join(__a , __a )
lowerCamelCase__: Tuple =os.path.join(__a , __a )
print(F"""Save PyTorch model to {os.path.abspath(__a )}""" )
torch.save(model.state_dict() , __a )
print(F"""Save configuration file to {os.path.abspath(__a )}""" )
with open(__a , "w" , encoding="utf-8" ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
parser.add_argument(
"--pytorch_dump_folder_path",
default=None,
type=str,
required=True,
help="Path to the folder to store the PyTorch model or dataset/vocab.",
)
parser.add_argument(
"--tf_checkpoint_path",
default="",
type=str,
help="An optional path to a TensorFlow checkpoint path to be converted.",
)
parser.add_argument(
"--transfo_xl_config_file",
default="",
type=str,
help=(
"An optional config json file corresponding to the pre-trained BERT model. \n"
"This specifies the model architecture."
),
)
parser.add_argument(
"--transfo_xl_dataset_file",
default="",
type=str,
help="An optional dataset file to be converted in a vocabulary.",
)
__A = parser.parse_args()
convert_transfo_xl_checkpoint_to_pytorch(
args.tf_checkpoint_path,
args.transfo_xl_config_file,
args.pytorch_dump_folder_path,
args.transfo_xl_dataset_file,
)
| 59 | 1 |
import argparse
from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta
from transformers.utils import logging
logging.set_verbosity_info()
def lowerCAmelCase_ ( __a , __a , __a ) -> List[Any]:
"""simple docstring"""
lowerCamelCase__: Any =TaConfig.from_json_file(__a )
print(F"""Building PyTorch model from configuration: {config}""" )
lowerCamelCase__: Union[str, Any] =TaForConditionalGeneration(__a )
# Load weights from tf checkpoint
load_tf_weights_in_ta(__a , __a , __a )
# Save pytorch-model
print(F"""Save PyTorch model to {pytorch_dump_path}""" )
model.save_pretrained(__a )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
)
parser.add_argument(
"--config_file",
default=None,
type=str,
required=True,
help=(
"The config json file corresponding to the pre-trained T5 model. \nThis specifies the model architecture."
),
)
parser.add_argument(
"--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
)
__A = parser.parse_args()
convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
| 59 |
from collections import UserDict
from typing import List, Union
from ..utils import (
add_end_docstrings,
is_tf_available,
is_torch_available,
is_vision_available,
logging,
requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_vision_available():
from PIL import Image
from ..image_utils import load_image
if is_torch_available():
from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
if is_tf_available():
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
from ..tf_utils import stable_softmax
__A = logging.get_logger(__name__)
@add_end_docstrings(__SCREAMING_SNAKE_CASE )
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__(self : Optional[int] , **UpperCAmelCase_ : List[Any]) ->List[str]:
'''simple docstring'''
super().__init__(**UpperCAmelCase_)
requires_backends(self , "vision")
self.check_model_type(
TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
if self.framework == "tf"
else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING)
def __call__(self : List[str] , UpperCAmelCase_ : Union[str, List[str], "Image", List["Image"]] , **UpperCAmelCase_ : List[Any]) ->Tuple:
'''simple docstring'''
return super().__call__(UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[Any] , **UpperCAmelCase_ : Optional[int]) ->Any:
'''simple docstring'''
lowerCamelCase__: Optional[int] ={}
if "candidate_labels" in kwargs:
lowerCamelCase__: Tuple =kwargs["candidate_labels"]
if "hypothesis_template" in kwargs:
lowerCamelCase__: Tuple =kwargs["hypothesis_template"]
return preprocess_params, {}, {}
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Optional[Any]="This is a photo of {}.") ->str:
'''simple docstring'''
lowerCamelCase__: int =load_image(UpperCAmelCase_)
lowerCamelCase__: Any =self.image_processor(images=[image] , return_tensors=self.framework)
lowerCamelCase__: Any =candidate_labels
lowerCamelCase__: List[str] =[hypothesis_template.format(UpperCAmelCase_) for x in candidate_labels]
lowerCamelCase__: int =self.tokenizer(UpperCAmelCase_ , return_tensors=self.framework , padding=UpperCAmelCase_)
lowerCamelCase__: str =[text_inputs]
return inputs
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Any) ->Tuple:
'''simple docstring'''
lowerCamelCase__: int =model_inputs.pop("candidate_labels")
lowerCamelCase__: List[str] =model_inputs.pop("text_inputs")
if isinstance(text_inputs[0] , UpperCAmelCase_):
lowerCamelCase__: List[Any] =text_inputs[0]
else:
# Batching case.
lowerCamelCase__: List[Any] =text_inputs[0][0]
lowerCamelCase__: List[str] =self.model(**UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: str ={
"candidate_labels": candidate_labels,
"logits": outputs.logits_per_image,
}
return model_outputs
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Union[str, Any]) ->int:
'''simple docstring'''
lowerCamelCase__: List[Any] =model_outputs.pop("candidate_labels")
lowerCamelCase__: Optional[int] =model_outputs["logits"][0]
if self.framework == "pt":
lowerCamelCase__: Optional[Any] =logits.softmax(dim=-1).squeeze(-1)
lowerCamelCase__: Optional[Any] =probs.tolist()
if not isinstance(UpperCAmelCase_ , UpperCAmelCase_):
lowerCamelCase__: Optional[int] =[scores]
elif self.framework == "tf":
lowerCamelCase__: List[str] =stable_softmax(UpperCAmelCase_ , axis=-1)
lowerCamelCase__: Optional[int] =probs.numpy().tolist()
else:
raise ValueError(F"""Unsupported framework: {self.framework}""")
lowerCamelCase__: Optional[int] =[
{"score": score, "label": candidate_label}
for score, candidate_label in sorted(zip(UpperCAmelCase_ , UpperCAmelCase_) , key=lambda UpperCAmelCase_: -x[0])
]
return result
| 59 | 1 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
__A = logging.get_logger(__name__)
__A = {
"shi-labs/nat-mini-in1k-224": "https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json",
# See all Nat models at https://huggingface.co/models?filter=nat
}
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = "nat"
lowercase_ = {
"num_attention_heads": "num_heads",
"num_hidden_layers": "num_layers",
}
def __init__(self : Optional[int] , UpperCAmelCase_ : List[str]=4 , UpperCAmelCase_ : Dict=3 , UpperCAmelCase_ : Optional[Any]=64 , UpperCAmelCase_ : List[str]=[3, 4, 6, 5] , UpperCAmelCase_ : List[str]=[2, 4, 8, 16] , UpperCAmelCase_ : Union[str, Any]=7 , UpperCAmelCase_ : Tuple=3.0 , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : Dict=0.0 , UpperCAmelCase_ : Optional[Any]=0.0 , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Tuple="gelu" , UpperCAmelCase_ : int=0.02 , UpperCAmelCase_ : Dict=1E-5 , UpperCAmelCase_ : Union[str, Any]=0.0 , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : int=None , **UpperCAmelCase_ : str , ) ->int:
'''simple docstring'''
super().__init__(**UpperCAmelCase_)
lowerCamelCase__: Dict =patch_size
lowerCamelCase__: List[Any] =num_channels
lowerCamelCase__: Any =embed_dim
lowerCamelCase__: Optional[Any] =depths
lowerCamelCase__: Dict =len(UpperCAmelCase_)
lowerCamelCase__: List[Any] =num_heads
lowerCamelCase__: Optional[int] =kernel_size
lowerCamelCase__: Any =mlp_ratio
lowerCamelCase__: Optional[int] =qkv_bias
lowerCamelCase__: Optional[int] =hidden_dropout_prob
lowerCamelCase__: Tuple =attention_probs_dropout_prob
lowerCamelCase__: Tuple =drop_path_rate
lowerCamelCase__: Dict =hidden_act
lowerCamelCase__: Any =layer_norm_eps
lowerCamelCase__: Any =initializer_range
# we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel
# this indicates the channel dimension after the last stage of the model
lowerCamelCase__: Union[str, Any] =int(embed_dim * 2 ** (len(UpperCAmelCase_) - 1))
lowerCamelCase__: Tuple =layer_scale_init_value
lowerCamelCase__: int =["stem"] + [F"""stage{idx}""" for idx in range(1 , len(UpperCAmelCase_) + 1)]
lowerCamelCase__ , lowerCamelCase__: Any =get_aligned_output_features_output_indices(
out_features=UpperCAmelCase_ , out_indices=UpperCAmelCase_ , stage_names=self.stage_names)
| 59 |
import json
import os
from dataclasses import dataclass
from functools import partial
from typing import Callable
import flax.linen as nn
import jax
import jax.numpy as jnp
import joblib
import optax
import wandb
from flax import jax_utils, struct, traverse_util
from flax.serialization import from_bytes, to_bytes
from flax.training import train_state
from flax.training.common_utils import shard
from tqdm.auto import tqdm
from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering
from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = 42
lowercase_ = jnp.floataa
lowercase_ = True
def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]:
'''simple docstring'''
super().setup()
lowerCamelCase__: int =nn.Dense(5 , dtype=self.dtype)
def __call__(self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Any) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =super().__call__(*UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: int =self.cls(outputs[2])
return outputs[:2] + (cls_out,)
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = FlaxBigBirdForNaturalQuestionsModule
def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a ) -> Tuple:
"""simple docstring"""
def cross_entropy(__a , __a , __a=None ):
lowerCamelCase__: Tuple =logits.shape[-1]
lowerCamelCase__: Tuple =(labels[..., None] == jnp.arange(__a )[None]).astype("f4" )
lowerCamelCase__: str =jax.nn.log_softmax(__a , axis=-1 )
lowerCamelCase__: Optional[Any] =-jnp.sum(labels * logits , axis=-1 )
if reduction is not None:
lowerCamelCase__: Optional[Any] =reduction(__a )
return loss
lowerCamelCase__: str =partial(__a , reduction=jnp.mean )
lowerCamelCase__: str =cross_entropy(__a , __a )
lowerCamelCase__: Optional[int] =cross_entropy(__a , __a )
lowerCamelCase__: Optional[Any] =cross_entropy(__a , __a )
return (start_loss + end_loss + pooled_loss) / 3
@dataclass
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
lowercase_ = "google/bigbird-roberta-base"
lowercase_ = 3000
lowercase_ = 1_0500
lowercase_ = 128
lowercase_ = 3
lowercase_ = 1
lowercase_ = 5
# tx_args
lowercase_ = 3E-5
lowercase_ = 0.0
lowercase_ = 2_0000
lowercase_ = 0.0095
lowercase_ = "bigbird-roberta-natural-questions"
lowercase_ = "training-expt"
lowercase_ = "data/nq-training.jsonl"
lowercase_ = "data/nq-validation.jsonl"
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[str]:
'''simple docstring'''
os.makedirs(self.base_dir , exist_ok=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =os.path.join(self.base_dir , self.save_dir)
lowerCamelCase__: List[str] =self.batch_size_per_device * jax.device_count()
@dataclass
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
lowercase_ = 42
lowercase_ = 4096 # no dynamic padding on TPUs
def __call__(self : List[Any] , UpperCAmelCase_ : Optional[Any]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =self.collate_fn(UpperCAmelCase_)
lowerCamelCase__: List[Any] =jax.tree_util.tree_map(UpperCAmelCase_ , UpperCAmelCase_)
return batch
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List[str]) ->List[Any]:
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: List[Any] =self.fetch_inputs(features["input_ids"])
lowerCamelCase__: Union[str, Any] ={
"input_ids": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa),
"attention_mask": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa),
"start_labels": jnp.array(features["start_token"] , dtype=jnp.intaa),
"end_labels": jnp.array(features["end_token"] , dtype=jnp.intaa),
"pooled_labels": jnp.array(features["category"] , dtype=jnp.intaa),
}
return batch
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : list) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Tuple =[self._fetch_inputs(UpperCAmelCase_) for ids in input_ids]
return zip(*UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : list) ->Any:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =[1 for _ in range(len(UpperCAmelCase_))]
while len(UpperCAmelCase_) < self.max_length:
input_ids.append(self.pad_id)
attention_mask.append(0)
return input_ids, attention_mask
def lowerCAmelCase_ ( __a , __a , __a=None ) -> str:
"""simple docstring"""
if seed is not None:
lowerCamelCase__: Any =dataset.shuffle(seed=__a )
for i in range(len(__a ) // batch_size ):
lowerCamelCase__: Any =dataset[i * batch_size : (i + 1) * batch_size]
yield dict(__a )
@partial(jax.pmap , axis_name="batch" )
def lowerCAmelCase_ ( __a , __a , **__a ) -> List[str]:
"""simple docstring"""
def loss_fn(__a ):
lowerCamelCase__: Optional[int] =model_inputs.pop("start_labels" )
lowerCamelCase__: int =model_inputs.pop("end_labels" )
lowerCamelCase__: List[str] =model_inputs.pop("pooled_labels" )
lowerCamelCase__: Optional[int] =state.apply_fn(**__a , params=__a , dropout_rng=__a , train=__a )
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[Any] =outputs
return state.loss_fn(
__a , __a , __a , __a , __a , __a , )
lowerCamelCase__ , lowerCamelCase__: int =jax.random.split(__a )
lowerCamelCase__: Optional[Any] =jax.value_and_grad(__a )
lowerCamelCase__ , lowerCamelCase__: List[str] =grad_fn(state.params )
lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" )
lowerCamelCase__: List[str] =jax.lax.pmean(__a , "batch" )
lowerCamelCase__: List[str] =state.apply_gradients(grads=__a )
return state, metrics, new_drp_rng
@partial(jax.pmap , axis_name="batch" )
def lowerCAmelCase_ ( __a , **__a ) -> List[Any]:
"""simple docstring"""
lowerCamelCase__: int =model_inputs.pop("start_labels" )
lowerCamelCase__: List[str] =model_inputs.pop("end_labels" )
lowerCamelCase__: int =model_inputs.pop("pooled_labels" )
lowerCamelCase__: Optional[Any] =state.apply_fn(**__a , params=state.params , train=__a )
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[str] =outputs
lowerCamelCase__: Optional[int] =state.loss_fn(__a , __a , __a , __a , __a , __a )
lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" )
return metrics
class _SCREAMING_SNAKE_CASE ( train_state.TrainState ):
'''simple docstring'''
lowercase_ = struct.field(pytree_node=__SCREAMING_SNAKE_CASE )
@dataclass
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = None
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int=None) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Dict =model.params
lowerCamelCase__: Tuple =TrainState.create(
apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , loss_fn=UpperCAmelCase_ , )
if ckpt_dir is not None:
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =restore_checkpoint(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Tuple ={
"lr": args.lr,
"init_lr": args.init_lr,
"warmup_steps": args.warmup_steps,
"num_train_steps": num_train_steps,
"weight_decay": args.weight_decay,
}
lowerCamelCase__ , lowerCamelCase__: List[Any] =build_tx(**UpperCAmelCase_)
lowerCamelCase__: str =train_state.TrainState(
step=UpperCAmelCase_ , apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , opt_state=UpperCAmelCase_ , )
lowerCamelCase__: Tuple =args
lowerCamelCase__: Tuple =data_collator
lowerCamelCase__: str =lr
lowerCamelCase__: Dict =params
lowerCamelCase__: List[str] =jax_utils.replicate(UpperCAmelCase_)
return state
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Tuple =self.args
lowerCamelCase__: Any =len(UpperCAmelCase_) // args.batch_size
lowerCamelCase__: List[str] =jax.random.PRNGKey(0)
lowerCamelCase__: Optional[Any] =jax.random.split(UpperCAmelCase_ , jax.device_count())
for epoch in range(args.max_epochs):
lowerCamelCase__: Union[str, Any] =jnp.array(0 , dtype=jnp.floataa)
lowerCamelCase__: str =get_batched_dataset(UpperCAmelCase_ , args.batch_size , seed=UpperCAmelCase_)
lowerCamelCase__: Dict =0
for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc=F"""Running EPOCH-{epoch}"""):
lowerCamelCase__: List[str] =self.data_collator(UpperCAmelCase_)
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.train_step_fn(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_)
running_loss += jax_utils.unreplicate(metrics["loss"])
i += 1
if i % args.logging_steps == 0:
lowerCamelCase__: Optional[int] =jax_utils.unreplicate(state.step)
lowerCamelCase__: List[Any] =running_loss.item() / i
lowerCamelCase__: Tuple =self.scheduler_fn(state_step - 1)
lowerCamelCase__: Union[str, Any] =self.evaluate(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Dict ={
"step": state_step.item(),
"eval_loss": eval_loss.item(),
"tr_loss": tr_loss,
"lr": lr.item(),
}
tqdm.write(str(UpperCAmelCase_))
self.logger.log(UpperCAmelCase_ , commit=UpperCAmelCase_)
if i % args.save_steps == 0:
self.save_checkpoint(args.save_dir + F"""-e{epoch}-s{i}""" , state=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str) ->Any:
'''simple docstring'''
lowerCamelCase__: List[Any] =get_batched_dataset(UpperCAmelCase_ , self.args.batch_size)
lowerCamelCase__: List[str] =len(UpperCAmelCase_) // self.args.batch_size
lowerCamelCase__: str =jnp.array(0 , dtype=jnp.floataa)
lowerCamelCase__: Optional[Any] =0
for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc="Evaluating ... "):
lowerCamelCase__: int =self.data_collator(UpperCAmelCase_)
lowerCamelCase__: str =self.val_step_fn(UpperCAmelCase_ , **UpperCAmelCase_)
running_loss += jax_utils.unreplicate(metrics["loss"])
i += 1
return running_loss / i
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int]) ->int:
'''simple docstring'''
lowerCamelCase__: Any =jax_utils.unreplicate(UpperCAmelCase_)
print(F"""SAVING CHECKPOINT IN {save_dir}""" , end=" ... ")
self.model_save_fn(UpperCAmelCase_ , params=state.params)
with open(os.path.join(UpperCAmelCase_ , "opt_state.msgpack") , "wb") as f:
f.write(to_bytes(state.opt_state))
joblib.dump(self.args , os.path.join(UpperCAmelCase_ , "args.joblib"))
joblib.dump(self.data_collator , os.path.join(UpperCAmelCase_ , "data_collator.joblib"))
with open(os.path.join(UpperCAmelCase_ , "training_state.json") , "w") as f:
json.dump({"step": state.step.item()} , UpperCAmelCase_)
print("DONE")
def lowerCAmelCase_ ( __a , __a ) -> str:
"""simple docstring"""
print(F"""RESTORING CHECKPOINT FROM {save_dir}""" , end=" ... " )
with open(os.path.join(__a , "flax_model.msgpack" ) , "rb" ) as f:
lowerCamelCase__: Tuple =from_bytes(state.params , f.read() )
with open(os.path.join(__a , "opt_state.msgpack" ) , "rb" ) as f:
lowerCamelCase__: Optional[int] =from_bytes(state.opt_state , f.read() )
lowerCamelCase__: Any =joblib.load(os.path.join(__a , "args.joblib" ) )
lowerCamelCase__: Union[str, Any] =joblib.load(os.path.join(__a , "data_collator.joblib" ) )
with open(os.path.join(__a , "training_state.json" ) , "r" ) as f:
lowerCamelCase__: Optional[Any] =json.load(__a )
lowerCamelCase__: Any =training_state["step"]
print("DONE" )
return params, opt_state, step, args, data_collator
def lowerCAmelCase_ ( __a , __a , __a , __a ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase__: int =num_train_steps - warmup_steps
lowerCamelCase__: str =optax.linear_schedule(init_value=__a , end_value=__a , transition_steps=__a )
lowerCamelCase__: Optional[Any] =optax.linear_schedule(init_value=__a , end_value=1e-7 , transition_steps=__a )
lowerCamelCase__: List[Any] =optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] )
return lr
def lowerCAmelCase_ ( __a , __a , __a , __a , __a ) -> str:
"""simple docstring"""
def weight_decay_mask(__a ):
lowerCamelCase__: List[str] =traverse_util.flatten_dict(__a )
lowerCamelCase__: List[str] ={k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()}
return traverse_util.unflatten_dict(__a )
lowerCamelCase__: Optional[Any] =scheduler_fn(__a , __a , __a , __a )
lowerCamelCase__: Tuple =optax.adamw(learning_rate=__a , weight_decay=__a , mask=__a )
return tx, lr
| 59 | 1 |
import unittest
from parameterized import parameterized
from transformers import OpenLlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__(self : Tuple , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Any=13 , UpperCAmelCase_ : Union[str, Any]=7 , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : int=False , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : str=99 , UpperCAmelCase_ : Union[str, Any]=32 , UpperCAmelCase_ : Optional[int]=5 , UpperCAmelCase_ : List[str]=4 , UpperCAmelCase_ : List[Any]=37 , UpperCAmelCase_ : str="gelu" , UpperCAmelCase_ : Tuple=0.1 , UpperCAmelCase_ : str=0.1 , UpperCAmelCase_ : Union[str, Any]=512 , UpperCAmelCase_ : Union[str, Any]=16 , UpperCAmelCase_ : List[Any]=2 , UpperCAmelCase_ : int=0.02 , UpperCAmelCase_ : List[str]=3 , UpperCAmelCase_ : Optional[int]=4 , UpperCAmelCase_ : Any=None , ) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Dict =parent
lowerCamelCase__: str =batch_size
lowerCamelCase__: Optional[int] =seq_length
lowerCamelCase__: Dict =is_training
lowerCamelCase__: Optional[int] =use_input_mask
lowerCamelCase__: Dict =use_token_type_ids
lowerCamelCase__: Optional[Any] =use_labels
lowerCamelCase__: str =vocab_size
lowerCamelCase__: int =hidden_size
lowerCamelCase__: List[str] =num_hidden_layers
lowerCamelCase__: int =num_attention_heads
lowerCamelCase__: Any =intermediate_size
lowerCamelCase__: Tuple =hidden_act
lowerCamelCase__: List[Any] =hidden_dropout_prob
lowerCamelCase__: List[str] =attention_probs_dropout_prob
lowerCamelCase__: Union[str, Any] =max_position_embeddings
lowerCamelCase__: Optional[Any] =type_vocab_size
lowerCamelCase__: Tuple =type_sequence_label_size
lowerCamelCase__: int =initializer_range
lowerCamelCase__: Union[str, Any] =num_labels
lowerCamelCase__: Union[str, Any] =num_choices
lowerCamelCase__: str =scope
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->int:
'''simple docstring'''
lowerCamelCase__: List[str] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
lowerCamelCase__: Dict =None
if self.use_input_mask:
lowerCamelCase__: Dict =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__: List[str] =None
lowerCamelCase__: int =None
lowerCamelCase__: str =None
if self.use_labels:
lowerCamelCase__: Dict =ids_tensor([self.batch_size] , self.type_sequence_label_size)
lowerCamelCase__: Optional[Any] =ids_tensor([self.batch_size, self.seq_length] , self.num_labels)
lowerCamelCase__: List[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 SCREAMING_SNAKE_CASE_ (self : Dict) ->Dict:
'''simple docstring'''
return OpenLlamaConfig(
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=UpperCAmelCase_ , initializer_range=self.initializer_range , use_stable_embedding=UpperCAmelCase_ , )
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int]) ->Tuple:
'''simple docstring'''
lowerCamelCase__: List[str] =OpenLlamaModel(config=UpperCAmelCase_)
model.to(UpperCAmelCase_)
model.eval()
lowerCamelCase__: Any =model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_)
lowerCamelCase__: Tuple =model(UpperCAmelCase_)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Any , ) ->Dict:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =True
lowerCamelCase__: List[str] =OpenLlamaModel(UpperCAmelCase_)
model.to(UpperCAmelCase_)
model.eval()
lowerCamelCase__: str =model(
UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , encoder_hidden_states=UpperCAmelCase_ , encoder_attention_mask=UpperCAmelCase_ , )
lowerCamelCase__: Dict =model(
UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , encoder_hidden_states=UpperCAmelCase_ , )
lowerCamelCase__: List[str] =model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int] , ) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: str =OpenLlamaForCausalLM(config=UpperCAmelCase_)
model.to(UpperCAmelCase_)
model.eval()
lowerCamelCase__: Tuple =model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size))
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Any , ) ->Any:
'''simple docstring'''
lowerCamelCase__: Optional[int] =True
lowerCamelCase__: Any =True
lowerCamelCase__: int =OpenLlamaForCausalLM(config=UpperCAmelCase_)
model.to(UpperCAmelCase_)
model.eval()
# first forward pass
lowerCamelCase__: str =model(
UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , encoder_hidden_states=UpperCAmelCase_ , encoder_attention_mask=UpperCAmelCase_ , use_cache=UpperCAmelCase_ , )
lowerCamelCase__: Dict =outputs.past_key_values
# create hypothetical multiple next token and extent to next_input_ids
lowerCamelCase__: Optional[int] =ids_tensor((self.batch_size, 3) , config.vocab_size)
lowerCamelCase__: Optional[Any] =ids_tensor((self.batch_size, 3) , vocab_size=2)
# append to next input_ids and
lowerCamelCase__: Any =torch.cat([input_ids, next_tokens] , dim=-1)
lowerCamelCase__: Dict =torch.cat([input_mask, next_mask] , dim=-1)
lowerCamelCase__: Optional[int] =model(
UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , encoder_hidden_states=UpperCAmelCase_ , encoder_attention_mask=UpperCAmelCase_ , output_hidden_states=UpperCAmelCase_ , )["hidden_states"][0]
lowerCamelCase__: str =model(
UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , encoder_hidden_states=UpperCAmelCase_ , encoder_attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ , output_hidden_states=UpperCAmelCase_ , )["hidden_states"][0]
# select random slice
lowerCamelCase__: str =ids_tensor((1,) , output_from_past.shape[-1]).item()
lowerCamelCase__: List[str] =output_from_no_past[:, -3:, random_slice_idx].detach()
lowerCamelCase__: Union[str, Any] =output_from_past[:, :, random_slice_idx].detach()
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-3))
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =self.prepare_config_and_inputs()
(
(
lowerCamelCase__
) , (
lowerCamelCase__
) , (
lowerCamelCase__
) , (
lowerCamelCase__
) , (
lowerCamelCase__
) , (
lowerCamelCase__
) , (
lowerCamelCase__
) ,
): Optional[int] =config_and_inputs
lowerCamelCase__: Optional[int] ={"input_ids": input_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ):
'''simple docstring'''
lowercase_ = (
(OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else ()
)
lowercase_ = (OpenLlamaForCausalLM,) if is_torch_available() else ()
lowercase_ = (
{
"feature-extraction": OpenLlamaModel,
"text-classification": OpenLlamaForSequenceClassification,
"text-generation": OpenLlamaForCausalLM,
"zero-shot": OpenLlamaForSequenceClassification,
}
if is_torch_available()
else {}
)
lowercase_ = False
lowercase_ = False
def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: str =OpenLlamaModelTester(self)
lowerCamelCase__: Optional[Any] =ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37)
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[str]:
'''simple docstring'''
self.config_tester.run_common_tests()
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->str:
'''simple docstring'''
lowerCamelCase__: List[Any] =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Tuple =self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
lowerCamelCase__: str =type
self.model_tester.create_and_check_model(*UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any) ->Dict:
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.model_tester.prepare_config_and_inputs_for_common()
lowerCamelCase__: Union[str, Any] =3
lowerCamelCase__: Union[str, Any] =input_dict["input_ids"]
lowerCamelCase__: Dict =input_ids.ne(1).to(UpperCAmelCase_)
lowerCamelCase__: Any =ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size)
lowerCamelCase__: Dict =OpenLlamaForSequenceClassification(UpperCAmelCase_)
model.to(UpperCAmelCase_)
model.eval()
lowerCamelCase__: Optional[Any] =model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_)
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels))
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: str =self.model_tester.prepare_config_and_inputs_for_common()
lowerCamelCase__: Tuple =3
lowerCamelCase__: str ="single_label_classification"
lowerCamelCase__: Tuple =input_dict["input_ids"]
lowerCamelCase__: Tuple =input_ids.ne(1).to(UpperCAmelCase_)
lowerCamelCase__: Any =ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size)
lowerCamelCase__: Optional[int] =OpenLlamaForSequenceClassification(UpperCAmelCase_)
model.to(UpperCAmelCase_)
model.eval()
lowerCamelCase__: Optional[int] =model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_)
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels))
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->str:
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: Tuple =self.model_tester.prepare_config_and_inputs_for_common()
lowerCamelCase__: List[Any] =3
lowerCamelCase__: str ="multi_label_classification"
lowerCamelCase__: Dict =input_dict["input_ids"]
lowerCamelCase__: Tuple =input_ids.ne(1).to(UpperCAmelCase_)
lowerCamelCase__: int =ids_tensor(
[self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size).to(torch.float)
lowerCamelCase__: List[Any] =OpenLlamaForSequenceClassification(UpperCAmelCase_)
model.to(UpperCAmelCase_)
model.eval()
lowerCamelCase__: Union[str, Any] =model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_)
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels))
@unittest.skip("Open-Llama buffers include complex numbers, which breaks this test")
def SCREAMING_SNAKE_CASE_ (self : Any) ->Dict:
'''simple docstring'''
pass
@parameterized.expand([("linear",), ("dynamic",)])
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : List[Any]) ->List[str]:
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: Optional[Any] =self.model_tester.prepare_config_and_inputs_for_common()
lowerCamelCase__: Any =ids_tensor([1, 10] , config.vocab_size)
lowerCamelCase__: List[Any] =ids_tensor([1, int(config.max_position_embeddings * 1.5)] , config.vocab_size)
set_seed(42) # Fixed seed at init time so the two models get the same random weights
lowerCamelCase__: str =OpenLlamaModel(UpperCAmelCase_)
original_model.to(UpperCAmelCase_)
original_model.eval()
lowerCamelCase__: Tuple =original_model(UpperCAmelCase_).last_hidden_state
lowerCamelCase__: int =original_model(UpperCAmelCase_).last_hidden_state
set_seed(42) # Fixed seed at init time so the two models get the same random weights
lowerCamelCase__: Union[str, Any] ={"type": scaling_type, "factor": 10.0}
lowerCamelCase__: Optional[int] =OpenLlamaModel(UpperCAmelCase_)
scaled_model.to(UpperCAmelCase_)
scaled_model.eval()
lowerCamelCase__: Any =scaled_model(UpperCAmelCase_).last_hidden_state
lowerCamelCase__: Any =scaled_model(UpperCAmelCase_).last_hidden_state
# Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
# maximum sequence length, so the outputs for the short input should match.
if scaling_type == "dynamic":
self.assertTrue(torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-5))
else:
self.assertFalse(torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-5))
# The output should be different for long inputs
self.assertFalse(torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-5))
| 59 |
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = ["image_processor", "tokenizer"]
lowercase_ = "ChineseCLIPImageProcessor"
lowercase_ = ("BertTokenizer", "BertTokenizerFast")
def __init__(self : Any , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Union[str, Any]=None , **UpperCAmelCase_ : str) ->Dict:
'''simple docstring'''
lowerCamelCase__: str =None
if "feature_extractor" in kwargs:
warnings.warn(
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
" instead." , UpperCAmelCase_ , )
lowerCamelCase__: Tuple =kwargs.pop("feature_extractor")
lowerCamelCase__: Optional[int] =image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError("You need to specify an `image_processor`.")
if tokenizer is None:
raise ValueError("You need to specify a `tokenizer`.")
super().__init__(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Optional[int] =self.image_processor
def __call__(self : int , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[int]:
'''simple docstring'''
if text is None and images is None:
raise ValueError("You have to specify either text or images. Both cannot be none.")
if text is not None:
lowerCamelCase__: Dict =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if images is not None:
lowerCamelCase__: List[str] =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if text is not None and images is not None:
lowerCamelCase__: Union[str, Any] =image_features.pixel_values
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int) ->str:
'''simple docstring'''
return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any]) ->Dict:
'''simple docstring'''
return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_)
@property
def SCREAMING_SNAKE_CASE_ (self : int) ->List[str]:
'''simple docstring'''
lowerCamelCase__: str =self.tokenizer.model_input_names
lowerCamelCase__: Union[str, Any] =self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
@property
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str:
'''simple docstring'''
warnings.warn(
"`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , UpperCAmelCase_ , )
return self.image_processor_class
| 59 | 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 _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ):
'''simple docstring'''
lowercase_ = ShapEPipeline
lowercase_ = ["prompt"]
lowercase_ = ["prompt"]
lowercase_ = [
"num_images_per_prompt",
"num_inference_steps",
"generator",
"latents",
"guidance_scale",
"frame_size",
"output_type",
"return_dict",
]
lowercase_ = False
@property
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[str]:
'''simple docstring'''
return 32
@property
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Optional[int]:
'''simple docstring'''
return 32
@property
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Dict:
'''simple docstring'''
return self.time_input_dim * 4
@property
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->int:
'''simple docstring'''
return 8
@property
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__: Tuple =CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
return tokenizer
@property
def SCREAMING_SNAKE_CASE_ (self : int) ->Optional[int]:
'''simple docstring'''
torch.manual_seed(0)
lowerCamelCase__: Optional[Any] =CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , )
return CLIPTextModelWithProjection(UpperCAmelCase_)
@property
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->List[Any]:
'''simple docstring'''
torch.manual_seed(0)
lowerCamelCase__: List[str] ={
"num_attention_heads": 2,
"attention_head_dim": 16,
"embedding_dim": self.time_input_dim,
"num_embeddings": 32,
"embedding_proj_dim": self.text_embedder_hidden_size,
"time_embed_dim": self.time_embed_dim,
"num_layers": 1,
"clip_embed_dim": self.time_input_dim * 2,
"additional_embeddings": 0,
"time_embed_act_fn": "gelu",
"norm_in_type": "layer",
"encoder_hid_proj_type": None,
"added_emb_type": None,
}
lowerCamelCase__: Optional[Any] =PriorTransformer(**UpperCAmelCase_)
return model
@property
def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]:
'''simple docstring'''
torch.manual_seed(0)
lowerCamelCase__: List[Any] ={
"param_shapes": (
(self.renderer_dim, 93),
(self.renderer_dim, 8),
(self.renderer_dim, 8),
(self.renderer_dim, 8),
),
"d_latent": self.time_input_dim,
"d_hidden": self.renderer_dim,
"n_output": 12,
"background": (
0.1,
0.1,
0.1,
),
}
lowerCamelCase__: Tuple =ShapERenderer(**UpperCAmelCase_)
return model
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: str =self.dummy_prior
lowerCamelCase__: Optional[Any] =self.dummy_text_encoder
lowerCamelCase__: Optional[int] =self.dummy_tokenizer
lowerCamelCase__: List[Any] =self.dummy_renderer
lowerCamelCase__: Any =HeunDiscreteScheduler(
beta_schedule="exp" , num_train_timesteps=1_024 , prediction_type="sample" , use_karras_sigmas=UpperCAmelCase_ , clip_sample=UpperCAmelCase_ , clip_sample_range=1.0 , )
lowerCamelCase__: Dict ={
"prior": prior,
"text_encoder": text_encoder,
"tokenizer": tokenizer,
"renderer": renderer,
"scheduler": scheduler,
}
return components
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[Any]=0) ->str:
'''simple docstring'''
if str(UpperCAmelCase_).startswith("mps"):
lowerCamelCase__: str =torch.manual_seed(UpperCAmelCase_)
else:
lowerCamelCase__: Optional[int] =torch.Generator(device=UpperCAmelCase_).manual_seed(UpperCAmelCase_)
lowerCamelCase__: Tuple ={
"prompt": "horse",
"generator": generator,
"num_inference_steps": 1,
"frame_size": 32,
"output_type": "np",
}
return inputs
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Any:
'''simple docstring'''
lowerCamelCase__: str ="cpu"
lowerCamelCase__: Optional[int] =self.get_dummy_components()
lowerCamelCase__: Dict =self.pipeline_class(**UpperCAmelCase_)
lowerCamelCase__: Any =pipe.to(UpperCAmelCase_)
pipe.set_progress_bar_config(disable=UpperCAmelCase_)
lowerCamelCase__: Any =pipe(**self.get_dummy_inputs(UpperCAmelCase_))
lowerCamelCase__: List[str] =output.images[0]
lowerCamelCase__: Any =image[0, -3:, -3:, -1]
assert image.shape == (20, 32, 32, 3)
lowerCamelCase__: int =np.array(
[
0.0003_9216,
0.0003_9216,
0.0003_9216,
0.0003_9216,
0.0003_9216,
0.0003_9216,
0.0003_9216,
0.0003_9216,
0.0003_9216,
])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Union[str, Any]:
'''simple docstring'''
self._test_inference_batch_consistent(batch_sizes=[1, 2])
def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]:
'''simple docstring'''
lowerCamelCase__: List[Any] =torch_device == "cpu"
lowerCamelCase__: int =True
self._test_inference_batch_single_identical(
batch_size=2 , test_max_difference=UpperCAmelCase_ , relax_max_difference=UpperCAmelCase_ , )
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Any:
'''simple docstring'''
lowerCamelCase__: Tuple =self.get_dummy_components()
lowerCamelCase__: List[Any] =self.pipeline_class(**UpperCAmelCase_)
lowerCamelCase__: List[str] =pipe.to(UpperCAmelCase_)
pipe.set_progress_bar_config(disable=UpperCAmelCase_)
lowerCamelCase__: Dict =1
lowerCamelCase__: List[str] =2
lowerCamelCase__: List[str] =self.get_dummy_inputs(UpperCAmelCase_)
for key in inputs.keys():
if key in self.batch_params:
lowerCamelCase__: List[str] =batch_size * [inputs[key]]
lowerCamelCase__: Union[str, Any] =pipe(**UpperCAmelCase_ , num_images_per_prompt=UpperCAmelCase_)[0]
assert images.shape[0] == batch_size * num_images_per_prompt
@slow
@require_torch_gpu
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Any:
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def SCREAMING_SNAKE_CASE_ (self : Any) ->List[Any]:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =load_numpy(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
"/shap_e/test_shap_e_np_out.npy")
lowerCamelCase__: Any =ShapEPipeline.from_pretrained("openai/shap-e")
lowerCamelCase__: Union[str, Any] =pipe.to(UpperCAmelCase_)
pipe.set_progress_bar_config(disable=UpperCAmelCase_)
lowerCamelCase__: Dict =torch.Generator(device=UpperCAmelCase_).manual_seed(0)
lowerCamelCase__: Dict =pipe(
"a shark" , generator=UpperCAmelCase_ , guidance_scale=15.0 , num_inference_steps=64 , frame_size=64 , output_type="np" , ).images[0]
assert images.shape == (20, 64, 64, 3)
assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_)
| 59 |
from math import ceil, sqrt
def lowerCAmelCase_ ( __a = 1000000 ) -> int:
"""simple docstring"""
lowerCamelCase__: Any =0
for outer_width in range(3 , (limit // 4) + 2 ):
if outer_width**2 > limit:
lowerCamelCase__: Optional[int] =max(ceil(sqrt(outer_width**2 - limit ) ) , 1 )
else:
lowerCamelCase__: Tuple =1
if (outer_width - hole_width_lower_bound) % 2:
hole_width_lower_bound += 1
answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1
return answer
if __name__ == "__main__":
print(f'{solution() = }')
| 59 | 1 |
import copy
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..bit import BitConfig
__A = logging.get_logger(__name__)
__A = {
"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 _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = "dpt"
def __init__(self : Optional[int] , UpperCAmelCase_ : Any=768 , UpperCAmelCase_ : Optional[Any]=12 , UpperCAmelCase_ : Union[str, Any]=12 , UpperCAmelCase_ : Tuple=3_072 , UpperCAmelCase_ : Tuple="gelu" , UpperCAmelCase_ : Dict=0.0 , UpperCAmelCase_ : List[str]=0.0 , UpperCAmelCase_ : List[Any]=0.02 , UpperCAmelCase_ : Any=1E-1_2 , UpperCAmelCase_ : Tuple=384 , UpperCAmelCase_ : Dict=16 , UpperCAmelCase_ : str=3 , UpperCAmelCase_ : Any=False , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Dict=[2, 5, 8, 11] , UpperCAmelCase_ : List[str]="project" , UpperCAmelCase_ : Dict=[4, 2, 1, 0.5] , UpperCAmelCase_ : Dict=[96, 192, 384, 768] , UpperCAmelCase_ : Dict=256 , UpperCAmelCase_ : List[Any]=-1 , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : List[str]=0.4 , UpperCAmelCase_ : str=255 , UpperCAmelCase_ : Optional[int]=0.1 , UpperCAmelCase_ : int=[1, 1_024, 24, 24] , UpperCAmelCase_ : Dict=[0, 1] , UpperCAmelCase_ : List[str]=None , **UpperCAmelCase_ : Optional[Any] , ) ->Tuple:
'''simple docstring'''
super().__init__(**UpperCAmelCase_)
lowerCamelCase__: Optional[int] =hidden_size
lowerCamelCase__: List[str] =is_hybrid
if self.is_hybrid:
if backbone_config is None:
logger.info("Initializing the config with a `BiT` backbone.")
lowerCamelCase__: str ={
"global_padding": "same",
"layer_type": "bottleneck",
"depths": [3, 4, 9],
"out_features": ["stage1", "stage2", "stage3"],
"embedding_dynamic_padding": True,
}
lowerCamelCase__: Union[str, Any] =BitConfig(**UpperCAmelCase_)
elif isinstance(UpperCAmelCase_ , UpperCAmelCase_):
logger.info("Initializing the config with a `BiT` backbone.")
lowerCamelCase__: Optional[Any] =BitConfig(**UpperCAmelCase_)
elif isinstance(UpperCAmelCase_ , UpperCAmelCase_):
lowerCamelCase__: int =backbone_config
else:
raise ValueError(
F"""backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.""")
lowerCamelCase__: Optional[int] =backbone_featmap_shape
lowerCamelCase__: Optional[Any] =neck_ignore_stages
if readout_type != "project":
raise ValueError("Readout type must be 'project' when using `DPT-hybrid` mode.")
else:
lowerCamelCase__: List[Any] =None
lowerCamelCase__: Optional[int] =None
lowerCamelCase__: Optional[Any] =[]
lowerCamelCase__: Union[str, Any] =num_hidden_layers
lowerCamelCase__: List[str] =num_attention_heads
lowerCamelCase__: Any =intermediate_size
lowerCamelCase__: Dict =hidden_act
lowerCamelCase__: Optional[int] =hidden_dropout_prob
lowerCamelCase__: Dict =attention_probs_dropout_prob
lowerCamelCase__: Any =initializer_range
lowerCamelCase__: Optional[int] =layer_norm_eps
lowerCamelCase__: Dict =image_size
lowerCamelCase__: str =patch_size
lowerCamelCase__: Any =num_channels
lowerCamelCase__: Dict =qkv_bias
lowerCamelCase__: Dict =backbone_out_indices
if readout_type not in ["ignore", "add", "project"]:
raise ValueError("Readout_type must be one of ['ignore', 'add', 'project']")
lowerCamelCase__: int =readout_type
lowerCamelCase__: str =reassemble_factors
lowerCamelCase__: int =neck_hidden_sizes
lowerCamelCase__: Dict =fusion_hidden_size
lowerCamelCase__: List[str] =head_in_index
lowerCamelCase__: Dict =use_batch_norm_in_fusion_residual
# auxiliary head attributes (semantic segmentation)
lowerCamelCase__: Dict =use_auxiliary_head
lowerCamelCase__: List[str] =auxiliary_loss_weight
lowerCamelCase__: Union[str, Any] =semantic_loss_ignore_index
lowerCamelCase__: int =semantic_classifier_dropout
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Tuple:
'''simple docstring'''
lowerCamelCase__: List[str] =copy.deepcopy(self.__dict__)
if output["backbone_config"] is not None:
lowerCamelCase__: List[Any] =self.backbone_config.to_dict()
lowerCamelCase__: Union[str, Any] =self.__class__.model_type
return output
| 59 |
def lowerCAmelCase_ ( __a = 50000000 ) -> int:
"""simple docstring"""
lowerCamelCase__: Any =set()
lowerCamelCase__: int =int((limit - 24) ** (1 / 2) )
lowerCamelCase__: Tuple =set(range(3 , prime_square_limit + 1 , 2 ) )
primes.add(2 )
for p in range(3 , prime_square_limit + 1 , 2 ):
if p not in primes:
continue
primes.difference_update(set(range(p * p , prime_square_limit + 1 , __a ) ) )
for primea in primes:
lowerCamelCase__: Optional[int] =primea * primea
for primea in primes:
lowerCamelCase__: List[str] =primea * primea * primea
if square + cube >= limit - 16:
break
for primea in primes:
lowerCamelCase__: int =primea * primea * primea * primea
lowerCamelCase__: Optional[Any] =square + cube + tetr
if total >= limit:
break
ret.add(__a )
return len(__a )
if __name__ == "__main__":
print(f'{solution() = }')
| 59 | 1 |
__A = tuple[float, float, float]
__A = tuple[float, float, float]
def lowerCAmelCase_ ( __a , __a ) -> Vectorad:
"""simple docstring"""
lowerCamelCase__: Optional[int] =end_pointa[0] - end_pointa[0]
lowerCamelCase__: Any =end_pointa[1] - end_pointa[1]
lowerCamelCase__: str =end_pointa[2] - end_pointa[2]
return (x, y, z)
def lowerCAmelCase_ ( __a , __a ) -> Vectorad:
"""simple docstring"""
lowerCamelCase__: List[str] =ab[1] * ac[2] - ab[2] * ac[1] # *i
lowerCamelCase__: Tuple =(ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j
lowerCamelCase__: Tuple =ab[0] * ac[1] - ab[1] * ac[0] # *k
return (x, y, z)
def lowerCAmelCase_ ( __a , __a ) -> bool:
"""simple docstring"""
return tuple(round(__a , __a ) for x in vector ) == (0, 0, 0)
def lowerCAmelCase_ ( __a , __a , __a , __a = 10 ) -> bool:
"""simple docstring"""
lowerCamelCase__: List[Any] =create_vector(__a , __a )
lowerCamelCase__: Dict =create_vector(__a , __a )
return is_zero_vector(get_ad_vectors_cross(__a , __a ) , __a )
| 59 |
from __future__ import annotations
from decimal import Decimal
from math import * # noqa: F403
from sympy import diff
def lowerCAmelCase_ ( __a , __a , __a = 10**-10 ) -> float:
"""simple docstring"""
lowerCamelCase__: List[str] =a
while True:
lowerCamelCase__: Optional[Any] =Decimal(__a ) - (
Decimal(eval(__a ) ) / Decimal(eval(str(diff(__a ) ) ) ) # noqa: S307
)
# This number dictates the accuracy of the answer
if abs(eval(__a ) ) < precision: # noqa: S307
return float(__a )
# Let's Execute
if __name__ == "__main__":
# Find root of trigonometric function
# Find value of pi
print(f'The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}')
# Find root of polynomial
print(f'The root of x**2 - 5*x + 2 = 0 is {newton_raphson("x**2 - 5*x + 2", 0.4)}')
# Find Square Root of 5
print(f'The root of log(x) - 1 = 0 is {newton_raphson("log(x) - 1", 2)}')
# Exponential Roots
print(f'The root of exp(x) - 1 = 0 is {newton_raphson("exp(x) - 1", 0)}')
| 59 | 1 |
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
__A = logging.get_logger(__name__)
__A = "▁"
__A = {"vocab_file": "sentencepiece.bpe.model"}
__A = {
"vocab_file": {
"facebook/mbart-large-en-ro": (
"https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model"
),
"facebook/mbart-large-cc25": (
"https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model"
),
}
}
__A = {
"facebook/mbart-large-en-ro": 1024,
"facebook/mbart-large-cc25": 1024,
}
# fmt: off
__A = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"]
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = VOCAB_FILES_NAMES
lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowercase_ = PRETRAINED_VOCAB_FILES_MAP
lowercase_ = ["input_ids", "attention_mask"]
lowercase_ = []
lowercase_ = []
def __init__(self : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[int]="<s>" , UpperCAmelCase_ : Tuple="</s>" , UpperCAmelCase_ : Tuple="</s>" , UpperCAmelCase_ : Union[str, Any]="<s>" , UpperCAmelCase_ : List[str]="<unk>" , UpperCAmelCase_ : Union[str, Any]="<pad>" , UpperCAmelCase_ : Union[str, Any]="<mask>" , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , UpperCAmelCase_ : Dict=None , **UpperCAmelCase_ : Dict , ) ->Any:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_) if isinstance(UpperCAmelCase_ , UpperCAmelCase_) else mask_token
lowerCamelCase__: str ={} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , tokenizer_file=UpperCAmelCase_ , src_lang=UpperCAmelCase_ , tgt_lang=UpperCAmelCase_ , additional_special_tokens=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , )
lowerCamelCase__: Union[str, Any] =spm.SentencePieceProcessor(**self.sp_model_kwargs)
self.sp_model.Load(str(UpperCAmelCase_))
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>' | ',' | '.' | '▁' | 's' | '▁de' | '-'
# spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a'
# Mimic fairseq token-to-id alignment for the first 4 token
lowerCamelCase__: List[str] ={"<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__: Optional[int] =1
lowerCamelCase__: Optional[Any] =len(self.sp_model)
lowerCamelCase__: int ={
code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(UpperCAmelCase_)
}
lowerCamelCase__: int ={v: k for k, v in self.lang_code_to_id.items()}
lowerCamelCase__: str =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__: Optional[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[int] =src_lang if src_lang is not None else "en_XX"
lowerCamelCase__: int =self.lang_code_to_id[self._src_lang]
lowerCamelCase__: Dict =tgt_lang
self.set_src_lang_special_tokens(self._src_lang)
def __getstate__(self : str) ->Any:
'''simple docstring'''
lowerCamelCase__: str =self.__dict__.copy()
lowerCamelCase__: Optional[Any] =None
lowerCamelCase__: List[Any] =self.sp_model.serialized_model_proto()
return state
def __setstate__(self : List[Any] , UpperCAmelCase_ : Union[str, Any]) ->Any:
'''simple docstring'''
lowerCamelCase__: Tuple =d
# for backward compatibility
if not hasattr(self , "sp_model_kwargs"):
lowerCamelCase__: Dict ={}
lowerCamelCase__: List[str] =spm.SentencePieceProcessor(**self.sp_model_kwargs)
self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
@property
def SCREAMING_SNAKE_CASE_ (self : str) ->Dict:
'''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 SCREAMING_SNAKE_CASE_ (self : List[Any]) ->str:
'''simple docstring'''
return self._src_lang
@src_lang.setter
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : str) ->None:
'''simple docstring'''
lowerCamelCase__: List[str] =new_src_lang
self.set_src_lang_special_tokens(self._src_lang)
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False) ->List[int]:
'''simple docstring'''
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_)
lowerCamelCase__: Any =[1] * len(self.prefix_tokens)
lowerCamelCase__: Tuple =[1] * len(self.suffix_tokens)
if token_ids_a is None:
return prefix_ones + ([0] * len(UpperCAmelCase_)) + suffix_ones
return prefix_ones + ([0] * len(UpperCAmelCase_)) + ([0] * len(UpperCAmelCase_)) + suffix_ones
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None) ->List[int]:
'''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 SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None) ->List[int]:
'''simple docstring'''
lowerCamelCase__: int =[self.sep_token_id]
lowerCamelCase__: 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 SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] , UpperCAmelCase_ : Optional[str] , **UpperCAmelCase_ : Any) ->Tuple:
'''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__: Any =src_lang
lowerCamelCase__: str =self(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =self.convert_tokens_to_ids(UpperCAmelCase_)
lowerCamelCase__: List[Any] =tgt_lang_id
return inputs
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: str ={self.convert_ids_to_tokens(UpperCAmelCase_): i for i in range(self.vocab_size)}
vocab.update(self.added_tokens_encoder)
return vocab
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : str) ->List[str]:
'''simple docstring'''
return self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : List[str]) ->Dict:
'''simple docstring'''
if token in self.fairseq_tokens_to_ids:
return self.fairseq_tokens_to_ids[token]
lowerCamelCase__: Any =self.sp_model.PieceToId(UpperCAmelCase_)
# 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 SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : Dict) ->Optional[Any]:
'''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 SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : Union[str, Any]) ->Dict:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] ="".join(UpperCAmelCase_).replace(UpperCAmelCase_ , " ").strip()
return out_string
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None) ->Tuple[str]:
'''simple docstring'''
if not os.path.isdir(UpperCAmelCase_):
logger.error(F"""Vocabulary path ({save_directory}) should be a directory""")
return
lowerCamelCase__: str =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:
lowerCamelCase__: Optional[Any] =self.sp_model.serialized_model_proto()
fi.write(UpperCAmelCase_)
return (out_vocab_file,)
def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str = "en_XX" , UpperCAmelCase_ : Optional[List[str]] = None , UpperCAmelCase_ : str = "ro_RO" , **UpperCAmelCase_ : List[str] , ) ->BatchEncoding:
'''simple docstring'''
lowerCamelCase__: Optional[int] =src_lang
lowerCamelCase__: Optional[Any] =tgt_lang
return super().prepare_seqaseq_batch(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : str) ->Optional[Any]:
'''simple docstring'''
return self.set_src_lang_special_tokens(self.src_lang)
def SCREAMING_SNAKE_CASE_ (self : str) ->Union[str, Any]:
'''simple docstring'''
return self.set_tgt_lang_special_tokens(self.tgt_lang)
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : str) ->None:
'''simple docstring'''
lowerCamelCase__: Any =self.lang_code_to_id[src_lang]
lowerCamelCase__: Tuple =[]
lowerCamelCase__: Union[str, Any] =[self.eos_token_id, self.cur_lang_code]
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : str) ->None:
'''simple docstring'''
lowerCamelCase__: str =self.lang_code_to_id[lang]
lowerCamelCase__: int =[]
lowerCamelCase__: int =[self.eos_token_id, self.cur_lang_code]
| 59 |
import numpy as np
from numpy import ndarray
from scipy.optimize import Bounds, LinearConstraint, minimize
def lowerCAmelCase_ ( __a ) -> float:
"""simple docstring"""
return np.dot(__a , __a )
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__(self : List[str] , *,
UpperCAmelCase_ : float = np.inf , UpperCAmelCase_ : str = "linear" , UpperCAmelCase_ : float = 0.0 , ) ->None:
'''simple docstring'''
lowerCamelCase__: Dict =regularization
lowerCamelCase__: Any =gamma
if kernel == "linear":
lowerCamelCase__: Dict =self.__linear
elif kernel == "rbf":
if self.gamma == 0:
raise ValueError("rbf kernel requires gamma")
if not isinstance(self.gamma , (float, int)):
raise ValueError("gamma must be float or int")
if not self.gamma > 0:
raise ValueError("gamma must be > 0")
lowerCamelCase__: Tuple =self.__rbf
# in the future, there could be a default value like in sklearn
# sklear: def_gamma = 1/(n_features * X.var()) (wiki)
# previously it was 1/(n_features)
else:
lowerCamelCase__: Optional[Any] =F"""Unknown kernel: {kernel}"""
raise ValueError(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float:
'''simple docstring'''
return np.dot(UpperCAmelCase_ , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float:
'''simple docstring'''
return np.exp(-(self.gamma * norm_squared(vectora - vectora)))
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : list[ndarray] , UpperCAmelCase_ : ndarray) ->None:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =observations
lowerCamelCase__: Optional[int] =classes
# using Wolfe's Dual to calculate w.
# Primal problem: minimize 1/2*norm_squared(w)
# constraint: yn(w . xn + b) >= 1
#
# With l a vector
# Dual problem: maximize sum_n(ln) -
# 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm))
# constraint: self.C >= ln >= 0
# and sum_n(ln*yn) = 0
# Then we get w using w = sum_n(ln*yn*xn)
# At the end we can get b ~= mean(yn - w . xn)
#
# Since we use kernels, we only need l_star to calculate b
# and to classify observations
((lowerCamelCase__) , ): List[str] =np.shape(UpperCAmelCase_)
def to_minimize(UpperCAmelCase_ : ndarray) -> float:
lowerCamelCase__: int =0
((lowerCamelCase__) , ): Optional[Any] =np.shape(UpperCAmelCase_)
for i in range(UpperCAmelCase_):
for j in range(UpperCAmelCase_):
s += (
candidate[i]
* candidate[j]
* classes[i]
* classes[j]
* self.kernel(observations[i] , observations[j])
)
return 1 / 2 * s - sum(UpperCAmelCase_)
lowerCamelCase__: List[Any] =LinearConstraint(UpperCAmelCase_ , 0 , 0)
lowerCamelCase__: str =Bounds(0 , self.regularization)
lowerCamelCase__: Union[str, Any] =minimize(
UpperCAmelCase_ , np.ones(UpperCAmelCase_) , bounds=UpperCAmelCase_ , constraints=[ly_contraint]).x
lowerCamelCase__: str =l_star
# calculating mean offset of separation plane to points
lowerCamelCase__: Tuple =0
for i in range(UpperCAmelCase_):
for j in range(UpperCAmelCase_):
s += classes[i] - classes[i] * self.optimum[i] * self.kernel(
observations[i] , observations[j])
lowerCamelCase__: int =s / n
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : ndarray) ->int:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =sum(
self.optimum[n]
* self.classes[n]
* self.kernel(self.observations[n] , UpperCAmelCase_)
for n in range(len(self.classes)))
return 1 if s + self.offset >= 0 else -1
if __name__ == "__main__":
import doctest
doctest.testmod()
| 59 | 1 |
import json
import logging
import os
import sys
from pathlib import Path
import finetune_rag
from transformers.file_utils import is_apex_available
from transformers.testing_utils import (
TestCasePlus,
execute_subprocess_async,
require_ray,
require_torch_gpu,
require_torch_multi_gpu,
)
logging.basicConfig(level=logging.DEBUG)
__A = logging.getLogger()
__A = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : int) ->List[str]:
'''simple docstring'''
os.makedirs(UpperCAmelCase_ , exist_ok=UpperCAmelCase_)
lowerCamelCase__: Union[str, Any] ={"source": "What is love ?", "target": "life"}
lowerCamelCase__: str ={"train": 12, "val": 2, "test": 2}
for split in ["train", "test", "val"]:
for field in ["source", "target"]:
lowerCamelCase__: Optional[int] ="\n".join([contents[field]] * n_lines[split])
with open(os.path.join(UpperCAmelCase_ , F"""{split}.{field}""") , "w") as f:
f.write(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : str = "pytorch") ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Dict =self.get_auto_remove_tmp_dir()
lowerCamelCase__: Tuple =os.path.join(UpperCAmelCase_ , "output")
lowerCamelCase__: str =os.path.join(UpperCAmelCase_ , "data")
self._create_dummy_data(data_dir=UpperCAmelCase_)
lowerCamelCase__: str =F"""
--data_dir {data_dir} \
--output_dir {output_dir} \
--model_name_or_path facebook/rag-sequence-base \
--model_type rag_sequence \
--do_train \
--do_predict \
--n_val -1 \
--val_check_interval 1.0 \
--train_batch_size 2 \
--eval_batch_size 1 \
--max_source_length 25 \
--max_target_length 25 \
--val_max_target_length 25 \
--test_max_target_length 25 \
--label_smoothing 0.1 \
--dropout 0.1 \
--attention_dropout 0.1 \
--weight_decay 0.001 \
--adam_epsilon 1e-08 \
--max_grad_norm 0.1 \
--lr_scheduler polynomial \
--learning_rate 3e-04 \
--num_train_epochs 1 \
--warmup_steps 4 \
--gradient_accumulation_steps 1 \
--distributed-port 8787 \
--use_dummy_dataset 1 \
--distributed_retriever {distributed_retriever} \
""".split()
if gpus > 0:
testargs.append(F"""--gpus={gpus}""")
if is_apex_available():
testargs.append("--fp16")
else:
testargs.append("--gpus=0")
testargs.append("--distributed_backend=ddp_cpu")
testargs.append("--num_processes=2")
lowerCamelCase__: List[Any] =[sys.executable, str(Path(finetune_rag.__file__).resolve())] + testargs
execute_subprocess_async(UpperCAmelCase_ , env=self.get_env())
lowerCamelCase__: int =os.path.join(UpperCAmelCase_ , "metrics.json")
with open(UpperCAmelCase_) as f:
lowerCamelCase__: Optional[Any] =json.load(UpperCAmelCase_)
return result
@require_torch_gpu
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =self._run_finetune(gpus=1)
self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2)
@require_torch_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[int] =self._run_finetune(gpus=2)
self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2)
@require_torch_gpu
@require_ray
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Tuple:
'''simple docstring'''
lowerCamelCase__: str =self._run_finetune(gpus=1 , distributed_retriever="ray")
self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2)
@require_torch_multi_gpu
@require_ray
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Dict =self._run_finetune(gpus=1 , distributed_retriever="ray")
self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2)
| 59 |
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
__A = logging.getLogger(__name__)
def lowerCAmelCase_ ( __a , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = False , ) -> str:
"""simple docstring"""
lowerCamelCase__: int =bnb_quantization_config.load_in_abit
lowerCamelCase__: Any =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." )
lowerCamelCase__: List[Any] =[]
# custom device map
if isinstance(__a , __a ) and len(device_map.keys() ) > 1:
lowerCamelCase__: Optional[int] =[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:
lowerCamelCase__: Any =get_keys_to_not_convert(__a )
# add cpu modules to skip modules only for 4-bit modules
if load_in_abit:
bnb_quantization_config.skip_modules.extend(__a )
lowerCamelCase__: List[str] =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:
lowerCamelCase__: List[Any] =[]
lowerCamelCase__: int =bnb_quantization_config.keep_in_fpaa_modules
modules_to_not_convert.extend(__a )
# compatibility with peft
lowerCamelCase__: List[str] =load_in_abit
lowerCamelCase__: int =load_in_abit
lowerCamelCase__: Tuple =get_parameter_device(__a )
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." )
lowerCamelCase__: Tuple =replace_with_bnb_layers(__a , __a , modules_to_not_convert=__a )
# convert param to the right dtype
lowerCamelCase__: Dict =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:
lowerCamelCase__: str =name.replace(".weight" , "" ).replace(".bias" , "" )
lowerCamelCase__: Optional[Any] =getattr(__a , __a , __a )
if param is not None:
param.to(torch.floataa )
elif torch.is_floating_point(__a ):
param.to(__a )
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():
lowerCamelCase__: str =replace_with_bnb_layers(
__a , __a , modules_to_not_convert=__a )
lowerCamelCase__: Optional[Any] =get_quantized_model_device_map(
__a , __a , __a , max_memory=__a , no_split_module_classes=__a , )
if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
lowerCamelCase__: Any =True
lowerCamelCase__: List[str] =any(x in list(device_map.values() ) for x in ["cpu", "disk"] )
load_checkpoint_in_model(
__a , __a , __a , dtype=bnb_quantization_config.torch_dtype , offload_folder=__a , offload_state_dict=__a , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , )
return dispatch_model(__a , device_map=__a , offload_dir=__a )
def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , __a=None ) -> str:
"""simple docstring"""
if device_map is None:
if torch.cuda.is_available():
lowerCamelCase__: str ={"": 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(__a , __a ):
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'." )
lowerCamelCase__: Optional[int] ={}
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 )
} )
lowerCamelCase__: Optional[Any] ={}
lowerCamelCase__: str =special_dtypes
lowerCamelCase__: List[str] =no_split_module_classes
lowerCamelCase__: Dict =bnb_quantization_config.target_dtype
# get max_memory for each device.
if device_map != "sequential":
lowerCamelCase__: Optional[Any] =get_balanced_memory(
__a , low_zero=(device_map == "balanced_low_0") , max_memory=__a , **__a , )
lowerCamelCase__: Union[str, Any] =max_memory
lowerCamelCase__: Dict =infer_auto_device_map(__a , **__a )
if isinstance(__a , __a ):
# check if don't have any quantized module on the cpu
lowerCamelCase__: Union[str, Any] =bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules
lowerCamelCase__: List[Any] ={
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(
"\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n " )
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 lowerCAmelCase_ ( __a , __a , __a=None , __a=None ) -> Optional[Any]:
"""simple docstring"""
if modules_to_not_convert is None:
lowerCamelCase__: List[Any] =[]
lowerCamelCase__ , lowerCamelCase__: Any =_replace_with_bnb_layers(
__a , __a , __a , __a )
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 lowerCAmelCase_ ( __a , __a , __a=None , __a=None , ) -> List[Any]:
"""simple docstring"""
lowerCamelCase__: Optional[int] =False
for name, module in model.named_children():
if current_key_name is None:
lowerCamelCase__: Optional[Any] =[]
current_key_name.append(__a )
if isinstance(__a , nn.Linear ) and name not in modules_to_not_convert:
# Check if the current key is not in the `modules_to_not_convert`
lowerCamelCase__: List[str] =".".join(__a )
lowerCamelCase__: Optional[Any] =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:
lowerCamelCase__: int =False
break
if proceed:
# Load bnb module with empty weight and replace ``nn.Linear` module
if bnb_quantization_config.load_in_abit:
lowerCamelCase__: Optional[int] =bnb.nn.LinearabitLt(
module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=__a , threshold=bnb_quantization_config.llm_inta_threshold , )
elif bnb_quantization_config.load_in_abit:
lowerCamelCase__: Dict =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" )
lowerCamelCase__: Dict =module.weight.data
if module.bias is not None:
lowerCamelCase__: List[Any] =module.bias.data
bnb_module.requires_grad_(__a )
setattr(__a , __a , __a )
lowerCamelCase__: int =True
if len(list(module.children() ) ) > 0:
lowerCamelCase__ , lowerCamelCase__: List[str] =_replace_with_bnb_layers(
__a , __a , __a , __a )
lowerCamelCase__: Union[str, Any] =has_been_replaced | _has_been_replaced
# Remove the last key for recursion
current_key_name.pop(-1 )
return model, has_been_replaced
def lowerCAmelCase_ ( __a ) -> List[Any]:
"""simple docstring"""
with init_empty_weights():
lowerCamelCase__: Any =deepcopy(__a ) # this has 0 cost since it is done inside `init_empty_weights` context manager`
lowerCamelCase__: str =find_tied_parameters(__a )
# For compatibility with Accelerate < 0.18
if isinstance(__a , __a ):
lowerCamelCase__: int =sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() )
else:
lowerCamelCase__: str =sum(__a , [] )
lowerCamelCase__: str =len(__a ) > 0
# Check if it is a base model
lowerCamelCase__: Optional[Any] =False
if hasattr(__a , "base_model_prefix" ):
lowerCamelCase__: Union[str, Any] =not hasattr(__a , 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
lowerCamelCase__: Optional[int] =list(model.named_children() )
lowerCamelCase__: Optional[int] =[list_modules[-1][0]]
# add last module together with tied weights
lowerCamelCase__: Union[str, Any] =set(__a ) - set(__a )
lowerCamelCase__: List[str] =list(set(__a ) ) + list(__a )
# remove ".weight" from the keys
lowerCamelCase__: List[Any] =[".weight", ".bias"]
lowerCamelCase__: Tuple =[]
for name in list_untouched:
for name_to_remove in names_to_remove:
if name_to_remove in name:
lowerCamelCase__: Optional[Any] =name.replace(__a , "" )
filtered_module_names.append(__a )
return filtered_module_names
def lowerCAmelCase_ ( __a ) -> Tuple:
"""simple docstring"""
for m in model.modules():
if isinstance(__a , bnb.nn.Linearabit ):
return True
return False
def lowerCAmelCase_ ( __a ) -> List[str]:
"""simple docstring"""
return next(parameter.parameters() ).device
def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a , __a ) -> Any:
"""simple docstring"""
if fpaa_statistics is None:
set_module_tensor_to_device(__a , __a , 0 , dtype=__a , value=__a )
lowerCamelCase__: Dict =param_name
lowerCamelCase__: Tuple =model
if "." in tensor_name:
lowerCamelCase__: Any =tensor_name.split("." )
for split in splits[:-1]:
lowerCamelCase__: Any =getattr(__a , __a )
if new_module is None:
raise ValueError(F"""{module} has no attribute {split}.""" )
lowerCamelCase__: str =new_module
lowerCamelCase__: int =splits[-1]
# offload weights
lowerCamelCase__: str =False
offload_weight(module._parameters[tensor_name] , __a , __a , index=__a )
if hasattr(module._parameters[tensor_name] , "SCB" ):
offload_weight(
module._parameters[tensor_name].SCB , param_name.replace("weight" , "SCB" ) , __a , index=__a , )
else:
offload_weight(__a , __a , __a , index=__a )
offload_weight(__a , param_name.replace("weight" , "SCB" ) , __a , index=__a )
set_module_tensor_to_device(__a , __a , "meta" , dtype=__a , value=torch.empty(*param.size() ) )
| 59 | 1 |
from typing import Optional
from urllib.parse import quote
import huggingface_hub as hfh
from packaging import version
def lowerCAmelCase_ ( __a , __a , __a = None ) -> str:
"""simple docstring"""
if version.parse(hfh.__version__ ).release < version.parse("0.11.0" ).release:
# old versions of hfh don't url-encode the file path
lowerCamelCase__: Union[str, Any] =quote(__a )
return hfh.hf_hub_url(__a , __a , repo_type="dataset" , revision=__a )
| 59 |
from __future__ import annotations
from math import pi
def lowerCAmelCase_ ( __a , __a , __a ) -> dict[str, float]:
"""simple docstring"""
if (inductance, frequency, reactance).count(0 ) != 1:
raise ValueError("One and only one argument must be 0" )
if inductance < 0:
raise ValueError("Inductance cannot be negative" )
if frequency < 0:
raise ValueError("Frequency cannot be negative" )
if reactance < 0:
raise ValueError("Inductive reactance cannot be negative" )
if inductance == 0:
return {"inductance": reactance / (2 * pi * frequency)}
elif frequency == 0:
return {"frequency": reactance / (2 * pi * inductance)}
elif reactance == 0:
return {"reactance": 2 * pi * frequency * inductance}
else:
raise ValueError("Exactly one argument must be 0" )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 59 | 1 |
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.layers import LSTM, Dense
from tensorflow.keras.models import Sequential
if __name__ == "__main__":
__A = pd.read_csv("sample_data.csv", header=None)
__A = df.shape[:1][0]
# If you're using some other dataset input the target column
__A = df.iloc[:, 1:2]
__A = actual_data.values.reshape(len_data, 1)
__A = MinMaxScaler().fit_transform(actual_data)
__A = 10
__A = 5
__A = 20
__A = len_data - periods * look_back
__A = actual_data[:division]
__A = actual_data[division - look_back :]
__A , __A = [], []
__A , __A = [], []
for i in range(0, len(train_data) - forward_days - look_back + 1):
train_x.append(train_data[i : i + look_back])
train_y.append(train_data[i + look_back : i + look_back + forward_days])
for i in range(0, len(test_data) - forward_days - look_back + 1):
test_x.append(test_data[i : i + look_back])
test_y.append(test_data[i + look_back : i + look_back + forward_days])
__A = np.array(train_x)
__A = np.array(test_x)
__A = np.array([list(i.ravel()) for i in train_y])
__A = np.array([list(i.ravel()) for i in test_y])
__A = Sequential()
model.add(LSTM(128, input_shape=(look_back, 1), return_sequences=True))
model.add(LSTM(64, input_shape=(128, 1)))
model.add(Dense(forward_days))
model.compile(loss="mean_squared_error", optimizer="adam")
__A = model.fit(
x_train, y_train, epochs=150, verbose=1, shuffle=True, batch_size=4
)
__A = model.predict(x_test)
| 59 |
import pyarrow.parquet as pq
import pytest
from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config
from datasets.features.image import Image
from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size
from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases
def lowerCAmelCase_ ( __a , __a ) -> List[Any]:
"""simple docstring"""
assert isinstance(__a , __a )
assert dataset.num_rows == 4
assert dataset.num_columns == 3
assert dataset.column_names == ["col_1", "col_2", "col_3"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("keep_in_memory" , [False, True] )
def lowerCAmelCase_ ( __a , __a , __a ) -> Any:
"""simple docstring"""
lowerCamelCase__: Any =tmp_path / "cache"
lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
lowerCamelCase__: Tuple =ParquetDatasetReader(__a , cache_dir=__a , keep_in_memory=__a ).read()
_check_parquet_dataset(__a , __a )
@pytest.mark.parametrize(
"features" , [
None,
{"col_1": "string", "col_2": "int64", "col_3": "float64"},
{"col_1": "string", "col_2": "string", "col_3": "string"},
{"col_1": "int32", "col_2": "int32", "col_3": "int32"},
{"col_1": "float32", "col_2": "float32", "col_3": "float32"},
] , )
def lowerCAmelCase_ ( __a , __a , __a ) -> List[str]:
"""simple docstring"""
lowerCamelCase__: int =tmp_path / "cache"
lowerCamelCase__: Tuple ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
lowerCamelCase__: Union[str, Any] =features.copy() if features else default_expected_features
lowerCamelCase__: Optional[int] =(
Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None
)
lowerCamelCase__: int =ParquetDatasetReader(__a , features=__a , cache_dir=__a ).read()
_check_parquet_dataset(__a , __a )
@pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] )
def lowerCAmelCase_ ( __a , __a , __a ) -> Any:
"""simple docstring"""
lowerCamelCase__: Any =tmp_path / "cache"
lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
lowerCamelCase__: Optional[Any] =ParquetDatasetReader(__a , cache_dir=__a , split=__a ).read()
_check_parquet_dataset(__a , __a )
assert dataset.split == split if split else "train"
@pytest.mark.parametrize("path_type" , [str, list] )
def lowerCAmelCase_ ( __a , __a , __a ) -> int:
"""simple docstring"""
if issubclass(__a , __a ):
lowerCamelCase__: List[Any] =parquet_path
elif issubclass(__a , __a ):
lowerCamelCase__: str =[parquet_path]
lowerCamelCase__: Tuple =tmp_path / "cache"
lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read()
_check_parquet_dataset(__a , __a )
def lowerCAmelCase_ ( __a , __a , __a=("train",) ) -> Dict:
"""simple docstring"""
assert isinstance(__a , __a )
for split in splits:
lowerCamelCase__: Tuple =dataset_dict[split]
assert dataset.num_rows == 4
assert dataset.num_columns == 3
assert dataset.column_names == ["col_1", "col_2", "col_3"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("keep_in_memory" , [False, True] )
def lowerCAmelCase_ ( __a , __a , __a ) -> Any:
"""simple docstring"""
lowerCamelCase__: List[Any] =tmp_path / "cache"
lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
lowerCamelCase__: Tuple =ParquetDatasetReader(
{"train": parquet_path} , cache_dir=__a , keep_in_memory=__a ).read()
_check_parquet_datasetdict(__a , __a )
@pytest.mark.parametrize(
"features" , [
None,
{"col_1": "string", "col_2": "int64", "col_3": "float64"},
{"col_1": "string", "col_2": "string", "col_3": "string"},
{"col_1": "int32", "col_2": "int32", "col_3": "int32"},
{"col_1": "float32", "col_2": "float32", "col_3": "float32"},
] , )
def lowerCAmelCase_ ( __a , __a , __a ) -> Optional[Any]:
"""simple docstring"""
lowerCamelCase__: Tuple =tmp_path / "cache"
lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
lowerCamelCase__: List[Any] =features.copy() if features else default_expected_features
lowerCamelCase__: int =(
Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None
)
lowerCamelCase__: Optional[Any] =ParquetDatasetReader({"train": parquet_path} , features=__a , cache_dir=__a ).read()
_check_parquet_datasetdict(__a , __a )
@pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] )
def lowerCAmelCase_ ( __a , __a , __a ) -> Union[str, Any]:
"""simple docstring"""
if split:
lowerCamelCase__: Any ={split: parquet_path}
else:
lowerCamelCase__: int ="train"
lowerCamelCase__: Any ={"train": parquet_path, "test": parquet_path}
lowerCamelCase__: str =tmp_path / "cache"
lowerCamelCase__: Any ={"col_1": "string", "col_2": "int64", "col_3": "float64"}
lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read()
_check_parquet_datasetdict(__a , __a , splits=list(path.keys() ) )
assert all(dataset[split].split == split for split in path.keys() )
def lowerCAmelCase_ ( __a , __a ) -> int:
"""simple docstring"""
lowerCamelCase__: List[str] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" )
assert writer.write() > 0
lowerCamelCase__: List[str] =pq.ParquetFile(tmp_path / "foo.parquet" )
lowerCamelCase__: List[str] =pf.read()
assert dataset.data.table == output_table
def lowerCAmelCase_ ( __a , __a ) -> List[str]:
"""simple docstring"""
lowerCamelCase__: List[str] =str(shared_datadir / "test_image_rgb.jpg" )
lowerCamelCase__: Union[str, Any] ={"image": [image_path]}
lowerCamelCase__: Optional[Any] =Features({"image": Image()} )
lowerCamelCase__: Optional[int] =Dataset.from_dict(__a , features=__a )
lowerCamelCase__: Optional[int] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" )
assert writer.write() > 0
lowerCamelCase__: Dict =Dataset.from_parquet(str(tmp_path / "foo.parquet" ) )
assert dataset.features == reloaded_dataset.features
lowerCamelCase__: Optional[Any] =ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=__a ).read()
assert dataset.features == reloaded_iterable_dataset.features
@pytest.mark.parametrize(
"feature, expected" , [
(Features({"foo": Value("int32" )} ), None),
(Features({"image": Image(), "foo": Value("int32" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS),
(Features({"nested": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS),
] , )
def lowerCAmelCase_ ( __a , __a ) -> Optional[Any]:
"""simple docstring"""
assert get_writer_batch_size(__a ) == expected
| 59 | 1 |
import json
import os
import shutil
import tempfile
from unittest import TestCase
from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast
from transformers.models.bart.configuration_bart import BartConfig
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
from transformers.models.dpr.configuration_dpr import DPRConfig
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow
from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available
if is_torch_available() and is_datasets_available() and is_faiss_available():
from transformers.models.rag.configuration_rag import RagConfig
from transformers.models.rag.tokenization_rag import RagTokenizer
@require_faiss
@require_torch
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Tuple:
'''simple docstring'''
lowerCamelCase__: str =tempfile.mkdtemp()
lowerCamelCase__: Optional[int] =8
# DPR tok
lowerCamelCase__: Dict =[
"[UNK]",
"[CLS]",
"[SEP]",
"[PAD]",
"[MASK]",
"want",
"##want",
"##ed",
"wa",
"un",
"runn",
"##ing",
",",
"low",
"lowest",
]
lowerCamelCase__: Optional[Any] =os.path.join(self.tmpdirname , "dpr_tokenizer")
os.makedirs(UpperCAmelCase_ , exist_ok=UpperCAmelCase_)
lowerCamelCase__: Any =os.path.join(UpperCAmelCase_ , DPR_VOCAB_FILES_NAMES["vocab_file"])
with open(self.vocab_file , "w" , encoding="utf-8") as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
# BART tok
lowerCamelCase__: Union[str, Any] =[
"l",
"o",
"w",
"e",
"r",
"s",
"t",
"i",
"d",
"n",
"\u0120",
"\u0120l",
"\u0120n",
"\u0120lo",
"\u0120low",
"er",
"\u0120lowest",
"\u0120newer",
"\u0120wider",
"<unk>",
]
lowerCamelCase__: Optional[int] =dict(zip(UpperCAmelCase_ , range(len(UpperCAmelCase_))))
lowerCamelCase__: int =["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
lowerCamelCase__: List[str] ={"unk_token": "<unk>"}
lowerCamelCase__: Dict =os.path.join(self.tmpdirname , "bart_tokenizer")
os.makedirs(UpperCAmelCase_ , exist_ok=UpperCAmelCase_)
lowerCamelCase__: Any =os.path.join(UpperCAmelCase_ , BART_VOCAB_FILES_NAMES["vocab_file"])
lowerCamelCase__: Tuple =os.path.join(UpperCAmelCase_ , BART_VOCAB_FILES_NAMES["merges_file"])
with open(self.vocab_file , "w" , encoding="utf-8") as fp:
fp.write(json.dumps(UpperCAmelCase_) + "\n")
with open(self.merges_file , "w" , encoding="utf-8") as fp:
fp.write("\n".join(UpperCAmelCase_))
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->DPRQuestionEncoderTokenizer:
'''simple docstring'''
return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , "dpr_tokenizer"))
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->BartTokenizer:
'''simple docstring'''
return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , "bart_tokenizer"))
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]:
'''simple docstring'''
shutil.rmtree(self.tmpdirname)
@require_tokenizers
def SCREAMING_SNAKE_CASE_ (self : int) ->List[Any]:
'''simple docstring'''
lowerCamelCase__: Tuple =os.path.join(self.tmpdirname , "rag_tokenizer")
lowerCamelCase__: Optional[Any] =RagConfig(question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict())
lowerCamelCase__: Union[str, Any] =RagTokenizer(question_encoder=self.get_dpr_tokenizer() , generator=self.get_bart_tokenizer())
rag_config.save_pretrained(UpperCAmelCase_)
rag_tokenizer.save_pretrained(UpperCAmelCase_)
lowerCamelCase__: Union[str, Any] =RagTokenizer.from_pretrained(UpperCAmelCase_ , config=UpperCAmelCase_)
self.assertIsInstance(new_rag_tokenizer.question_encoder , UpperCAmelCase_)
self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab() , rag_tokenizer.question_encoder.get_vocab())
self.assertIsInstance(new_rag_tokenizer.generator , UpperCAmelCase_)
self.assertEqual(new_rag_tokenizer.generator.get_vocab() , rag_tokenizer.generator.get_vocab())
@slow
def SCREAMING_SNAKE_CASE_ (self : Dict) ->List[str]:
'''simple docstring'''
lowerCamelCase__: int =RagTokenizer.from_pretrained("facebook/rag-token-nq")
lowerCamelCase__: str =[
"who got the first nobel prize in physics",
"when is the next deadpool movie being released",
"which mode is used for short wave broadcast service",
"who is the owner of reading football club",
"when is the next scandal episode coming out",
"when is the last time the philadelphia won the superbowl",
"what is the most current adobe flash player version",
"how many episodes are there in dragon ball z",
"what is the first step in the evolution of the eye",
"where is gall bladder situated in human body",
"what is the main mineral in lithium batteries",
"who is the president of usa right now",
"where do the greasers live in the outsiders",
"panda is a national animal of which country",
"what is the name of manchester united stadium",
]
lowerCamelCase__: Dict =tokenizer(UpperCAmelCase_)
self.assertIsNotNone(UpperCAmelCase_)
@slow
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: List[Any] =RagTokenizer.from_pretrained("facebook/rag-sequence-nq")
lowerCamelCase__: Optional[int] =[
"who got the first nobel prize in physics",
"when is the next deadpool movie being released",
"which mode is used for short wave broadcast service",
"who is the owner of reading football club",
"when is the next scandal episode coming out",
"when is the last time the philadelphia won the superbowl",
"what is the most current adobe flash player version",
"how many episodes are there in dragon ball z",
"what is the first step in the evolution of the eye",
"where is gall bladder situated in human body",
"what is the main mineral in lithium batteries",
"who is the president of usa right now",
"where do the greasers live in the outsiders",
"panda is a national animal of which country",
"what is the name of manchester united stadium",
]
lowerCamelCase__: List[Any] =tokenizer(UpperCAmelCase_)
self.assertIsNotNone(UpperCAmelCase_)
| 59 |
import unittest
from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin
__A = get_tests_dir("fixtures/test_sentencepiece.model")
@require_sentencepiece
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ):
'''simple docstring'''
lowercase_ = XLMProphetNetTokenizer
lowercase_ = False
lowercase_ = True
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[Any]:
'''simple docstring'''
super().setUp()
# We have a SentencePiece fixture for testing
lowerCamelCase__: Any =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_)
tokenizer.save_pretrained(self.tmpdirname)
def SCREAMING_SNAKE_CASE_ (self : str) ->str:
'''simple docstring'''
lowerCamelCase__: List[Any] ="[PAD]"
lowerCamelCase__: Tuple =0
self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_) , UpperCAmelCase_)
self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_) , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Dict) ->int:
'''simple docstring'''
lowerCamelCase__: List[Any] =list(self.get_tokenizer().get_vocab().keys())
self.assertEqual(vocab_keys[0] , "[PAD]")
self.assertEqual(vocab_keys[1] , "[CLS]")
self.assertEqual(vocab_keys[-1] , "j")
self.assertEqual(len(UpperCAmelCase_) , 1_012)
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]:
'''simple docstring'''
self.assertEqual(self.get_tokenizer().vocab_size , 1_012)
def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_)
lowerCamelCase__: Tuple =tokenizer.tokenize("This is a test")
self.assertListEqual(UpperCAmelCase_ , ["▁This", "▁is", "▁a", "▁t", "est"])
self.assertListEqual(
tokenizer.convert_tokens_to_ids(UpperCAmelCase_) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , )
lowerCamelCase__: Optional[Any] =tokenizer.tokenize("I was born in 92000, and this is falsé.")
self.assertListEqual(
UpperCAmelCase_ , [
SPIECE_UNDERLINE + "I",
SPIECE_UNDERLINE + "was",
SPIECE_UNDERLINE + "b",
"or",
"n",
SPIECE_UNDERLINE + "in",
SPIECE_UNDERLINE + "",
"9",
"2",
"0",
"0",
"0",
",",
SPIECE_UNDERLINE + "and",
SPIECE_UNDERLINE + "this",
SPIECE_UNDERLINE + "is",
SPIECE_UNDERLINE + "f",
"al",
"s",
"é",
".",
] , )
lowerCamelCase__: Any =tokenizer.convert_tokens_to_ids(UpperCAmelCase_)
self.assertListEqual(
UpperCAmelCase_ , [
value + tokenizer.fairseq_offset
for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4]
] , )
lowerCamelCase__: Any =tokenizer.convert_ids_to_tokens(UpperCAmelCase_)
self.assertListEqual(
UpperCAmelCase_ , [
SPIECE_UNDERLINE + "I",
SPIECE_UNDERLINE + "was",
SPIECE_UNDERLINE + "b",
"or",
"n",
SPIECE_UNDERLINE + "in",
SPIECE_UNDERLINE + "",
"[UNK]",
"2",
"0",
"0",
"0",
",",
SPIECE_UNDERLINE + "and",
SPIECE_UNDERLINE + "this",
SPIECE_UNDERLINE + "is",
SPIECE_UNDERLINE + "f",
"al",
"s",
"[UNK]",
".",
] , )
@cached_property
def SCREAMING_SNAKE_CASE_ (self : Any) ->int:
'''simple docstring'''
return XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased")
@slow
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[str]:
'''simple docstring'''
lowerCamelCase__: Optional[int] ="Hello World!"
lowerCamelCase__: Dict =[35_389, 6_672, 49, 2]
self.assertListEqual(UpperCAmelCase_ , self.big_tokenizer.encode(UpperCAmelCase_))
@slow
def SCREAMING_SNAKE_CASE_ (self : int) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__: Any ={"input_ids": [[11_073, 82_783, 18, 26, 82_783, 549, 51_540, 248, 17_209, 1_301, 217, 20, 215_186, 1_325, 147, 17_209, 1_301, 217, 20, 56_370, 53, 122_020, 20, 16_477, 27, 87_355, 4_548, 20, 4_728, 78_392, 17, 159_969, 18, 26, 24_491, 629, 15, 538, 22_704, 5_439, 15, 2_788, 24_491, 9_885, 15, 43_534, 605, 15, 814, 18_403, 33_200, 29, 15, 43_534, 24_458, 12_410, 111, 24_966, 83_669, 9_637, 144_068, 26, 850, 22_346, 27, 147, 24_966, 83_669, 83_490, 26, 39_113, 735, 27, 689, 656, 2_800, 1_339, 4_600, 53, 122_020, 115_785, 34, 816, 1_339, 46_887, 18, 147, 53_905, 1_951, 42_238, 41_170, 17_732, 834, 436, 15, 27_523, 98_733, 217, 147, 5_542, 4_981, 930, 17_347, 16, 2], [20_091, 629, 94, 82_786, 58, 490, 20, 1_528, 84, 53_905, 344, 80_592, 110_128, 18_822, 5_267, 1_306, 62, 152_537, 308, 7_997, 401, 124_427, 549, 35_442, 225, 109, 15_055, 25_748, 147, 7_119, 43_712, 34, 767, 135_366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63_784, 119_466, 17, 147_808, 88_214, 18, 656, 81, 32, 3_296, 10_280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=UpperCAmelCase_ , model_name="microsoft/xprophetnet-large-wiki100-cased" , revision="1acad1643ddd54a44df6a1b797ada8373685d90e" , )
| 59 | 1 |
from math import pow
def lowerCAmelCase_ ( __a , __a , __a , __a , __a , ) -> tuple[int, int]:
"""simple docstring"""
if current_sum == needed_sum:
# If the sum of the powers is equal to needed_sum, then we have a solution.
solutions_count += 1
return current_sum, solutions_count
lowerCamelCase__: Tuple =int(pow(__a , __a ) )
if current_sum + i_to_n <= needed_sum:
# If the sum of the powers is less than needed_sum, then continue adding powers.
current_sum += i_to_n
lowerCamelCase__ , lowerCamelCase__: Optional[Any] =backtrack(
__a , __a , current_number + 1 , __a , __a )
current_sum -= i_to_n
if i_to_n < needed_sum:
# If the power of i is less than needed_sum, then try with the next power.
lowerCamelCase__ , lowerCamelCase__: Tuple =backtrack(
__a , __a , current_number + 1 , __a , __a )
return current_sum, solutions_count
def lowerCAmelCase_ ( __a , __a ) -> int:
"""simple docstring"""
if not (1 <= needed_sum <= 1000 and 2 <= power <= 10):
raise ValueError(
"Invalid input\n"
"needed_sum must be between 1 and 1000, power between 2 and 10." )
return backtrack(__a , __a , 1 , 0 , 0 )[1] # Return the solutions_count
if __name__ == "__main__":
import doctest
doctest.testmod()
| 59 |
import os
import shutil
import tempfile
import unittest
import numpy as np
from transformers import AutoTokenizer, BarkProcessor
from transformers.testing_utils import require_torch, slow
@require_torch
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->str:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] ="ylacombe/bark-small"
lowerCamelCase__: Tuple =tempfile.mkdtemp()
lowerCamelCase__: Tuple ="en_speaker_1"
lowerCamelCase__: Optional[int] ="This is a test string"
lowerCamelCase__: List[str] ="speaker_embeddings_path.json"
lowerCamelCase__: int ="speaker_embeddings"
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , **UpperCAmelCase_ : Any) ->Tuple:
'''simple docstring'''
return AutoTokenizer.from_pretrained(self.checkpoint , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Union[str, Any]:
'''simple docstring'''
shutil.rmtree(self.tmpdirname)
def SCREAMING_SNAKE_CASE_ (self : int) ->Any:
'''simple docstring'''
lowerCamelCase__: List[Any] =self.get_tokenizer()
lowerCamelCase__: List[str] =BarkProcessor(tokenizer=UpperCAmelCase_)
processor.save_pretrained(self.tmpdirname)
lowerCamelCase__: Dict =BarkProcessor.from_pretrained(self.tmpdirname)
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab())
@slow
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Tuple =BarkProcessor.from_pretrained(
pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , )
processor.save_pretrained(
self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , )
lowerCamelCase__: Dict =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)")
lowerCamelCase__: Any =BarkProcessor.from_pretrained(
self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="(BOS)" , eos_token="(EOS)" , )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab())
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->int:
'''simple docstring'''
lowerCamelCase__: Any =BarkProcessor.from_pretrained(
pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , )
lowerCamelCase__: List[str] =35
lowerCamelCase__: Optional[Any] =2
lowerCamelCase__: Optional[Any] =8
lowerCamelCase__: Optional[int] ={
"semantic_prompt": np.ones(UpperCAmelCase_),
"coarse_prompt": np.ones((nb_codebooks_coarse, seq_len)),
"fine_prompt": np.ones((nb_codebooks_total, seq_len)),
}
# test providing already loaded voice_preset
lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=UpperCAmelCase_)
lowerCamelCase__: int =inputs["history_prompt"]
for key in voice_preset:
self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist())
# test loading voice preset from npz file
lowerCamelCase__: Union[str, Any] =os.path.join(self.tmpdirname , "file.npz")
np.savez(UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: Tuple =processor(text=self.input_string , voice_preset=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =inputs["history_prompt"]
for key in voice_preset:
self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist())
# test loading voice preset from the hub
lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=self.voice_preset)
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__: str =self.get_tokenizer()
lowerCamelCase__: Dict =BarkProcessor(tokenizer=UpperCAmelCase_)
lowerCamelCase__: List[Any] =processor(text=self.input_string)
lowerCamelCase__: Optional[int] =tokenizer(
self.input_string , padding="max_length" , max_length=256 , add_special_tokens=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist())
| 59 | 1 |
import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import cached_download, hf_hub_url
from PIL import Image
from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor
from transformers.utils import logging
logging.set_verbosity_info()
__A = logging.get_logger(__name__)
def lowerCAmelCase_ ( __a ) -> int:
"""simple docstring"""
lowerCamelCase__: Any =DPTConfig()
if "large" in checkpoint_url:
lowerCamelCase__: Optional[int] =1024
lowerCamelCase__: Any =4096
lowerCamelCase__: Optional[int] =24
lowerCamelCase__: Tuple =16
lowerCamelCase__: Dict =[5, 11, 17, 23]
lowerCamelCase__: List[Any] =[256, 512, 1024, 1024]
lowerCamelCase__: str =(1, 384, 384)
if "ade" in checkpoint_url:
lowerCamelCase__: int =True
lowerCamelCase__: str =150
lowerCamelCase__: str ="huggingface/label-files"
lowerCamelCase__: List[str] ="ade20k-id2label.json"
lowerCamelCase__: Optional[int] =json.load(open(cached_download(hf_hub_url(__a , __a , repo_type="dataset" ) ) , "r" ) )
lowerCamelCase__: str ={int(__a ): v for k, v in idalabel.items()}
lowerCamelCase__: Optional[Any] =idalabel
lowerCamelCase__: Tuple ={v: k for k, v in idalabel.items()}
lowerCamelCase__: int =[1, 150, 480, 480]
return config, expected_shape
def lowerCAmelCase_ ( __a ) -> List[Any]:
"""simple docstring"""
lowerCamelCase__: int =["pretrained.model.head.weight", "pretrained.model.head.bias"]
for k in ignore_keys:
state_dict.pop(__a , __a )
def lowerCAmelCase_ ( __a ) -> Dict:
"""simple docstring"""
if (
"pretrained.model" in name
and "cls_token" not in name
and "pos_embed" not in name
and "patch_embed" not in name
):
lowerCamelCase__: Any =name.replace("pretrained.model" , "dpt.encoder" )
if "pretrained.model" in name:
lowerCamelCase__: Union[str, Any] =name.replace("pretrained.model" , "dpt.embeddings" )
if "patch_embed" in name:
lowerCamelCase__: List[str] =name.replace("patch_embed" , "patch_embeddings" )
if "pos_embed" in name:
lowerCamelCase__: List[str] =name.replace("pos_embed" , "position_embeddings" )
if "attn.proj" in name:
lowerCamelCase__: str =name.replace("attn.proj" , "attention.output.dense" )
if "proj" in name and "project" not in name:
lowerCamelCase__: Any =name.replace("proj" , "projection" )
if "blocks" in name:
lowerCamelCase__: Tuple =name.replace("blocks" , "layer" )
if "mlp.fc1" in name:
lowerCamelCase__: List[Any] =name.replace("mlp.fc1" , "intermediate.dense" )
if "mlp.fc2" in name:
lowerCamelCase__: Any =name.replace("mlp.fc2" , "output.dense" )
if "norm1" in name:
lowerCamelCase__: Any =name.replace("norm1" , "layernorm_before" )
if "norm2" in name:
lowerCamelCase__: List[Any] =name.replace("norm2" , "layernorm_after" )
if "scratch.output_conv" in name:
lowerCamelCase__: int =name.replace("scratch.output_conv" , "head" )
if "scratch" in name:
lowerCamelCase__: List[Any] =name.replace("scratch" , "neck" )
if "layer1_rn" in name:
lowerCamelCase__: Dict =name.replace("layer1_rn" , "convs.0" )
if "layer2_rn" in name:
lowerCamelCase__: Optional[int] =name.replace("layer2_rn" , "convs.1" )
if "layer3_rn" in name:
lowerCamelCase__: Union[str, Any] =name.replace("layer3_rn" , "convs.2" )
if "layer4_rn" in name:
lowerCamelCase__: Optional[Any] =name.replace("layer4_rn" , "convs.3" )
if "refinenet" in name:
lowerCamelCase__: int =int(name[len("neck.refinenet" ) : len("neck.refinenet" ) + 1] )
# tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3
lowerCamelCase__: Optional[Any] =name.replace(F"""refinenet{layer_idx}""" , F"""fusion_stage.layers.{abs(layer_idx-4 )}""" )
if "out_conv" in name:
lowerCamelCase__: Optional[int] =name.replace("out_conv" , "projection" )
if "resConfUnit1" in name:
lowerCamelCase__: Optional[int] =name.replace("resConfUnit1" , "residual_layer1" )
if "resConfUnit2" in name:
lowerCamelCase__: Union[str, Any] =name.replace("resConfUnit2" , "residual_layer2" )
if "conv1" in name:
lowerCamelCase__: Dict =name.replace("conv1" , "convolution1" )
if "conv2" in name:
lowerCamelCase__: Dict =name.replace("conv2" , "convolution2" )
# readout blocks
if "pretrained.act_postprocess1.0.project.0" in name:
lowerCamelCase__: int =name.replace("pretrained.act_postprocess1.0.project.0" , "neck.reassemble_stage.readout_projects.0.0" )
if "pretrained.act_postprocess2.0.project.0" in name:
lowerCamelCase__: Union[str, Any] =name.replace("pretrained.act_postprocess2.0.project.0" , "neck.reassemble_stage.readout_projects.1.0" )
if "pretrained.act_postprocess3.0.project.0" in name:
lowerCamelCase__: Optional[int] =name.replace("pretrained.act_postprocess3.0.project.0" , "neck.reassemble_stage.readout_projects.2.0" )
if "pretrained.act_postprocess4.0.project.0" in name:
lowerCamelCase__: Optional[int] =name.replace("pretrained.act_postprocess4.0.project.0" , "neck.reassemble_stage.readout_projects.3.0" )
# resize blocks
if "pretrained.act_postprocess1.3" in name:
lowerCamelCase__: Tuple =name.replace("pretrained.act_postprocess1.3" , "neck.reassemble_stage.layers.0.projection" )
if "pretrained.act_postprocess1.4" in name:
lowerCamelCase__: Union[str, Any] =name.replace("pretrained.act_postprocess1.4" , "neck.reassemble_stage.layers.0.resize" )
if "pretrained.act_postprocess2.3" in name:
lowerCamelCase__: List[str] =name.replace("pretrained.act_postprocess2.3" , "neck.reassemble_stage.layers.1.projection" )
if "pretrained.act_postprocess2.4" in name:
lowerCamelCase__: List[str] =name.replace("pretrained.act_postprocess2.4" , "neck.reassemble_stage.layers.1.resize" )
if "pretrained.act_postprocess3.3" in name:
lowerCamelCase__: Dict =name.replace("pretrained.act_postprocess3.3" , "neck.reassemble_stage.layers.2.projection" )
if "pretrained.act_postprocess4.3" in name:
lowerCamelCase__: str =name.replace("pretrained.act_postprocess4.3" , "neck.reassemble_stage.layers.3.projection" )
if "pretrained.act_postprocess4.4" in name:
lowerCamelCase__: List[Any] =name.replace("pretrained.act_postprocess4.4" , "neck.reassemble_stage.layers.3.resize" )
if "pretrained" in name:
lowerCamelCase__: Union[str, Any] =name.replace("pretrained" , "dpt" )
if "bn" in name:
lowerCamelCase__: Union[str, Any] =name.replace("bn" , "batch_norm" )
if "head" in name:
lowerCamelCase__: int =name.replace("head" , "head.head" )
if "encoder.norm" in name:
lowerCamelCase__: Union[str, Any] =name.replace("encoder.norm" , "layernorm" )
if "auxlayer" in name:
lowerCamelCase__: Optional[Any] =name.replace("auxlayer" , "auxiliary_head.head" )
return name
def lowerCAmelCase_ ( __a , __a ) -> int:
"""simple docstring"""
for i in range(config.num_hidden_layers ):
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
lowerCamelCase__: List[Any] =state_dict.pop(F"""dpt.encoder.layer.{i}.attn.qkv.weight""" )
lowerCamelCase__: Optional[Any] =state_dict.pop(F"""dpt.encoder.layer.{i}.attn.qkv.bias""" )
# next, add query, keys and values (in that order) to the state dict
lowerCamelCase__: Dict =in_proj_weight[: config.hidden_size, :]
lowerCamelCase__: Union[str, Any] =in_proj_bias[: config.hidden_size]
lowerCamelCase__: Any =in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
lowerCamelCase__: List[Any] =in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
lowerCamelCase__: List[str] =in_proj_weight[
-config.hidden_size :, :
]
lowerCamelCase__: Union[str, Any] =in_proj_bias[-config.hidden_size :]
def lowerCAmelCase_ ( ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase__: str ="http://images.cocodataset.org/val2017/000000039769.jpg"
lowerCamelCase__: Tuple =Image.open(requests.get(__a , stream=__a ).raw )
return im
@torch.no_grad()
def lowerCAmelCase_ ( __a , __a , __a , __a ) -> List[Any]:
"""simple docstring"""
lowerCamelCase__ , lowerCamelCase__: Optional[Any] =get_dpt_config(__a )
# load original state_dict from URL
lowerCamelCase__: int =torch.hub.load_state_dict_from_url(__a , map_location="cpu" )
# remove certain keys
remove_ignore_keys_(__a )
# rename keys
for key in state_dict.copy().keys():
lowerCamelCase__: Optional[Any] =state_dict.pop(__a )
lowerCamelCase__: Optional[Any] =val
# read in qkv matrices
read_in_q_k_v(__a , __a )
# load HuggingFace model
lowerCamelCase__: Any =DPTForSemanticSegmentation(__a ) if "ade" in checkpoint_url else DPTForDepthEstimation(__a )
model.load_state_dict(__a )
model.eval()
# Check outputs on an image
lowerCamelCase__: int =480 if "ade" in checkpoint_url else 384
lowerCamelCase__: Union[str, Any] =DPTImageProcessor(size=__a )
lowerCamelCase__: Optional[Any] =prepare_img()
lowerCamelCase__: Optional[Any] =image_processor(__a , return_tensors="pt" )
# forward pass
lowerCamelCase__: Dict =model(**__a ).logits if "ade" in checkpoint_url else model(**__a ).predicted_depth
# Assert logits
lowerCamelCase__: List[str] =torch.tensor([[6.3_1_9_9, 6.3_6_2_9, 6.4_1_4_8], [6.3_8_5_0, 6.3_6_1_5, 6.4_1_6_6], [6.3_5_1_9, 6.3_1_7_6, 6.3_5_7_5]] )
if "ade" in checkpoint_url:
lowerCamelCase__: Dict =torch.tensor([[4.0_4_8_0, 4.2_4_2_0, 4.4_3_6_0], [4.3_1_2_4, 4.5_6_9_3, 4.8_2_6_1], [4.5_7_6_8, 4.8_9_6_5, 5.2_1_6_3]] )
assert outputs.shape == torch.Size(__a )
assert (
torch.allclose(outputs[0, 0, :3, :3] , __a , atol=1e-4 )
if "ade" in checkpoint_url
else torch.allclose(outputs[0, :3, :3] , __a )
)
Path(__a ).mkdir(exist_ok=__a )
print(F"""Saving model to {pytorch_dump_folder_path}""" )
model.save_pretrained(__a )
print(F"""Saving image processor to {pytorch_dump_folder_path}""" )
image_processor.save_pretrained(__a )
if push_to_hub:
print("Pushing model to hub..." )
model.push_to_hub(
repo_path_or_name=Path(__a , __a ) , organization="nielsr" , commit_message="Add model" , use_temp_dir=__a , )
image_processor.push_to_hub(
repo_path_or_name=Path(__a , __a ) , organization="nielsr" , commit_message="Add image processor" , use_temp_dir=__a , )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--checkpoint_url",
default="https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt",
type=str,
help="URL of the original DPT checkpoint you'd like to convert.",
)
parser.add_argument(
"--pytorch_dump_folder_path",
default=None,
type=str,
required=True,
help="Path to the output PyTorch model directory.",
)
parser.add_argument(
"--push_to_hub",
action="store_true",
)
parser.add_argument(
"--model_name",
default="dpt-large",
type=str,
help="Name of the model, in case you're pushing to the hub.",
)
__A = parser.parse_args()
convert_dpt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
| 59 |
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = ["image_processor", "tokenizer"]
lowercase_ = "CLIPImageProcessor"
lowercase_ = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast")
def __init__(self : List[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : List[str]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =None
if "feature_extractor" in kwargs:
warnings.warn(
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
" instead." , UpperCAmelCase_ , )
lowerCamelCase__: int =kwargs.pop("feature_extractor")
lowerCamelCase__: int =image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError("You need to specify an `image_processor`.")
if tokenizer is None:
raise ValueError("You need to specify a `tokenizer`.")
super().__init__(UpperCAmelCase_ , UpperCAmelCase_)
def __call__(self : List[Any] , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : int=None , **UpperCAmelCase_ : Any) ->Union[str, Any]:
'''simple docstring'''
if text is None and images is None:
raise ValueError("You have to specify either text or images. Both cannot be none.")
if text is not None:
lowerCamelCase__: List[Any] =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if images is not None:
lowerCamelCase__: int =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if text is not None and images is not None:
lowerCamelCase__: str =image_features.pixel_values
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[Any]) ->Dict:
'''simple docstring'''
return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Any) ->Optional[Any]:
'''simple docstring'''
return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_)
@property
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =self.tokenizer.model_input_names
lowerCamelCase__: str =self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
| 59 | 1 |
import copy
from ...configuration_utils import PretrainedConfig
from ...utils import add_start_docstrings
__A = R"\n [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and\n can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.\n\n Args:\n title_sep (`str`, *optional*, defaults to `\" / \"`):\n Separator inserted between the title and the text of the retrieved document when calling [`RagRetriever`].\n doc_sep (`str`, *optional*, defaults to `\" // \"`):\n Separator inserted between the text of the retrieved document and the original input when calling\n [`RagRetriever`].\n n_docs (`int`, *optional*, defaults to 5):\n Number of documents to retrieve.\n max_combined_length (`int`, *optional*, defaults to 300):\n Max length of contextualized input returned by [`~RagRetriever.__call__`].\n retrieval_vector_size (`int`, *optional*, defaults to 768):\n Dimensionality of the document embeddings indexed by [`RagRetriever`].\n retrieval_batch_size (`int`, *optional*, defaults to 8):\n Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated\n [`RagRetriever`].\n dataset (`str`, *optional*, defaults to `\"wiki_dpr\"`):\n A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids\n using `datasets.list_datasets()`).\n dataset_split (`str`, *optional*, defaults to `\"train\"`)\n Which split of the `dataset` to load.\n index_name (`str`, *optional*, defaults to `\"compressed\"`)\n The index name of the index associated with the `dataset`. One can choose between `\"legacy\"`, `\"exact\"` and\n `\"compressed\"`.\n index_path (`str`, *optional*)\n The path to the serialized faiss index on disk.\n passages_path (`str`, *optional*):\n A path to text passages compatible with the faiss index. Required if using\n [`~models.rag.retrieval_rag.LegacyIndex`]\n use_dummy_dataset (`bool`, *optional*, defaults to `False`)\n Whether to load a \"dummy\" variant of the dataset specified by `dataset`.\n label_smoothing (`float`, *optional*, defaults to 0.0):\n Only relevant if `return_loss` is set to `True`. Controls the `epsilon` parameter value for label smoothing\n in the loss calculation. If set to 0, no label smoothing is performed.\n do_marginalize (`bool`, *optional*, defaults to `False`):\n If `True`, the logits are marginalized over all documents by making use of\n `torch.nn.functional.log_softmax`.\n reduce_loss (`bool`, *optional*, defaults to `False`):\n Whether or not to reduce the NLL loss using the `torch.Tensor.sum` operation.\n do_deduplication (`bool`, *optional*, defaults to `True`):\n Whether or not to deduplicate the generations from different context documents for a given input. Has to be\n set to `False` if used while training with distributed backend.\n exclude_bos_score (`bool`, *optional*, defaults to `False`):\n Whether or not to disregard the BOS token when computing the loss.\n output_retrieved(`bool`, *optional*, defaults to `False`):\n If set to `True`, `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and\n `context_attention_mask` are returned. See returned tensors for more detail.\n use_cache (`bool`, *optional*, defaults to `True`):\n Whether or not the model should return the last key/values attentions (not used by all models).\n forced_eos_token_id (`int`, *optional*):\n The id of the token to force as the last generated token when `max_length` is reached. Usually set to\n `eos_token_id`.\n"
@add_start_docstrings(__SCREAMING_SNAKE_CASE )
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = "rag"
lowercase_ = True
def __init__(self : str , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : int=True , UpperCAmelCase_ : str=None , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Union[str, Any]=" / " , UpperCAmelCase_ : Dict=" // " , UpperCAmelCase_ : Union[str, Any]=5 , UpperCAmelCase_ : Any=300 , UpperCAmelCase_ : Optional[Any]=768 , UpperCAmelCase_ : Optional[int]=8 , UpperCAmelCase_ : int="wiki_dpr" , UpperCAmelCase_ : Optional[Any]="train" , UpperCAmelCase_ : Optional[Any]="compressed" , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : Union[str, Any]=False , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : Optional[Any]=0.0 , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : Dict=False , UpperCAmelCase_ : Optional[Any]=False , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[str]=None , **UpperCAmelCase_ : Dict , ) ->int:
'''simple docstring'''
super().__init__(
bos_token_id=UpperCAmelCase_ , pad_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , decoder_start_token_id=UpperCAmelCase_ , forced_eos_token_id=UpperCAmelCase_ , is_encoder_decoder=UpperCAmelCase_ , prefix=UpperCAmelCase_ , vocab_size=UpperCAmelCase_ , **UpperCAmelCase_ , )
assert (
"question_encoder" in kwargs and "generator" in kwargs
), "Config has to be initialized with question_encoder and generator config"
lowerCamelCase__: Optional[int] =kwargs.pop("question_encoder")
lowerCamelCase__: int =question_encoder_config.pop("model_type")
lowerCamelCase__: List[str] =kwargs.pop("generator")
lowerCamelCase__: Optional[Any] =decoder_config.pop("model_type")
from ..auto.configuration_auto import AutoConfig
lowerCamelCase__: int =AutoConfig.for_model(UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =AutoConfig.for_model(UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =reduce_loss
lowerCamelCase__: str =label_smoothing
lowerCamelCase__: int =exclude_bos_score
lowerCamelCase__: int =do_marginalize
lowerCamelCase__: Dict =title_sep
lowerCamelCase__: List[Any] =doc_sep
lowerCamelCase__: Optional[int] =n_docs
lowerCamelCase__: str =max_combined_length
lowerCamelCase__: Optional[int] =dataset
lowerCamelCase__: Any =dataset_split
lowerCamelCase__: Any =index_name
lowerCamelCase__: Dict =retrieval_vector_size
lowerCamelCase__: str =retrieval_batch_size
lowerCamelCase__: int =passages_path
lowerCamelCase__: Tuple =index_path
lowerCamelCase__: Dict =use_dummy_dataset
lowerCamelCase__: Optional[Any] =output_retrieved
lowerCamelCase__: Any =do_deduplication
lowerCamelCase__: str =use_cache
if self.forced_eos_token_id is None:
lowerCamelCase__: Optional[int] =getattr(self.generator , "forced_eos_token_id" , UpperCAmelCase_)
@classmethod
def SCREAMING_SNAKE_CASE_ (cls : List[str] , UpperCAmelCase_ : PretrainedConfig , UpperCAmelCase_ : PretrainedConfig , **UpperCAmelCase_ : int) ->PretrainedConfig:
'''simple docstring'''
return cls(question_encoder=question_encoder_config.to_dict() , generator=generator_config.to_dict() , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str:
'''simple docstring'''
lowerCamelCase__: List[str] =copy.deepcopy(self.__dict__)
lowerCamelCase__: str =self.question_encoder.to_dict()
lowerCamelCase__: Union[str, Any] =self.generator.to_dict()
lowerCamelCase__: Tuple =self.__class__.model_type
return output
| 59 |
from datetime import datetime
import matplotlib.pyplot as plt
import torch
def lowerCAmelCase_ ( __a ) -> Any:
"""simple docstring"""
for param in module.parameters():
lowerCamelCase__: Tuple =False
def lowerCAmelCase_ ( ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase__: List[str] ="cuda" if torch.cuda.is_available() else "cpu"
if torch.backends.mps.is_available() and torch.backends.mps.is_built():
lowerCamelCase__: str ="mps"
if device == "mps":
print(
"WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch"
" errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues"
" with generations." )
return device
def lowerCAmelCase_ ( __a ) -> List[str]:
"""simple docstring"""
lowerCamelCase__: Union[str, Any] =plt.imshow(__a )
fig.axes.get_xaxis().set_visible(__a )
fig.axes.get_yaxis().set_visible(__a )
plt.show()
def lowerCAmelCase_ ( ) -> Optional[Any]:
"""simple docstring"""
lowerCamelCase__: List[str] =datetime.now()
lowerCamelCase__: str =current_time.strftime("%H:%M:%S" )
return timestamp
| 59 | 1 |
from __future__ import annotations
def lowerCAmelCase_ ( __a ) -> bool:
"""simple docstring"""
lowerCamelCase__: Union[str, Any] =len(__a )
# We need to create solution object to save path.
lowerCamelCase__: Optional[Any] =[[0 for _ in range(__a )] for _ in range(__a )]
lowerCamelCase__: int =run_maze(__a , 0 , 0 , __a )
if solved:
print("\n".join(str(__a ) for row in solutions ) )
else:
print("No solution exists!" )
return solved
def lowerCAmelCase_ ( __a , __a , __a , __a ) -> bool:
"""simple docstring"""
lowerCamelCase__: List[str] =len(__a )
# Final check point.
if i == j == (size - 1):
lowerCamelCase__: List[str] =1
return True
lowerCamelCase__: Optional[int] =(not i < 0) and (not j < 0) # Check lower bounds
lowerCamelCase__: Dict =(i < size) and (j < size) # Check upper bounds
if lower_flag and upper_flag:
# check for already visited and block points.
lowerCamelCase__: Optional[Any] =(not solutions[i][j]) and (not maze[i][j])
if block_flag:
# check visited
lowerCamelCase__: Optional[Any] =1
# check for directions
if (
run_maze(__a , i + 1 , __a , __a )
or run_maze(__a , __a , j + 1 , __a )
or run_maze(__a , i - 1 , __a , __a )
or run_maze(__a , __a , j - 1 , __a )
):
return True
lowerCamelCase__: List[Any] =0
return False
return False
if __name__ == "__main__":
import doctest
doctest.testmod()
| 59 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
__A = {
"configuration_pix2struct": [
"PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP",
"Pix2StructConfig",
"Pix2StructTextConfig",
"Pix2StructVisionConfig",
],
"processing_pix2struct": ["Pix2StructProcessor"],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = ["Pix2StructImageProcessor"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
"PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST",
"Pix2StructPreTrainedModel",
"Pix2StructForConditionalGeneration",
"Pix2StructVisionModel",
"Pix2StructTextModel",
]
if TYPE_CHECKING:
from .configuration_pixastruct import (
PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP,
PixaStructConfig,
PixaStructTextConfig,
PixaStructVisionConfig,
)
from .processing_pixastruct import PixaStructProcessor
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .image_processing_pixastruct import PixaStructImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_pixastruct import (
PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST,
PixaStructForConditionalGeneration,
PixaStructPreTrainedModel,
PixaStructTextModel,
PixaStructVisionModel,
)
else:
import sys
__A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 59 | 1 |
import os
import warnings
from typing import List, Optional
from ...tokenization_utils_base import BatchEncoding
from ...utils import logging
from .configuration_rag import RagConfig
__A = logging.get_logger(__name__)
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__(self : Tuple , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str) ->List[str]:
'''simple docstring'''
lowerCamelCase__: List[str] =question_encoder
lowerCamelCase__: List[str] =generator
lowerCamelCase__: List[Any] =self.question_encoder
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Union[str, Any]) ->List[str]:
'''simple docstring'''
if os.path.isfile(UpperCAmelCase_):
raise ValueError(F"""Provided path ({save_directory}) should be a directory, not a file""")
os.makedirs(UpperCAmelCase_ , exist_ok=UpperCAmelCase_)
lowerCamelCase__: Optional[int] =os.path.join(UpperCAmelCase_ , "question_encoder_tokenizer")
lowerCamelCase__: Optional[Any] =os.path.join(UpperCAmelCase_ , "generator_tokenizer")
self.question_encoder.save_pretrained(UpperCAmelCase_)
self.generator.save_pretrained(UpperCAmelCase_)
@classmethod
def SCREAMING_SNAKE_CASE_ (cls : int , UpperCAmelCase_ : int , **UpperCAmelCase_ : Union[str, Any]) ->List[Any]:
'''simple docstring'''
from ..auto.tokenization_auto import AutoTokenizer
lowerCamelCase__: Tuple =kwargs.pop("config" , UpperCAmelCase_)
if config is None:
lowerCamelCase__: Optional[int] =RagConfig.from_pretrained(UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =AutoTokenizer.from_pretrained(
UpperCAmelCase_ , config=config.question_encoder , subfolder="question_encoder_tokenizer")
lowerCamelCase__: int =AutoTokenizer.from_pretrained(
UpperCAmelCase_ , config=config.generator , subfolder="generator_tokenizer")
return cls(question_encoder=UpperCAmelCase_ , generator=UpperCAmelCase_)
def __call__(self : Union[str, Any] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : Union[str, Any]) ->int:
'''simple docstring'''
return self.current_tokenizer(*UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[int]) ->Dict:
'''simple docstring'''
return self.generator.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Tuple) ->Any:
'''simple docstring'''
return self.generator.decode(*UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : int) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Any =self.question_encoder
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__: List[Any] =self.generator
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[List[str]] = None , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : str = "longest" , UpperCAmelCase_ : str = None , UpperCAmelCase_ : bool = True , **UpperCAmelCase_ : Union[str, Any] , ) ->BatchEncoding:
'''simple docstring'''
warnings.warn(
"`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the "
"regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` "
"context manager to prepare your targets. See the documentation of your specific tokenizer for more "
"details" , UpperCAmelCase_ , )
if max_length is None:
lowerCamelCase__: List[str] =self.current_tokenizer.model_max_length
lowerCamelCase__: List[Any] =self(
UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , max_length=UpperCAmelCase_ , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ , **UpperCAmelCase_ , )
if tgt_texts is None:
return model_inputs
# Process tgt_texts
if max_target_length is None:
lowerCamelCase__: Optional[int] =self.current_tokenizer.model_max_length
lowerCamelCase__: List[Any] =self(
text_target=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , padding=UpperCAmelCase_ , max_length=UpperCAmelCase_ , truncation=UpperCAmelCase_ , **UpperCAmelCase_ , )
lowerCamelCase__: Union[str, Any] =labels["input_ids"]
return model_inputs
| 59 |
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_distilbert import DistilBertTokenizer
__A = logging.get_logger(__name__)
__A = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
__A = {
"vocab_file": {
"distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt",
"distilbert-base-uncased-distilled-squad": (
"https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt"
),
"distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt",
"distilbert-base-cased-distilled-squad": (
"https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt"
),
"distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt",
"distilbert-base-multilingual-cased": (
"https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt"
),
},
"tokenizer_file": {
"distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json",
"distilbert-base-uncased-distilled-squad": (
"https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json"
),
"distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json",
"distilbert-base-cased-distilled-squad": (
"https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json"
),
"distilbert-base-german-cased": (
"https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json"
),
"distilbert-base-multilingual-cased": (
"https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json"
),
},
}
__A = {
"distilbert-base-uncased": 512,
"distilbert-base-uncased-distilled-squad": 512,
"distilbert-base-cased": 512,
"distilbert-base-cased-distilled-squad": 512,
"distilbert-base-german-cased": 512,
"distilbert-base-multilingual-cased": 512,
}
__A = {
"distilbert-base-uncased": {"do_lower_case": True},
"distilbert-base-uncased-distilled-squad": {"do_lower_case": True},
"distilbert-base-cased": {"do_lower_case": False},
"distilbert-base-cased-distilled-squad": {"do_lower_case": False},
"distilbert-base-german-cased": {"do_lower_case": False},
"distilbert-base-multilingual-cased": {"do_lower_case": False},
}
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = VOCAB_FILES_NAMES
lowercase_ = PRETRAINED_VOCAB_FILES_MAP
lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowercase_ = PRETRAINED_INIT_CONFIGURATION
lowercase_ = ["input_ids", "attention_mask"]
lowercase_ = DistilBertTokenizer
def __init__(self : Tuple , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[Any]="[UNK]" , UpperCAmelCase_ : Dict="[SEP]" , UpperCAmelCase_ : Dict="[PAD]" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[str]=None , **UpperCAmelCase_ : List[str] , ) ->str:
'''simple docstring'''
super().__init__(
UpperCAmelCase_ , tokenizer_file=UpperCAmelCase_ , do_lower_case=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , tokenize_chinese_chars=UpperCAmelCase_ , strip_accents=UpperCAmelCase_ , **UpperCAmelCase_ , )
lowerCamelCase__: Union[str, Any] =json.loads(self.backend_tokenizer.normalizer.__getstate__())
if (
normalizer_state.get("lowercase" , UpperCAmelCase_) != do_lower_case
or normalizer_state.get("strip_accents" , UpperCAmelCase_) != strip_accents
or normalizer_state.get("handle_chinese_chars" , UpperCAmelCase_) != tokenize_chinese_chars
):
lowerCamelCase__: List[str] =getattr(UpperCAmelCase_ , normalizer_state.pop("type"))
lowerCamelCase__: Optional[int] =do_lower_case
lowerCamelCase__: int =strip_accents
lowerCamelCase__: Any =tokenize_chinese_chars
lowerCamelCase__: Any =normalizer_class(**UpperCAmelCase_)
lowerCamelCase__: str =do_lower_case
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any]=None) ->Dict:
'''simple docstring'''
lowerCamelCase__: str =[self.cls_token_id] + token_ids_a + [self.sep_token_id]
if token_ids_a:
output += token_ids_a + [self.sep_token_id]
return output
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None) ->List[int]:
'''simple docstring'''
lowerCamelCase__: str =[self.sep_token_id]
lowerCamelCase__: str =[self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep) * [0]
return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1]
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None) ->Tuple[str]:
'''simple docstring'''
lowerCamelCase__: str =self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_)
return tuple(UpperCAmelCase_)
| 59 | 1 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
__A = {
"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:
__A = ["BlenderbotSmallTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
"BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST",
"BlenderbotSmallForCausalLM",
"BlenderbotSmallForConditionalGeneration",
"BlenderbotSmallModel",
"BlenderbotSmallPreTrainedModel",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
"TFBlenderbotSmallForConditionalGeneration",
"TFBlenderbotSmallModel",
"TFBlenderbotSmallPreTrainedModel",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
"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
__A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 59 |
import operator as op
def lowerCAmelCase_ ( __a ) -> Tuple:
"""simple docstring"""
lowerCamelCase__: Optional[Any] =[]
lowerCamelCase__: Tuple =lambda __a , __a : int(x / y ) # noqa: E731 integer division operation
lowerCamelCase__: Tuple ={
"^": op.pow,
"*": op.mul,
"/": div,
"+": op.add,
"-": op.sub,
} # operators & their respective operation
# print table header
print("Symbol".center(8 ) , "Action".center(12 ) , "Stack" , sep=" | " )
print("-" * (30 + len(__a )) )
for x in post_fix:
if x.isdigit(): # if x in digit
stack.append(__a ) # append x to stack
# output in tabular format
print(x.rjust(8 ) , ("push(" + x + ")").ljust(12 ) , ",".join(__a ) , sep=" | " )
else:
lowerCamelCase__: List[Any] =stack.pop() # pop stack
# output in tabular format
print("".rjust(8 ) , ("pop(" + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " )
lowerCamelCase__: Optional[Any] =stack.pop() # pop stack
# output in tabular format
print("".rjust(8 ) , ("pop(" + a + ")").ljust(12 ) , ",".join(__a ) , sep=" | " )
stack.append(
str(opr[x](int(__a ) , int(__a ) ) ) ) # evaluate the 2 values popped from stack & push result to stack
# output in tabular format
print(
x.rjust(8 ) , ("push(" + a + x + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " , )
return int(stack[0] )
if __name__ == "__main__":
__A = input("\n\nEnter a Postfix Equation (space separated) = ").split(" ")
print("\n\tResult = ", solve(Postfix))
| 59 | 1 |
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 _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = 42
class _SCREAMING_SNAKE_CASE ( nn.Module ):
'''simple docstring'''
def __init__(self : List[Any] , UpperCAmelCase_ : Union[str, Any]=3 , UpperCAmelCase_ : Union[str, Any]=3 , UpperCAmelCase_ : Tuple=("DownEncoderBlock2D",) , UpperCAmelCase_ : Optional[int]=(64,) , UpperCAmelCase_ : Dict=2 , UpperCAmelCase_ : Dict=32 , UpperCAmelCase_ : int="silu" , UpperCAmelCase_ : str=True , ) ->str:
'''simple docstring'''
super().__init__()
lowerCamelCase__: str =layers_per_block
lowerCamelCase__: int =torch.nn.Convad(
UpperCAmelCase_ , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , )
lowerCamelCase__: Union[str, Any] =None
lowerCamelCase__: Any =nn.ModuleList([])
# down
lowerCamelCase__: Dict =block_out_channels[0]
for i, down_block_type in enumerate(UpperCAmelCase_):
lowerCamelCase__: Optional[Any] =output_channel
lowerCamelCase__: Optional[int] =block_out_channels[i]
lowerCamelCase__: Tuple =i == len(UpperCAmelCase_) - 1
lowerCamelCase__: int =get_down_block(
UpperCAmelCase_ , num_layers=self.layers_per_block , in_channels=UpperCAmelCase_ , out_channels=UpperCAmelCase_ , add_downsample=not is_final_block , resnet_eps=1E-6 , downsample_padding=0 , resnet_act_fn=UpperCAmelCase_ , resnet_groups=UpperCAmelCase_ , attention_head_dim=UpperCAmelCase_ , temb_channels=UpperCAmelCase_ , )
self.down_blocks.append(UpperCAmelCase_)
# mid
lowerCamelCase__: int =UNetMidBlockaD(
in_channels=block_out_channels[-1] , resnet_eps=1E-6 , resnet_act_fn=UpperCAmelCase_ , output_scale_factor=1 , resnet_time_scale_shift="default" , attention_head_dim=block_out_channels[-1] , resnet_groups=UpperCAmelCase_ , temb_channels=UpperCAmelCase_ , )
# out
lowerCamelCase__: str =nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=UpperCAmelCase_ , eps=1E-6)
lowerCamelCase__: Union[str, Any] =nn.SiLU()
lowerCamelCase__: str =2 * out_channels if double_z else out_channels
lowerCamelCase__: int =nn.Convad(block_out_channels[-1] , UpperCAmelCase_ , 3 , padding=1)
lowerCamelCase__: Optional[int] =False
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List[Any]) ->int:
'''simple docstring'''
lowerCamelCase__: List[str] =x
lowerCamelCase__: Tuple =self.conv_in(UpperCAmelCase_)
if self.training and self.gradient_checkpointing:
def create_custom_forward(UpperCAmelCase_ : str):
def custom_forward(*UpperCAmelCase_ : Optional[Any]):
return module(*UpperCAmelCase_)
return custom_forward
# down
if is_torch_version(">=" , "1.11.0"):
for down_block in self.down_blocks:
lowerCamelCase__: Optional[Any] =torch.utils.checkpoint.checkpoint(
create_custom_forward(UpperCAmelCase_) , UpperCAmelCase_ , use_reentrant=UpperCAmelCase_)
# middle
lowerCamelCase__: Union[str, Any] =torch.utils.checkpoint.checkpoint(
create_custom_forward(self.mid_block) , UpperCAmelCase_ , use_reentrant=UpperCAmelCase_)
else:
for down_block in self.down_blocks:
lowerCamelCase__: List[Any] =torch.utils.checkpoint.checkpoint(create_custom_forward(UpperCAmelCase_) , UpperCAmelCase_)
# middle
lowerCamelCase__: Optional[int] =torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block) , UpperCAmelCase_)
else:
# down
for down_block in self.down_blocks:
lowerCamelCase__: Optional[int] =down_block(UpperCAmelCase_)
# middle
lowerCamelCase__: Any =self.mid_block(UpperCAmelCase_)
# post-process
lowerCamelCase__: List[str] =self.conv_norm_out(UpperCAmelCase_)
lowerCamelCase__: Tuple =self.conv_act(UpperCAmelCase_)
lowerCamelCase__: Union[str, Any] =self.conv_out(UpperCAmelCase_)
return sample
class _SCREAMING_SNAKE_CASE ( nn.Module ):
'''simple docstring'''
def __init__(self : Union[str, Any] , UpperCAmelCase_ : Union[str, Any]=3 , UpperCAmelCase_ : Dict=3 , UpperCAmelCase_ : Tuple=("UpDecoderBlock2D",) , UpperCAmelCase_ : Dict=(64,) , UpperCAmelCase_ : Union[str, Any]=2 , UpperCAmelCase_ : Dict=32 , UpperCAmelCase_ : List[Any]="silu" , UpperCAmelCase_ : Tuple="group" , ) ->Dict:
'''simple docstring'''
super().__init__()
lowerCamelCase__: Optional[int] =layers_per_block
lowerCamelCase__: str =nn.Convad(
UpperCAmelCase_ , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , )
lowerCamelCase__: List[Any] =None
lowerCamelCase__: Optional[Any] =nn.ModuleList([])
lowerCamelCase__: Any =in_channels if norm_type == "spatial" else None
# mid
lowerCamelCase__: Optional[Any] =UNetMidBlockaD(
in_channels=block_out_channels[-1] , resnet_eps=1E-6 , resnet_act_fn=UpperCAmelCase_ , 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=UpperCAmelCase_ , temb_channels=UpperCAmelCase_ , )
# up
lowerCamelCase__: Optional[Any] =list(reversed(UpperCAmelCase_))
lowerCamelCase__: Union[str, Any] =reversed_block_out_channels[0]
for i, up_block_type in enumerate(UpperCAmelCase_):
lowerCamelCase__: str =output_channel
lowerCamelCase__: Any =reversed_block_out_channels[i]
lowerCamelCase__: Dict =i == len(UpperCAmelCase_) - 1
lowerCamelCase__: Dict =get_up_block(
UpperCAmelCase_ , num_layers=self.layers_per_block + 1 , in_channels=UpperCAmelCase_ , out_channels=UpperCAmelCase_ , prev_output_channel=UpperCAmelCase_ , add_upsample=not is_final_block , resnet_eps=1E-6 , resnet_act_fn=UpperCAmelCase_ , resnet_groups=UpperCAmelCase_ , attention_head_dim=UpperCAmelCase_ , temb_channels=UpperCAmelCase_ , resnet_time_scale_shift=UpperCAmelCase_ , )
self.up_blocks.append(UpperCAmelCase_)
lowerCamelCase__: Union[str, Any] =output_channel
# out
if norm_type == "spatial":
lowerCamelCase__: int =SpatialNorm(block_out_channels[0] , UpperCAmelCase_)
else:
lowerCamelCase__: Dict =nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=UpperCAmelCase_ , eps=1E-6)
lowerCamelCase__: int =nn.SiLU()
lowerCamelCase__: List[Any] =nn.Convad(block_out_channels[0] , UpperCAmelCase_ , 3 , padding=1)
lowerCamelCase__: Optional[int] =False
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : str=None) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Tuple =z
lowerCamelCase__: List[Any] =self.conv_in(UpperCAmelCase_)
lowerCamelCase__: Union[str, Any] =next(iter(self.up_blocks.parameters())).dtype
if self.training and self.gradient_checkpointing:
def create_custom_forward(UpperCAmelCase_ : Optional[Any]):
def custom_forward(*UpperCAmelCase_ : List[Any]):
return module(*UpperCAmelCase_)
return custom_forward
if is_torch_version(">=" , "1.11.0"):
# middle
lowerCamelCase__: List[Any] =torch.utils.checkpoint.checkpoint(
create_custom_forward(self.mid_block) , UpperCAmelCase_ , UpperCAmelCase_ , use_reentrant=UpperCAmelCase_)
lowerCamelCase__: Any =sample.to(UpperCAmelCase_)
# up
for up_block in self.up_blocks:
lowerCamelCase__: Union[str, Any] =torch.utils.checkpoint.checkpoint(
create_custom_forward(UpperCAmelCase_) , UpperCAmelCase_ , UpperCAmelCase_ , use_reentrant=UpperCAmelCase_)
else:
# middle
lowerCamelCase__: List[Any] =torch.utils.checkpoint.checkpoint(
create_custom_forward(self.mid_block) , UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =sample.to(UpperCAmelCase_)
# up
for up_block in self.up_blocks:
lowerCamelCase__: Optional[Any] =torch.utils.checkpoint.checkpoint(create_custom_forward(UpperCAmelCase_) , UpperCAmelCase_ , UpperCAmelCase_)
else:
# middle
lowerCamelCase__: Optional[int] =self.mid_block(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Union[str, Any] =sample.to(UpperCAmelCase_)
# up
for up_block in self.up_blocks:
lowerCamelCase__: List[Any] =up_block(UpperCAmelCase_ , UpperCAmelCase_)
# post-process
if latent_embeds is None:
lowerCamelCase__: Union[str, Any] =self.conv_norm_out(UpperCAmelCase_)
else:
lowerCamelCase__: List[Any] =self.conv_norm_out(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =self.conv_act(UpperCAmelCase_)
lowerCamelCase__: str =self.conv_out(UpperCAmelCase_)
return sample
class _SCREAMING_SNAKE_CASE ( nn.Module ):
'''simple docstring'''
def __init__(self : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : Any="random" , UpperCAmelCase_ : Any=False , UpperCAmelCase_ : Optional[Any]=True) ->Dict:
'''simple docstring'''
super().__init__()
lowerCamelCase__: str =n_e
lowerCamelCase__: str =vq_embed_dim
lowerCamelCase__: str =beta
lowerCamelCase__: List[str] =legacy
lowerCamelCase__: Tuple =nn.Embedding(self.n_e , self.vq_embed_dim)
self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e)
lowerCamelCase__: Optional[Any] =remap
if self.remap is not None:
self.register_buffer("used" , torch.tensor(np.load(self.remap)))
lowerCamelCase__: List[str] =self.used.shape[0]
lowerCamelCase__: Any =unknown_index # "random" or "extra" or integer
if self.unknown_index == "extra":
lowerCamelCase__: int =self.re_embed
lowerCamelCase__: Tuple =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:
lowerCamelCase__: int =n_e
lowerCamelCase__: Optional[Any] =sane_index_shape
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : List[Any]) ->List[Any]:
'''simple docstring'''
lowerCamelCase__: int =inds.shape
assert len(UpperCAmelCase_) > 1
lowerCamelCase__: int =inds.reshape(ishape[0] , -1)
lowerCamelCase__: Optional[int] =self.used.to(UpperCAmelCase_)
lowerCamelCase__: Optional[int] =(inds[:, :, None] == used[None, None, ...]).long()
lowerCamelCase__: List[str] =match.argmax(-1)
lowerCamelCase__: Dict =match.sum(2) < 1
if self.unknown_index == "random":
lowerCamelCase__: List[str] =torch.randint(0 , self.re_embed , size=new[unknown].shape).to(device=new.device)
else:
lowerCamelCase__: str =self.unknown_index
return new.reshape(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Dict , UpperCAmelCase_ : Union[str, Any]) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =inds.shape
assert len(UpperCAmelCase_) > 1
lowerCamelCase__: Optional[int] =inds.reshape(ishape[0] , -1)
lowerCamelCase__: Dict =self.used.to(UpperCAmelCase_)
if self.re_embed > self.used.shape[0]: # extra token
lowerCamelCase__: str =0 # simply set to zero
lowerCamelCase__: Tuple =torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , UpperCAmelCase_)
return back.reshape(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Optional[int]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Any =z.permute(0 , 2 , 3 , 1).contiguous()
lowerCamelCase__: Dict =z.view(-1 , self.vq_embed_dim)
# distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
lowerCamelCase__: Tuple =torch.argmin(torch.cdist(UpperCAmelCase_ , self.embedding.weight) , dim=1)
lowerCamelCase__: List[str] =self.embedding(UpperCAmelCase_).view(z.shape)
lowerCamelCase__: Optional[int] =None
lowerCamelCase__: Dict =None
# compute loss for embedding
if not self.legacy:
lowerCamelCase__: int =self.beta * torch.mean((z_q.detach() - z) ** 2) + torch.mean((z_q - z.detach()) ** 2)
else:
lowerCamelCase__: str =torch.mean((z_q.detach() - z) ** 2) + self.beta * torch.mean((z_q - z.detach()) ** 2)
# preserve gradients
lowerCamelCase__: Optional[int] =z + (z_q - z).detach()
# reshape back to match original input shape
lowerCamelCase__: Optional[Any] =z_q.permute(0 , 3 , 1 , 2).contiguous()
if self.remap is not None:
lowerCamelCase__: Union[str, Any] =min_encoding_indices.reshape(z.shape[0] , -1) # add batch axis
lowerCamelCase__: Any =self.remap_to_used(UpperCAmelCase_)
lowerCamelCase__: Dict =min_encoding_indices.reshape(-1 , 1) # flatten
if self.sane_index_shape:
lowerCamelCase__: Any =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 SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : int) ->int:
'''simple docstring'''
if self.remap is not None:
lowerCamelCase__: Tuple =indices.reshape(shape[0] , -1) # add batch axis
lowerCamelCase__: List[str] =self.unmap_to_all(UpperCAmelCase_)
lowerCamelCase__: Union[str, Any] =indices.reshape(-1) # flatten again
# get quantized latent vectors
lowerCamelCase__: Dict =self.embedding(UpperCAmelCase_)
if shape is not None:
lowerCamelCase__: Optional[Any] =z_q.view(UpperCAmelCase_)
# reshape back to match original input shape
lowerCamelCase__: Union[str, Any] =z_q.permute(0 , 3 , 1 , 2).contiguous()
return z_q
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__(self : Optional[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Dict=False) ->Dict:
'''simple docstring'''
lowerCamelCase__: Optional[int] =parameters
lowerCamelCase__ , lowerCamelCase__: int =torch.chunk(UpperCAmelCase_ , 2 , dim=1)
lowerCamelCase__: Union[str, Any] =torch.clamp(self.logvar , -30.0 , 20.0)
lowerCamelCase__: int =deterministic
lowerCamelCase__: Any =torch.exp(0.5 * self.logvar)
lowerCamelCase__: Any =torch.exp(self.logvar)
if self.deterministic:
lowerCamelCase__: int =torch.zeros_like(
self.mean , device=self.parameters.device , dtype=self.parameters.dtype)
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any] , UpperCAmelCase_ : Optional[torch.Generator] = None) ->torch.FloatTensor:
'''simple docstring'''
lowerCamelCase__: str =randn_tensor(
self.mean.shape , generator=UpperCAmelCase_ , device=self.parameters.device , dtype=self.parameters.dtype)
lowerCamelCase__: str =self.mean + self.std * sample
return x
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : List[Any]=None) ->int:
'''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 SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Tuple=[1, 2, 3]) ->Dict:
'''simple docstring'''
if self.deterministic:
return torch.Tensor([0.0])
lowerCamelCase__: Any =np.log(2.0 * np.pi)
return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2) / self.var , dim=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str:
'''simple docstring'''
return self.mean
| 59 |
from collections import defaultdict
from typing import Optional
from ..image_utils import load_image
from ..utils import (
add_end_docstrings,
is_torch_available,
logging,
requires_backends,
)
from .base import PIPELINE_INIT_ARGS, ChunkPipeline
if is_torch_available():
import torch
from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING
__A = logging.get_logger(__name__)
@add_end_docstrings(__SCREAMING_SNAKE_CASE )
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__(self : List[Any] , **UpperCAmelCase_ : Any) ->Any:
'''simple docstring'''
super().__init__(**UpperCAmelCase_)
requires_backends(self , "vision")
requires_backends(self , "torch")
if self.framework != "pt":
raise ValueError(F"""The {self.__class__} is only available in PyTorch.""")
self.check_model_type(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Tuple , **UpperCAmelCase_ : List[Any]) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Optional[int] ={}
lowerCamelCase__: Tuple ={}
lowerCamelCase__: str ={}
# preprocess args
if "points_per_batch" in kwargs:
lowerCamelCase__: Optional[Any] =kwargs["points_per_batch"]
if "points_per_crop" in kwargs:
lowerCamelCase__: int =kwargs["points_per_crop"]
if "crops_n_layers" in kwargs:
lowerCamelCase__: Any =kwargs["crops_n_layers"]
if "crop_overlap_ratio" in kwargs:
lowerCamelCase__: Tuple =kwargs["crop_overlap_ratio"]
if "crop_n_points_downscale_factor" in kwargs:
lowerCamelCase__: List[Any] =kwargs["crop_n_points_downscale_factor"]
# postprocess args
if "pred_iou_thresh" in kwargs:
lowerCamelCase__: List[str] =kwargs["pred_iou_thresh"]
if "stability_score_offset" in kwargs:
lowerCamelCase__: int =kwargs["stability_score_offset"]
if "mask_threshold" in kwargs:
lowerCamelCase__: Optional[int] =kwargs["mask_threshold"]
if "stability_score_thresh" in kwargs:
lowerCamelCase__: str =kwargs["stability_score_thresh"]
if "crops_nms_thresh" in kwargs:
lowerCamelCase__: Any =kwargs["crops_nms_thresh"]
if "output_rle_mask" in kwargs:
lowerCamelCase__: List[Any] =kwargs["output_rle_mask"]
if "output_bboxes_mask" in kwargs:
lowerCamelCase__: List[str] =kwargs["output_bboxes_mask"]
return preprocess_kwargs, forward_params, postprocess_kwargs
def __call__(self : int , UpperCAmelCase_ : Dict , *UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[Any]:
'''simple docstring'''
return super().__call__(UpperCAmelCase_ , *UpperCAmelCase_ , num_workers=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any]=64 , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : float = 512 / 1_500 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 1 , ) ->Dict:
'''simple docstring'''
lowerCamelCase__: Dict =load_image(UpperCAmelCase_)
lowerCamelCase__: List[str] =self.image_processor.size["longest_edge"]
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =self.image_processor.generate_crop_boxes(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: str =self.image_processor(images=UpperCAmelCase_ , return_tensors="pt")
with self.device_placement():
if self.framework == "pt":
lowerCamelCase__: str =self.get_inference_context()
with inference_context():
lowerCamelCase__: Union[str, Any] =self._ensure_tensor_on_device(UpperCAmelCase_ , device=self.device)
lowerCamelCase__: Optional[Any] =self.model.get_image_embeddings(model_inputs.pop("pixel_values"))
lowerCamelCase__: str =image_embeddings
lowerCamelCase__: int =grid_points.shape[1]
lowerCamelCase__: int =points_per_batch if points_per_batch is not None else n_points
if points_per_batch <= 0:
raise ValueError(
"Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. "
"To return all points at once, set points_per_batch to None")
for i in range(0 , UpperCAmelCase_ , UpperCAmelCase_):
lowerCamelCase__: int =grid_points[:, i : i + points_per_batch, :, :]
lowerCamelCase__: Optional[Any] =input_labels[:, i : i + points_per_batch]
lowerCamelCase__: Dict =i == n_points - points_per_batch
yield {
"input_points": batched_points,
"input_labels": labels,
"input_boxes": crop_boxes,
"is_last": is_last,
**model_inputs,
}
def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=0.88 , UpperCAmelCase_ : Optional[Any]=0.95 , UpperCAmelCase_ : Tuple=0 , UpperCAmelCase_ : Any=1 , ) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Any =model_inputs.pop("input_boxes")
lowerCamelCase__: Dict =model_inputs.pop("is_last")
lowerCamelCase__: int =model_inputs.pop("original_sizes").tolist()
lowerCamelCase__: Union[str, Any] =model_inputs.pop("reshaped_input_sizes").tolist()
lowerCamelCase__: Union[str, Any] =self.model(**UpperCAmelCase_)
# post processing happens here in order to avoid CPU GPU copies of ALL the masks
lowerCamelCase__: Optional[int] =model_outputs["pred_masks"]
lowerCamelCase__: Union[str, Any] =self.image_processor.post_process_masks(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , binarize=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =model_outputs["iou_scores"]
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =self.image_processor.filter_masks(
masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , )
return {
"masks": masks,
"is_last": is_last,
"boxes": boxes,
"iou_scores": iou_scores,
}
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Optional[int]=0.7 , ) ->Tuple:
'''simple docstring'''
lowerCamelCase__: Any =[]
lowerCamelCase__: Optional[int] =[]
lowerCamelCase__: List[str] =[]
for model_output in model_outputs:
all_scores.append(model_output.pop("iou_scores"))
all_masks.extend(model_output.pop("masks"))
all_boxes.append(model_output.pop("boxes"))
lowerCamelCase__: str =torch.cat(UpperCAmelCase_)
lowerCamelCase__: List[str] =torch.cat(UpperCAmelCase_)
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Dict =self.image_processor.post_process_for_mask_generation(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: List[str] =defaultdict(UpperCAmelCase_)
for output in model_outputs:
for k, v in output.items():
extra[k].append(UpperCAmelCase_)
lowerCamelCase__: Any ={}
if output_rle_mask:
lowerCamelCase__: Union[str, Any] =rle_mask
if output_bboxes_mask:
lowerCamelCase__: int =bounding_boxes
return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
| 59 | 1 |
import json
import os
import unittest
from transformers.models.roc_bert.tokenization_roc_bert import (
VOCAB_FILES_NAMES,
RoCBertBasicTokenizer,
RoCBertTokenizer,
RoCBertWordpieceTokenizer,
_is_control,
_is_punctuation,
_is_whitespace,
)
from transformers.testing_utils import require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english
@require_tokenizers
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ):
'''simple docstring'''
lowercase_ = RoCBertTokenizer
lowercase_ = None
lowercase_ = False
lowercase_ = True
lowercase_ = filter_non_english
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[str]:
'''simple docstring'''
super().setUp()
lowerCamelCase__: int =["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"]
lowerCamelCase__: Dict ={}
lowerCamelCase__: Dict ={}
for i, value in enumerate(UpperCAmelCase_):
lowerCamelCase__: Any =i
lowerCamelCase__: List[str] =i
lowerCamelCase__: List[Any] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"])
lowerCamelCase__: Tuple =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"])
lowerCamelCase__: Optional[int] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"])
with open(self.vocab_file , "w" , encoding="utf-8") as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
with open(self.word_shape_file , "w" , encoding="utf-8") as word_shape_writer:
json.dump(UpperCAmelCase_ , UpperCAmelCase_ , ensure_ascii=UpperCAmelCase_)
with open(self.word_pronunciation_file , "w" , encoding="utf-8") as word_pronunciation_writer:
json.dump(UpperCAmelCase_ , UpperCAmelCase_ , ensure_ascii=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : int) ->int:
'''simple docstring'''
lowerCamelCase__: int =self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file)
lowerCamelCase__: Union[str, Any] =tokenizer.tokenize("你好[SEP]你是谁")
self.assertListEqual(UpperCAmelCase_ , ["你", "好", "[SEP]", "你", "是", "谁"])
self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_) , [5, 6, 2, 5, 7, 8])
self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase_) , [5, 6, 2, 5, 7, 8])
self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase_) , [5, 6, 2, 5, 7, 8])
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->int:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =RoCBertBasicTokenizer()
self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz") , ["ah", "\u535A", "\u63A8", "zz"])
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Any =RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase_)
self.assertListEqual(
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? ") , ["hello", "!", "how", "are", "you", "?"])
self.assertListEqual(tokenizer.tokenize("H\u00E9llo") , ["hello"])
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Any:
'''simple docstring'''
lowerCamelCase__: Dict =RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase_ , strip_accents=UpperCAmelCase_)
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? ") , ["hällo", "!", "how", "are", "you", "?"])
self.assertListEqual(tokenizer.tokenize("H\u00E9llo") , ["h\u00E9llo"])
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase_ , strip_accents=UpperCAmelCase_)
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? ") , ["hallo", "!", "how", "are", "you", "?"])
self.assertListEqual(tokenizer.tokenize("H\u00E9llo") , ["hello"])
def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Tuple =RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase_)
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? ") , ["hallo", "!", "how", "are", "you", "?"])
self.assertListEqual(tokenizer.tokenize("H\u00E9llo") , ["hello"])
def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->List[str]:
'''simple docstring'''
lowerCamelCase__: Dict =RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase_)
self.assertListEqual(
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? ") , ["HeLLo", "!", "how", "Are", "yoU", "?"])
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->int:
'''simple docstring'''
lowerCamelCase__: Dict =RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase_ , strip_accents=UpperCAmelCase_)
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? ") , ["HäLLo", "!", "how", "Are", "yoU", "?"])
def SCREAMING_SNAKE_CASE_ (self : int) ->str:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase_ , strip_accents=UpperCAmelCase_)
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? ") , ["HaLLo", "!", "how", "Are", "yoU", "?"])
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Dict =RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase_ , never_split=["[UNK]"])
self.assertListEqual(
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]") , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"])
def SCREAMING_SNAKE_CASE_ (self : Dict) ->List[str]:
'''simple docstring'''
lowerCamelCase__: Optional[int] =["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"]
lowerCamelCase__: Dict ={}
for i, token in enumerate(UpperCAmelCase_):
lowerCamelCase__: Any =i
lowerCamelCase__: Union[str, Any] =RoCBertWordpieceTokenizer(vocab=UpperCAmelCase_ , unk_token="[UNK]")
self.assertListEqual(tokenizer.tokenize("") , [])
self.assertListEqual(tokenizer.tokenize("unwanted running") , ["un", "##want", "##ed", "runn", "##ing"])
self.assertListEqual(tokenizer.tokenize("unwantedX running") , ["[UNK]", "runn", "##ing"])
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->List[str]:
'''simple docstring'''
self.assertTrue(_is_whitespace(" "))
self.assertTrue(_is_whitespace("\t"))
self.assertTrue(_is_whitespace("\r"))
self.assertTrue(_is_whitespace("\n"))
self.assertTrue(_is_whitespace("\u00A0"))
self.assertFalse(_is_whitespace("A"))
self.assertFalse(_is_whitespace("-"))
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->List[Any]:
'''simple docstring'''
self.assertTrue(_is_control("\u0005"))
self.assertFalse(_is_control("A"))
self.assertFalse(_is_control(" "))
self.assertFalse(_is_control("\t"))
self.assertFalse(_is_control("\r"))
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[str]:
'''simple docstring'''
self.assertTrue(_is_punctuation("-"))
self.assertTrue(_is_punctuation("$"))
self.assertTrue(_is_punctuation("`"))
self.assertTrue(_is_punctuation("."))
self.assertFalse(_is_punctuation("A"))
self.assertFalse(_is_punctuation(" "))
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->int:
'''simple docstring'''
lowerCamelCase__: Any =self.get_tokenizer()
# Example taken from the issue https://github.com/huggingface/tokenizers/issues/340
self.assertListEqual([tokenizer.tokenize(UpperCAmelCase_) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]])
if self.test_rust_tokenizer:
lowerCamelCase__: Tuple =self.get_rust_tokenizer()
self.assertListEqual(
[rust_tokenizer.tokenize(UpperCAmelCase_) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]])
def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]:
'''simple docstring'''
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""):
lowerCamelCase__: str =self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: Optional[int] =F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence."""
lowerCamelCase__: Optional[int] =tokenizer_r.encode_plus(
UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , return_offsets_mapping=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ , )
lowerCamelCase__: Tuple =tokenizer_r.do_lower_case if hasattr(UpperCAmelCase_ , "do_lower_case") else False
lowerCamelCase__: Tuple =(
[
((0, 0), tokenizer_r.cls_token),
((0, 1), "A"),
((1, 2), ","),
((3, 5), "na"),
((5, 6), "##ï"),
((6, 8), "##ve"),
((9, 15), tokenizer_r.mask_token),
((16, 21), "Allen"),
((21, 23), "##NL"),
((23, 24), "##P"),
((25, 33), "sentence"),
((33, 34), "."),
((0, 0), tokenizer_r.sep_token),
]
if not do_lower_case
else [
((0, 0), tokenizer_r.cls_token),
((0, 1), "a"),
((1, 2), ","),
((3, 8), "naive"),
((9, 15), tokenizer_r.mask_token),
((16, 21), "allen"),
((21, 23), "##nl"),
((23, 24), "##p"),
((25, 33), "sentence"),
((33, 34), "."),
((0, 0), tokenizer_r.sep_token),
]
)
self.assertEqual(
[e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["input_ids"]))
self.assertEqual([e[0] for e in expected_results] , tokens["offset_mapping"])
def SCREAMING_SNAKE_CASE_ (self : str) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =["的", "人", "有"]
lowerCamelCase__: List[str] ="".join(UpperCAmelCase_)
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""):
lowerCamelCase__: Dict =True
lowerCamelCase__: Optional[Any] =self.tokenizer_class.from_pretrained(UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: Optional[int] =self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: int =tokenizer_p.encode(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_)
lowerCamelCase__: List[Any] =tokenizer_r.encode(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_)
lowerCamelCase__: Tuple =tokenizer_r.convert_ids_to_tokens(UpperCAmelCase_)
lowerCamelCase__: List[str] =tokenizer_p.convert_ids_to_tokens(UpperCAmelCase_)
# it is expected that each Chinese character is not preceded by "##"
self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_)
self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =False
lowerCamelCase__: Tuple =self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: List[Any] =self.tokenizer_class.from_pretrained(UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: Tuple =tokenizer_r.encode(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_)
lowerCamelCase__: str =tokenizer_p.encode(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_)
lowerCamelCase__: Optional[int] =tokenizer_r.convert_ids_to_tokens(UpperCAmelCase_)
lowerCamelCase__: Tuple =tokenizer_p.convert_ids_to_tokens(UpperCAmelCase_)
# it is expected that only the first Chinese character is not preceded by "##".
lowerCamelCase__: List[str] =[
F"""##{token}""" if idx != 0 else token for idx, token in enumerate(UpperCAmelCase_)
]
self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_)
self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_)
@slow
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Dict:
'''simple docstring'''
lowerCamelCase__: Tuple =self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file)
lowerCamelCase__: int =tokenizer.encode("你好" , add_special_tokens=UpperCAmelCase_)
lowerCamelCase__: Any =tokenizer.encode("你是谁" , add_special_tokens=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =tokenizer.build_inputs_with_special_tokens(UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =tokenizer.build_inputs_with_special_tokens(UpperCAmelCase_ , UpperCAmelCase_)
assert encoded_sentence == [1] + text + [2]
assert encoded_pair == [1] + text + [2] + text_a + [2]
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->str:
'''simple docstring'''
lowerCamelCase__: Union[str, Any] =self.get_tokenizers(do_lower_case=UpperCAmelCase_)
for tokenizer in tokenizers:
with self.subTest(F"""{tokenizer.__class__.__name__}"""):
lowerCamelCase__: Union[str, Any] ="你好,你是谁"
lowerCamelCase__: str =tokenizer.tokenize(UpperCAmelCase_)
lowerCamelCase__: Optional[int] =tokenizer.convert_tokens_to_ids(UpperCAmelCase_)
lowerCamelCase__: int =tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase_)
lowerCamelCase__: Optional[int] =tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase_)
lowerCamelCase__: str =tokenizer.prepare_for_model(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_)
lowerCamelCase__: List[Any] =tokenizer.encode_plus(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_)
self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_)
| 59 |
from transformers import BertTokenizerFast
from .custom_tokenization import CustomTokenizer
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = CustomTokenizer
pass
| 59 | 1 |
import itertools
import json
import os
import unittest
from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ):
'''simple docstring'''
lowercase_ = RobertaTokenizer
lowercase_ = RobertaTokenizerFast
lowercase_ = True
lowercase_ = {"cls_token": "<s>"}
def SCREAMING_SNAKE_CASE_ (self : Dict) ->List[str]:
'''simple docstring'''
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
lowerCamelCase__: Union[str, Any] =[
"l",
"o",
"w",
"e",
"r",
"s",
"t",
"i",
"d",
"n",
"\u0120",
"\u0120l",
"\u0120n",
"\u0120lo",
"\u0120low",
"er",
"\u0120lowest",
"\u0120newer",
"\u0120wider",
"<unk>",
]
lowerCamelCase__: List[str] =dict(zip(UpperCAmelCase_ , range(len(UpperCAmelCase_))))
lowerCamelCase__: Union[str, Any] =["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
lowerCamelCase__: Union[str, Any] ={"unk_token": "<unk>"}
lowerCamelCase__: Any =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"])
lowerCamelCase__: List[str] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"])
with open(self.vocab_file , "w" , encoding="utf-8") as fp:
fp.write(json.dumps(UpperCAmelCase_) + "\n")
with open(self.merges_file , "w" , encoding="utf-8") as fp:
fp.write("\n".join(UpperCAmelCase_))
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , **UpperCAmelCase_ : Optional[int]) ->Optional[int]:
'''simple docstring'''
kwargs.update(self.special_tokens_map)
return self.tokenizer_class.from_pretrained(self.tmpdirname , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : str , **UpperCAmelCase_ : int) ->Optional[Any]:
'''simple docstring'''
kwargs.update(self.special_tokens_map)
return RobertaTokenizerFast.from_pretrained(self.tmpdirname , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Dict) ->str:
'''simple docstring'''
lowerCamelCase__: Any ="lower newer"
lowerCamelCase__: List[Any] ="lower newer"
return input_text, output_text
def SCREAMING_SNAKE_CASE_ (self : Any) ->List[Any]:
'''simple docstring'''
lowerCamelCase__: Any =self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map)
lowerCamelCase__: Any ="lower newer"
lowerCamelCase__: Any =["l", "o", "w", "er", "\u0120", "n", "e", "w", "er"]
lowerCamelCase__: Tuple =tokenizer.tokenize(UpperCAmelCase_) # , add_prefix_space=True)
self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: List[str] =tokens + [tokenizer.unk_token]
lowerCamelCase__: int =[0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_) , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->int:
'''simple docstring'''
lowerCamelCase__: int =self.get_tokenizer()
self.assertListEqual(tokenizer.encode("Hello world!" , add_special_tokens=UpperCAmelCase_) , [0, 31_414, 232, 328, 2])
self.assertListEqual(
tokenizer.encode("Hello world! cécé herlolip 418" , add_special_tokens=UpperCAmelCase_) , [0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2] , )
@slow
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Dict:
'''simple docstring'''
lowerCamelCase__: Optional[int] =self.tokenizer_class.from_pretrained("roberta-base")
lowerCamelCase__: List[Any] =tokenizer.encode("sequence builders" , add_special_tokens=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =tokenizer.encode("multi-sequence build" , add_special_tokens=UpperCAmelCase_)
lowerCamelCase__: List[str] =tokenizer.encode(
"sequence builders" , add_special_tokens=UpperCAmelCase_ , add_prefix_space=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =tokenizer.encode(
"sequence builders" , "multi-sequence build" , add_special_tokens=UpperCAmelCase_ , add_prefix_space=UpperCAmelCase_)
lowerCamelCase__: Any =tokenizer.build_inputs_with_special_tokens(UpperCAmelCase_)
lowerCamelCase__: List[str] =tokenizer.build_inputs_with_special_tokens(UpperCAmelCase_ , UpperCAmelCase_)
assert encoded_sentence == encoded_text_from_decode
assert encoded_pair == encoded_pair_from_decode
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]:
'''simple docstring'''
lowerCamelCase__: str =self.get_tokenizer()
lowerCamelCase__: List[Any] ="Encode this sequence."
lowerCamelCase__: Dict =tokenizer.byte_encoder[" ".encode("utf-8")[0]]
# Testing encoder arguments
lowerCamelCase__: Tuple =tokenizer.encode(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ , add_prefix_space=UpperCAmelCase_)
lowerCamelCase__: Dict =tokenizer.convert_ids_to_tokens(encoded[0])[0]
self.assertNotEqual(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Dict =tokenizer.encode(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ , add_prefix_space=UpperCAmelCase_)
lowerCamelCase__: int =tokenizer.convert_ids_to_tokens(encoded[0])[0]
self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_)
tokenizer.add_special_tokens({"bos_token": "<s>"})
lowerCamelCase__: List[str] =tokenizer.encode(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_)
lowerCamelCase__: int =tokenizer.convert_ids_to_tokens(encoded[1])[0]
self.assertNotEqual(UpperCAmelCase_ , UpperCAmelCase_)
# Testing spaces after special tokens
lowerCamelCase__: Any ="<mask>"
tokenizer.add_special_tokens(
{"mask_token": AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_)}) # mask token has a left space
lowerCamelCase__: Union[str, Any] =tokenizer.convert_tokens_to_ids(UpperCAmelCase_)
lowerCamelCase__: List[str] ="Encode <mask> sequence"
lowerCamelCase__: Optional[Any] ="Encode <mask>sequence"
lowerCamelCase__: List[str] =tokenizer.encode(UpperCAmelCase_)
lowerCamelCase__: List[Any] =encoded.index(UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1])[0]
self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Any =tokenizer.encode(UpperCAmelCase_)
lowerCamelCase__: List[str] =encoded.index(UpperCAmelCase_)
lowerCamelCase__: Any =tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1])[0]
self.assertNotEqual(UpperCAmelCase_ , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : str) ->str:
'''simple docstring'''
pass
def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->str:
'''simple docstring'''
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""):
lowerCamelCase__: List[Any] =self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: Optional[int] =self.tokenizer_class.from_pretrained(UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: Dict ="A, <mask> AllenNLP sentence."
lowerCamelCase__: List[str] =tokenizer_r.encode_plus(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_)
lowerCamelCase__: Optional[int] =tokenizer_p.encode_plus(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_)
# token_type_ids should put 0 everywhere
self.assertEqual(sum(tokens_r["token_type_ids"]) , sum(tokens_p["token_type_ids"]))
# attention_mask should put 1 everywhere, so sum over length should be 1
self.assertEqual(
sum(tokens_r["attention_mask"]) / len(tokens_r["attention_mask"]) , sum(tokens_p["attention_mask"]) / len(tokens_p["attention_mask"]) , )
lowerCamelCase__: Dict =tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"])
lowerCamelCase__: Optional[int] =tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"])
# Rust correctly handles the space before the mask while python doesnt
self.assertSequenceEqual(tokens_p["input_ids"] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2])
self.assertSequenceEqual(tokens_r["input_ids"] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2])
self.assertSequenceEqual(
UpperCAmelCase_ , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"])
self.assertSequenceEqual(
UpperCAmelCase_ , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"])
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Tuple:
'''simple docstring'''
for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2):
lowerCamelCase__: List[Any] =self.rust_tokenizer_class.from_pretrained(
self.tmpdirname , use_fast=UpperCAmelCase_ , add_prefix_space=UpperCAmelCase_ , trim_offsets=UpperCAmelCase_)
lowerCamelCase__: Dict =json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__())
lowerCamelCase__: str =json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__())
self.assertEqual(pre_tokenizer_state["add_prefix_space"] , UpperCAmelCase_)
self.assertEqual(post_processor_state["add_prefix_space"] , UpperCAmelCase_)
self.assertEqual(post_processor_state["trim_offsets"] , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]:
'''simple docstring'''
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""):
lowerCamelCase__: str ="hello" # `hello` is a token in the vocabulary of `pretrained_name`
lowerCamelCase__: List[Any] =F"""{text_of_1_token} {text_of_1_token}"""
lowerCamelCase__: Tuple =self.rust_tokenizer_class.from_pretrained(
UpperCAmelCase_ , use_fast=UpperCAmelCase_ , add_prefix_space=UpperCAmelCase_ , trim_offsets=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =tokenizer_r(UpperCAmelCase_ , return_offsets_mapping=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_)
self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase_)))
self.assertEqual(
encoding.offset_mapping[1] , (len(UpperCAmelCase_) + 1, len(UpperCAmelCase_) + 1 + len(UpperCAmelCase_)) , )
lowerCamelCase__: Optional[int] =self.rust_tokenizer_class.from_pretrained(
UpperCAmelCase_ , use_fast=UpperCAmelCase_ , add_prefix_space=UpperCAmelCase_ , trim_offsets=UpperCAmelCase_)
lowerCamelCase__: List[str] =tokenizer_r(UpperCAmelCase_ , return_offsets_mapping=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_)
self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase_)))
self.assertEqual(
encoding.offset_mapping[1] , (len(UpperCAmelCase_) + 1, len(UpperCAmelCase_) + 1 + len(UpperCAmelCase_)) , )
lowerCamelCase__: List[str] =self.rust_tokenizer_class.from_pretrained(
UpperCAmelCase_ , use_fast=UpperCAmelCase_ , add_prefix_space=UpperCAmelCase_ , trim_offsets=UpperCAmelCase_)
lowerCamelCase__: int =tokenizer_r(UpperCAmelCase_ , return_offsets_mapping=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_)
self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase_)))
self.assertEqual(
encoding.offset_mapping[1] , (len(UpperCAmelCase_), len(UpperCAmelCase_) + 1 + len(UpperCAmelCase_)) , )
lowerCamelCase__: Optional[Any] =self.rust_tokenizer_class.from_pretrained(
UpperCAmelCase_ , use_fast=UpperCAmelCase_ , add_prefix_space=UpperCAmelCase_ , trim_offsets=UpperCAmelCase_)
lowerCamelCase__: str =tokenizer_r(UpperCAmelCase_ , return_offsets_mapping=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_)
self.assertEqual(encoding.offset_mapping[0] , (0, len(UpperCAmelCase_)))
self.assertEqual(
encoding.offset_mapping[1] , (len(UpperCAmelCase_), len(UpperCAmelCase_) + 1 + len(UpperCAmelCase_)) , )
lowerCamelCase__: Dict =F""" {text}"""
# tokenizer_r = self.rust_tokenizer_class.from_pretrained(
# pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True
# )
# encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False)
# self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token)))
# self.assertEqual(
# encoding.offset_mapping[1],
# (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)),
# )
lowerCamelCase__: Optional[Any] =self.rust_tokenizer_class.from_pretrained(
UpperCAmelCase_ , use_fast=UpperCAmelCase_ , add_prefix_space=UpperCAmelCase_ , trim_offsets=UpperCAmelCase_)
lowerCamelCase__: Dict =tokenizer_r(UpperCAmelCase_ , return_offsets_mapping=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_)
self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(UpperCAmelCase_)))
self.assertEqual(
encoding.offset_mapping[1] , (1 + len(UpperCAmelCase_) + 1, 1 + len(UpperCAmelCase_) + 1 + len(UpperCAmelCase_)) , )
lowerCamelCase__: str =self.rust_tokenizer_class.from_pretrained(
UpperCAmelCase_ , use_fast=UpperCAmelCase_ , add_prefix_space=UpperCAmelCase_ , trim_offsets=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =tokenizer_r(UpperCAmelCase_ , return_offsets_mapping=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_)
self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(UpperCAmelCase_)))
self.assertEqual(
encoding.offset_mapping[1] , (1 + len(UpperCAmelCase_), 1 + len(UpperCAmelCase_) + 1 + len(UpperCAmelCase_)) , )
lowerCamelCase__: Optional[Any] =self.rust_tokenizer_class.from_pretrained(
UpperCAmelCase_ , use_fast=UpperCAmelCase_ , add_prefix_space=UpperCAmelCase_ , trim_offsets=UpperCAmelCase_)
lowerCamelCase__: Union[str, Any] =tokenizer_r(UpperCAmelCase_ , return_offsets_mapping=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_)
self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(UpperCAmelCase_)))
self.assertEqual(
encoding.offset_mapping[1] , (1 + len(UpperCAmelCase_), 1 + len(UpperCAmelCase_) + 1 + len(UpperCAmelCase_)) , )
| 59 |
import inspect
import os
import unittest
import torch
import accelerate
from accelerate import Accelerator
from accelerate.test_utils import execute_subprocess_async, require_multi_gpu
from accelerate.utils import patch_environment
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: List[Any] =inspect.getfile(accelerate.test_utils)
lowerCamelCase__: List[Any] =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_script.py"])
lowerCamelCase__: Any =os.path.sep.join(
mod_file.split(os.path.sep)[:-1] + ["scripts", "test_distributed_data_loop.py"])
lowerCamelCase__: Tuple =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_ops.py"])
@require_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : str) ->str:
'''simple docstring'''
print(F"""Found {torch.cuda.device_count()} devices.""")
lowerCamelCase__: Union[str, Any] =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path]
with patch_environment(omp_num_threads=1):
execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy())
@require_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[Any]:
'''simple docstring'''
print(F"""Found {torch.cuda.device_count()} devices.""")
lowerCamelCase__: Dict =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path]
print(F"""Command: {cmd}""")
with patch_environment(omp_num_threads=1):
execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy())
@require_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Tuple:
'''simple docstring'''
lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__)]
with patch_environment(omp_num_threads=1):
execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy())
@require_multi_gpu
def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]:
'''simple docstring'''
print(F"""Found {torch.cuda.device_count()} devices, using 2 devices only""")
lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path]
with patch_environment(omp_num_threads=1 , cuda_visible_devices="0,1"):
execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy())
if __name__ == "__main__":
__A = Accelerator()
__A = (accelerator.state.process_index + 2, 10)
__A = torch.randint(0, 10, shape).to(accelerator.device)
__A = ""
__A = accelerator.pad_across_processes(tensor)
if tensora.shape[0] != accelerator.state.num_processes + 1:
error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0."
if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor):
error_msg += "Tensors have different values."
if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0):
error_msg += "Padding was not done with the right value (0)."
__A = accelerator.pad_across_processes(tensor, pad_first=True)
if tensora.shape[0] != accelerator.state.num_processes + 1:
error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0."
__A = accelerator.state.num_processes - accelerator.state.process_index - 1
if not torch.equal(tensora[index:], tensor):
error_msg += "Tensors have different values."
if not torch.all(tensora[:index] == 0):
error_msg += "Padding was not done with the right value (0)."
# Raise error at the end to make sure we don't stop at the first failure.
if len(error_msg) > 0:
raise ValueError(error_msg)
| 59 | 1 |
from math import ceil
def lowerCAmelCase_ ( __a , __a ) -> Union[str, Any]:
"""simple docstring"""
lowerCamelCase__: str =list(range(0 , __a ) )
lowerCamelCase__: Dict =[item for sublist in list(device_map.values() ) for item in sublist]
# Duplicate check
lowerCamelCase__: List[str] =[]
for i in device_map_blocks:
if device_map_blocks.count(__a ) > 1 and i not in duplicate_blocks:
duplicate_blocks.append(__a )
# Missing blocks
lowerCamelCase__: Optional[Any] =[i for i in blocks if i not in device_map_blocks]
lowerCamelCase__: Union[str, Any] =[i for i in device_map_blocks if i not in blocks]
if len(__a ) != 0:
raise ValueError(
"Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device."
" These attention blocks were specified more than once: " + str(__a ) )
if len(__a ) != 0:
raise ValueError(
"There are attention blocks for this model that are not specified in the device_map. Add these attention "
"blocks to a device on the device_map: " + str(__a ) )
if len(__a ) != 0:
raise ValueError(
"The device_map contains more attention blocks than this model has. Remove these from the device_map:"
+ str(__a ) )
def lowerCAmelCase_ ( __a , __a ) -> Dict:
"""simple docstring"""
lowerCamelCase__: List[Any] =list(range(__a ) )
lowerCamelCase__: Tuple =int(ceil(n_layers / len(__a ) ) )
lowerCamelCase__: Tuple =[layers[i : i + n_blocks] for i in range(0 , __a , __a )]
return dict(zip(__a , __a ) )
| 59 |
from typing import List, Optional, Tuple, Union
import PIL
import torch
from torchvision import transforms
from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
from diffusers.schedulers import DDIMScheduler
from diffusers.utils import randn_tensor
__A = transforms.Compose(
[
transforms.Resize((256, 256)),
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5]),
]
)
def lowerCAmelCase_ ( __a ) -> str:
"""simple docstring"""
if isinstance(__a , torch.Tensor ):
return image
elif isinstance(__a , PIL.Image.Image ):
lowerCamelCase__: Any =[image]
lowerCamelCase__: Optional[Any] =[trans(img.convert("RGB" ) ) for img in image]
lowerCamelCase__: Dict =torch.stack(__a )
return image
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__(self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple) ->int:
'''simple docstring'''
super().__init__()
# make sure scheduler can always be converted to DDIM
lowerCamelCase__: Tuple =DDIMScheduler.from_config(scheduler.config)
self.register_modules(unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Union[str, Any]) ->Dict:
'''simple docstring'''
if strength < 0 or strength > 1:
raise ValueError(F"""The value of strength should in [0.0, 1.0] but is {strength}""")
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple) ->Tuple:
'''simple docstring'''
lowerCamelCase__: int =min(int(num_inference_steps * strength) , UpperCAmelCase_)
lowerCamelCase__: str =max(num_inference_steps - init_timestep , 0)
lowerCamelCase__: int =self.scheduler.timesteps[t_start:]
return timesteps, num_inference_steps - t_start
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int]=None) ->Optional[int]:
'''simple docstring'''
if not isinstance(UpperCAmelCase_ , (torch.Tensor, PIL.Image.Image, list)):
raise ValueError(
F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(UpperCAmelCase_)}""")
lowerCamelCase__: Optional[int] =image.to(device=UpperCAmelCase_ , dtype=UpperCAmelCase_)
if isinstance(UpperCAmelCase_ , UpperCAmelCase_) and len(UpperCAmelCase_) != batch_size:
raise ValueError(
F"""You have passed a list of generators of length {len(UpperCAmelCase_)}, but requested an effective batch"""
F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""")
lowerCamelCase__: Dict =init_latents.shape
lowerCamelCase__: int =randn_tensor(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=UpperCAmelCase_)
# get latents
print("add noise to latents at timestep" , UpperCAmelCase_)
lowerCamelCase__: Union[str, Any] =self.scheduler.add_noise(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: int =init_latents
return latents
@torch.no_grad()
def __call__(self : Tuple , UpperCAmelCase_ : Union[torch.FloatTensor, PIL.Image.Image] = None , UpperCAmelCase_ : float = 0.8 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , ) ->Union[ImagePipelineOutput, Tuple]:
'''simple docstring'''
self.check_inputs(UpperCAmelCase_)
# 2. Preprocess image
lowerCamelCase__: Dict =preprocess(UpperCAmelCase_)
# 3. set timesteps
self.scheduler.set_timesteps(UpperCAmelCase_ , device=self.device)
lowerCamelCase__ , lowerCamelCase__: str =self.get_timesteps(UpperCAmelCase_ , UpperCAmelCase_ , self.device)
lowerCamelCase__: Optional[int] =timesteps[:1].repeat(UpperCAmelCase_)
# 4. Prepare latent variables
lowerCamelCase__: int =self.prepare_latents(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , self.unet.dtype , self.device , UpperCAmelCase_)
lowerCamelCase__: Tuple =latents
# 5. Denoising loop
for t in self.progress_bar(UpperCAmelCase_):
# 1. predict noise model_output
lowerCamelCase__: Dict =self.unet(UpperCAmelCase_ , UpperCAmelCase_).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
lowerCamelCase__: Optional[int] =self.scheduler.step(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , eta=UpperCAmelCase_ , use_clipped_model_output=UpperCAmelCase_ , generator=UpperCAmelCase_ , ).prev_sample
lowerCamelCase__: str =(image / 2 + 0.5).clamp(0 , 1)
lowerCamelCase__: Optional[Any] =image.cpu().permute(0 , 2 , 3 , 1).numpy()
if output_type == "pil":
lowerCamelCase__: Dict =self.numpy_to_pil(UpperCAmelCase_)
if not return_dict:
return (image, latent_timestep.item())
return ImagePipelineOutput(images=UpperCAmelCase_)
| 59 | 1 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available
__A = {
"configuration_gpt_neo": ["GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoConfig", "GPTNeoOnnxConfig"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
"GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST",
"GPTNeoForCausalLM",
"GPTNeoForQuestionAnswering",
"GPTNeoForSequenceClassification",
"GPTNeoForTokenClassification",
"GPTNeoModel",
"GPTNeoPreTrainedModel",
"load_tf_weights_in_gpt_neo",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = [
"FlaxGPTNeoForCausalLM",
"FlaxGPTNeoModel",
"FlaxGPTNeoPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_gpt_neo import GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoConfig, GPTNeoOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_gpt_neo import (
GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST,
GPTNeoForCausalLM,
GPTNeoForQuestionAnswering,
GPTNeoForSequenceClassification,
GPTNeoForTokenClassification,
GPTNeoModel,
GPTNeoPreTrainedModel,
load_tf_weights_in_gpt_neo,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_gpt_neo import FlaxGPTNeoForCausalLM, FlaxGPTNeoModel, FlaxGPTNeoPreTrainedModel
else:
import sys
__A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 59 |
import argparse
import os
import pickle
import sys
import torch
from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl
from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils
from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
logging.set_verbosity_info()
# We do this to be able to load python 2 datasets pickles
# See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918
__A = data_utils.TransfoXLTokenizer
__A = data_utils.TransfoXLCorpus
__A = data_utils
__A = data_utils
def lowerCAmelCase_ ( __a , __a , __a , __a ) -> List[str]:
"""simple docstring"""
if transfo_xl_dataset_file:
# Convert a pre-processed corpus (see original TensorFlow repo)
with open(__a , "rb" ) as fp:
lowerCamelCase__: Optional[Any] =pickle.load(__a , encoding="latin1" )
# Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term)
lowerCamelCase__: Union[str, Any] =pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["pretrained_vocab_file"]
print(F"""Save vocabulary to {pytorch_vocab_dump_path}""" )
lowerCamelCase__: Any =corpus.vocab.__dict__
torch.save(__a , __a )
lowerCamelCase__: Dict =corpus.__dict__
corpus_dict_no_vocab.pop("vocab" , __a )
lowerCamelCase__: List[str] =pytorch_dump_folder_path + "/" + CORPUS_NAME
print(F"""Save dataset to {pytorch_dataset_dump_path}""" )
torch.save(__a , __a )
if tf_checkpoint_path:
# Convert a pre-trained TensorFlow model
lowerCamelCase__: Optional[Any] =os.path.abspath(__a )
lowerCamelCase__: Dict =os.path.abspath(__a )
print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" )
# Initialise PyTorch model
if transfo_xl_config_file == "":
lowerCamelCase__: int =TransfoXLConfig()
else:
lowerCamelCase__: Any =TransfoXLConfig.from_json_file(__a )
print(F"""Building PyTorch model from configuration: {config}""" )
lowerCamelCase__: List[Any] =TransfoXLLMHeadModel(__a )
lowerCamelCase__: List[str] =load_tf_weights_in_transfo_xl(__a , __a , __a )
# Save pytorch-model
lowerCamelCase__: List[str] =os.path.join(__a , __a )
lowerCamelCase__: Tuple =os.path.join(__a , __a )
print(F"""Save PyTorch model to {os.path.abspath(__a )}""" )
torch.save(model.state_dict() , __a )
print(F"""Save configuration file to {os.path.abspath(__a )}""" )
with open(__a , "w" , encoding="utf-8" ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
parser.add_argument(
"--pytorch_dump_folder_path",
default=None,
type=str,
required=True,
help="Path to the folder to store the PyTorch model or dataset/vocab.",
)
parser.add_argument(
"--tf_checkpoint_path",
default="",
type=str,
help="An optional path to a TensorFlow checkpoint path to be converted.",
)
parser.add_argument(
"--transfo_xl_config_file",
default="",
type=str,
help=(
"An optional config json file corresponding to the pre-trained BERT model. \n"
"This specifies the model architecture."
),
)
parser.add_argument(
"--transfo_xl_dataset_file",
default="",
type=str,
help="An optional dataset file to be converted in a vocabulary.",
)
__A = parser.parse_args()
convert_transfo_xl_checkpoint_to_pytorch(
args.tf_checkpoint_path,
args.transfo_xl_config_file,
args.pytorch_dump_folder_path,
args.transfo_xl_dataset_file,
)
| 59 | 1 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
__A = logging.get_logger(__name__)
__A = {
"microsoft/focalnet-tiny": "https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json",
}
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = "focalnet"
def __init__(self : List[Any] , UpperCAmelCase_ : List[str]=224 , UpperCAmelCase_ : Optional[int]=4 , UpperCAmelCase_ : int=3 , UpperCAmelCase_ : Any=96 , UpperCAmelCase_ : Optional[Any]=False , UpperCAmelCase_ : str=[192, 384, 768, 768] , UpperCAmelCase_ : Optional[Any]=[2, 2, 6, 2] , UpperCAmelCase_ : Optional[Any]=[2, 2, 2, 2] , UpperCAmelCase_ : int=[3, 3, 3, 3] , UpperCAmelCase_ : List[str]="gelu" , UpperCAmelCase_ : Optional[Any]=4.0 , UpperCAmelCase_ : str=0.0 , UpperCAmelCase_ : Dict=0.1 , UpperCAmelCase_ : Dict=False , UpperCAmelCase_ : List[Any]=1E-4 , UpperCAmelCase_ : List[Any]=False , UpperCAmelCase_ : List[Any]=False , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : Union[str, Any]=0.02 , UpperCAmelCase_ : Union[str, Any]=1E-5 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Tuple=None , **UpperCAmelCase_ : Tuple , ) ->Optional[int]:
'''simple docstring'''
super().__init__(**UpperCAmelCase_)
lowerCamelCase__: str =image_size
lowerCamelCase__: Tuple =patch_size
lowerCamelCase__: List[str] =num_channels
lowerCamelCase__: Dict =embed_dim
lowerCamelCase__: str =use_conv_embed
lowerCamelCase__: Union[str, Any] =hidden_sizes
lowerCamelCase__: Optional[Any] =depths
lowerCamelCase__: Union[str, Any] =focal_levels
lowerCamelCase__: Optional[Any] =focal_windows
lowerCamelCase__: Tuple =hidden_act
lowerCamelCase__: List[str] =mlp_ratio
lowerCamelCase__: Optional[int] =hidden_dropout_prob
lowerCamelCase__: int =drop_path_rate
lowerCamelCase__: List[str] =use_layerscale
lowerCamelCase__: Optional[Any] =layerscale_value
lowerCamelCase__: Dict =use_post_layernorm
lowerCamelCase__: Any =use_post_layernorm_in_modulation
lowerCamelCase__: List[Any] =normalize_modulator
lowerCamelCase__: Union[str, Any] =initializer_range
lowerCamelCase__: List[str] =layer_norm_eps
lowerCamelCase__: Dict =encoder_stride
lowerCamelCase__: Optional[Any] =["stem"] + [F"""stage{idx}""" for idx in range(1 , len(self.depths) + 1)]
lowerCamelCase__ , lowerCamelCase__: Any =get_aligned_output_features_output_indices(
out_features=UpperCAmelCase_ , out_indices=UpperCAmelCase_ , stage_names=self.stage_names)
| 59 |
from collections import UserDict
from typing import List, Union
from ..utils import (
add_end_docstrings,
is_tf_available,
is_torch_available,
is_vision_available,
logging,
requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_vision_available():
from PIL import Image
from ..image_utils import load_image
if is_torch_available():
from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
if is_tf_available():
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
from ..tf_utils import stable_softmax
__A = logging.get_logger(__name__)
@add_end_docstrings(__SCREAMING_SNAKE_CASE )
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__(self : Optional[int] , **UpperCAmelCase_ : List[Any]) ->List[str]:
'''simple docstring'''
super().__init__(**UpperCAmelCase_)
requires_backends(self , "vision")
self.check_model_type(
TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
if self.framework == "tf"
else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING)
def __call__(self : List[str] , UpperCAmelCase_ : Union[str, List[str], "Image", List["Image"]] , **UpperCAmelCase_ : List[Any]) ->Tuple:
'''simple docstring'''
return super().__call__(UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[Any] , **UpperCAmelCase_ : Optional[int]) ->Any:
'''simple docstring'''
lowerCamelCase__: Optional[int] ={}
if "candidate_labels" in kwargs:
lowerCamelCase__: Tuple =kwargs["candidate_labels"]
if "hypothesis_template" in kwargs:
lowerCamelCase__: Tuple =kwargs["hypothesis_template"]
return preprocess_params, {}, {}
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Optional[Any]="This is a photo of {}.") ->str:
'''simple docstring'''
lowerCamelCase__: int =load_image(UpperCAmelCase_)
lowerCamelCase__: Any =self.image_processor(images=[image] , return_tensors=self.framework)
lowerCamelCase__: Any =candidate_labels
lowerCamelCase__: List[str] =[hypothesis_template.format(UpperCAmelCase_) for x in candidate_labels]
lowerCamelCase__: int =self.tokenizer(UpperCAmelCase_ , return_tensors=self.framework , padding=UpperCAmelCase_)
lowerCamelCase__: str =[text_inputs]
return inputs
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Any) ->Tuple:
'''simple docstring'''
lowerCamelCase__: int =model_inputs.pop("candidate_labels")
lowerCamelCase__: List[str] =model_inputs.pop("text_inputs")
if isinstance(text_inputs[0] , UpperCAmelCase_):
lowerCamelCase__: List[Any] =text_inputs[0]
else:
# Batching case.
lowerCamelCase__: List[Any] =text_inputs[0][0]
lowerCamelCase__: List[str] =self.model(**UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: str ={
"candidate_labels": candidate_labels,
"logits": outputs.logits_per_image,
}
return model_outputs
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Union[str, Any]) ->int:
'''simple docstring'''
lowerCamelCase__: List[Any] =model_outputs.pop("candidate_labels")
lowerCamelCase__: Optional[int] =model_outputs["logits"][0]
if self.framework == "pt":
lowerCamelCase__: Optional[Any] =logits.softmax(dim=-1).squeeze(-1)
lowerCamelCase__: Optional[Any] =probs.tolist()
if not isinstance(UpperCAmelCase_ , UpperCAmelCase_):
lowerCamelCase__: Optional[int] =[scores]
elif self.framework == "tf":
lowerCamelCase__: List[str] =stable_softmax(UpperCAmelCase_ , axis=-1)
lowerCamelCase__: Optional[int] =probs.numpy().tolist()
else:
raise ValueError(F"""Unsupported framework: {self.framework}""")
lowerCamelCase__: Optional[int] =[
{"score": score, "label": candidate_label}
for score, candidate_label in sorted(zip(UpperCAmelCase_ , UpperCAmelCase_) , key=lambda UpperCAmelCase_: -x[0])
]
return result
| 59 | 1 |
from maths.prime_check import is_prime
def lowerCAmelCase_ ( __a ) -> int:
"""simple docstring"""
if not isinstance(__a , __a ):
lowerCamelCase__: Any =F"""Input value of [number={number}] must be an integer"""
raise TypeError(__a )
if is_prime(__a ) and is_prime(number + 2 ):
return number + 2
else:
return -1
if __name__ == "__main__":
import doctest
doctest.testmod()
| 59 |
import json
import os
from dataclasses import dataclass
from functools import partial
from typing import Callable
import flax.linen as nn
import jax
import jax.numpy as jnp
import joblib
import optax
import wandb
from flax import jax_utils, struct, traverse_util
from flax.serialization import from_bytes, to_bytes
from flax.training import train_state
from flax.training.common_utils import shard
from tqdm.auto import tqdm
from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering
from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = 42
lowercase_ = jnp.floataa
lowercase_ = True
def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]:
'''simple docstring'''
super().setup()
lowerCamelCase__: int =nn.Dense(5 , dtype=self.dtype)
def __call__(self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Any) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =super().__call__(*UpperCAmelCase_ , **UpperCAmelCase_)
lowerCamelCase__: int =self.cls(outputs[2])
return outputs[:2] + (cls_out,)
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = FlaxBigBirdForNaturalQuestionsModule
def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a ) -> Tuple:
"""simple docstring"""
def cross_entropy(__a , __a , __a=None ):
lowerCamelCase__: Tuple =logits.shape[-1]
lowerCamelCase__: Tuple =(labels[..., None] == jnp.arange(__a )[None]).astype("f4" )
lowerCamelCase__: str =jax.nn.log_softmax(__a , axis=-1 )
lowerCamelCase__: Optional[Any] =-jnp.sum(labels * logits , axis=-1 )
if reduction is not None:
lowerCamelCase__: Optional[Any] =reduction(__a )
return loss
lowerCamelCase__: str =partial(__a , reduction=jnp.mean )
lowerCamelCase__: str =cross_entropy(__a , __a )
lowerCamelCase__: Optional[int] =cross_entropy(__a , __a )
lowerCamelCase__: Optional[Any] =cross_entropy(__a , __a )
return (start_loss + end_loss + pooled_loss) / 3
@dataclass
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
lowercase_ = "google/bigbird-roberta-base"
lowercase_ = 3000
lowercase_ = 1_0500
lowercase_ = 128
lowercase_ = 3
lowercase_ = 1
lowercase_ = 5
# tx_args
lowercase_ = 3E-5
lowercase_ = 0.0
lowercase_ = 2_0000
lowercase_ = 0.0095
lowercase_ = "bigbird-roberta-natural-questions"
lowercase_ = "training-expt"
lowercase_ = "data/nq-training.jsonl"
lowercase_ = "data/nq-validation.jsonl"
def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[str]:
'''simple docstring'''
os.makedirs(self.base_dir , exist_ok=UpperCAmelCase_)
lowerCamelCase__: Optional[Any] =os.path.join(self.base_dir , self.save_dir)
lowerCamelCase__: List[str] =self.batch_size_per_device * jax.device_count()
@dataclass
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
lowercase_ = 42
lowercase_ = 4096 # no dynamic padding on TPUs
def __call__(self : List[Any] , UpperCAmelCase_ : Optional[Any]) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =self.collate_fn(UpperCAmelCase_)
lowerCamelCase__: List[Any] =jax.tree_util.tree_map(UpperCAmelCase_ , UpperCAmelCase_)
return batch
def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List[str]) ->List[Any]:
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__: List[Any] =self.fetch_inputs(features["input_ids"])
lowerCamelCase__: Union[str, Any] ={
"input_ids": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa),
"attention_mask": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa),
"start_labels": jnp.array(features["start_token"] , dtype=jnp.intaa),
"end_labels": jnp.array(features["end_token"] , dtype=jnp.intaa),
"pooled_labels": jnp.array(features["category"] , dtype=jnp.intaa),
}
return batch
def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : list) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Tuple =[self._fetch_inputs(UpperCAmelCase_) for ids in input_ids]
return zip(*UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : list) ->Any:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =[1 for _ in range(len(UpperCAmelCase_))]
while len(UpperCAmelCase_) < self.max_length:
input_ids.append(self.pad_id)
attention_mask.append(0)
return input_ids, attention_mask
def lowerCAmelCase_ ( __a , __a , __a=None ) -> str:
"""simple docstring"""
if seed is not None:
lowerCamelCase__: Any =dataset.shuffle(seed=__a )
for i in range(len(__a ) // batch_size ):
lowerCamelCase__: Any =dataset[i * batch_size : (i + 1) * batch_size]
yield dict(__a )
@partial(jax.pmap , axis_name="batch" )
def lowerCAmelCase_ ( __a , __a , **__a ) -> List[str]:
"""simple docstring"""
def loss_fn(__a ):
lowerCamelCase__: Optional[int] =model_inputs.pop("start_labels" )
lowerCamelCase__: int =model_inputs.pop("end_labels" )
lowerCamelCase__: List[str] =model_inputs.pop("pooled_labels" )
lowerCamelCase__: Optional[int] =state.apply_fn(**__a , params=__a , dropout_rng=__a , train=__a )
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[Any] =outputs
return state.loss_fn(
__a , __a , __a , __a , __a , __a , )
lowerCamelCase__ , lowerCamelCase__: int =jax.random.split(__a )
lowerCamelCase__: Optional[Any] =jax.value_and_grad(__a )
lowerCamelCase__ , lowerCamelCase__: List[str] =grad_fn(state.params )
lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" )
lowerCamelCase__: List[str] =jax.lax.pmean(__a , "batch" )
lowerCamelCase__: List[str] =state.apply_gradients(grads=__a )
return state, metrics, new_drp_rng
@partial(jax.pmap , axis_name="batch" )
def lowerCAmelCase_ ( __a , **__a ) -> List[Any]:
"""simple docstring"""
lowerCamelCase__: int =model_inputs.pop("start_labels" )
lowerCamelCase__: List[str] =model_inputs.pop("end_labels" )
lowerCamelCase__: int =model_inputs.pop("pooled_labels" )
lowerCamelCase__: Optional[Any] =state.apply_fn(**__a , params=state.params , train=__a )
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[str] =outputs
lowerCamelCase__: Optional[int] =state.loss_fn(__a , __a , __a , __a , __a , __a )
lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" )
return metrics
class _SCREAMING_SNAKE_CASE ( train_state.TrainState ):
'''simple docstring'''
lowercase_ = struct.field(pytree_node=__SCREAMING_SNAKE_CASE )
@dataclass
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = None
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int=None) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Dict =model.params
lowerCamelCase__: Tuple =TrainState.create(
apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , loss_fn=UpperCAmelCase_ , )
if ckpt_dir is not None:
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =restore_checkpoint(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Tuple ={
"lr": args.lr,
"init_lr": args.init_lr,
"warmup_steps": args.warmup_steps,
"num_train_steps": num_train_steps,
"weight_decay": args.weight_decay,
}
lowerCamelCase__ , lowerCamelCase__: List[Any] =build_tx(**UpperCAmelCase_)
lowerCamelCase__: str =train_state.TrainState(
step=UpperCAmelCase_ , apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , opt_state=UpperCAmelCase_ , )
lowerCamelCase__: Tuple =args
lowerCamelCase__: Tuple =data_collator
lowerCamelCase__: str =lr
lowerCamelCase__: Dict =params
lowerCamelCase__: List[str] =jax_utils.replicate(UpperCAmelCase_)
return state
def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple) ->Optional[Any]:
'''simple docstring'''
lowerCamelCase__: Tuple =self.args
lowerCamelCase__: Any =len(UpperCAmelCase_) // args.batch_size
lowerCamelCase__: List[str] =jax.random.PRNGKey(0)
lowerCamelCase__: Optional[Any] =jax.random.split(UpperCAmelCase_ , jax.device_count())
for epoch in range(args.max_epochs):
lowerCamelCase__: Union[str, Any] =jnp.array(0 , dtype=jnp.floataa)
lowerCamelCase__: str =get_batched_dataset(UpperCAmelCase_ , args.batch_size , seed=UpperCAmelCase_)
lowerCamelCase__: Dict =0
for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc=F"""Running EPOCH-{epoch}"""):
lowerCamelCase__: List[str] =self.data_collator(UpperCAmelCase_)
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.train_step_fn(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_)
running_loss += jax_utils.unreplicate(metrics["loss"])
i += 1
if i % args.logging_steps == 0:
lowerCamelCase__: Optional[int] =jax_utils.unreplicate(state.step)
lowerCamelCase__: List[Any] =running_loss.item() / i
lowerCamelCase__: Tuple =self.scheduler_fn(state_step - 1)
lowerCamelCase__: Union[str, Any] =self.evaluate(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Dict ={
"step": state_step.item(),
"eval_loss": eval_loss.item(),
"tr_loss": tr_loss,
"lr": lr.item(),
}
tqdm.write(str(UpperCAmelCase_))
self.logger.log(UpperCAmelCase_ , commit=UpperCAmelCase_)
if i % args.save_steps == 0:
self.save_checkpoint(args.save_dir + F"""-e{epoch}-s{i}""" , state=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str) ->Any:
'''simple docstring'''
lowerCamelCase__: List[Any] =get_batched_dataset(UpperCAmelCase_ , self.args.batch_size)
lowerCamelCase__: List[str] =len(UpperCAmelCase_) // self.args.batch_size
lowerCamelCase__: str =jnp.array(0 , dtype=jnp.floataa)
lowerCamelCase__: Optional[Any] =0
for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc="Evaluating ... "):
lowerCamelCase__: int =self.data_collator(UpperCAmelCase_)
lowerCamelCase__: str =self.val_step_fn(UpperCAmelCase_ , **UpperCAmelCase_)
running_loss += jax_utils.unreplicate(metrics["loss"])
i += 1
return running_loss / i
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int]) ->int:
'''simple docstring'''
lowerCamelCase__: Any =jax_utils.unreplicate(UpperCAmelCase_)
print(F"""SAVING CHECKPOINT IN {save_dir}""" , end=" ... ")
self.model_save_fn(UpperCAmelCase_ , params=state.params)
with open(os.path.join(UpperCAmelCase_ , "opt_state.msgpack") , "wb") as f:
f.write(to_bytes(state.opt_state))
joblib.dump(self.args , os.path.join(UpperCAmelCase_ , "args.joblib"))
joblib.dump(self.data_collator , os.path.join(UpperCAmelCase_ , "data_collator.joblib"))
with open(os.path.join(UpperCAmelCase_ , "training_state.json") , "w") as f:
json.dump({"step": state.step.item()} , UpperCAmelCase_)
print("DONE")
def lowerCAmelCase_ ( __a , __a ) -> str:
"""simple docstring"""
print(F"""RESTORING CHECKPOINT FROM {save_dir}""" , end=" ... " )
with open(os.path.join(__a , "flax_model.msgpack" ) , "rb" ) as f:
lowerCamelCase__: Tuple =from_bytes(state.params , f.read() )
with open(os.path.join(__a , "opt_state.msgpack" ) , "rb" ) as f:
lowerCamelCase__: Optional[int] =from_bytes(state.opt_state , f.read() )
lowerCamelCase__: Any =joblib.load(os.path.join(__a , "args.joblib" ) )
lowerCamelCase__: Union[str, Any] =joblib.load(os.path.join(__a , "data_collator.joblib" ) )
with open(os.path.join(__a , "training_state.json" ) , "r" ) as f:
lowerCamelCase__: Optional[Any] =json.load(__a )
lowerCamelCase__: Any =training_state["step"]
print("DONE" )
return params, opt_state, step, args, data_collator
def lowerCAmelCase_ ( __a , __a , __a , __a ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase__: int =num_train_steps - warmup_steps
lowerCamelCase__: str =optax.linear_schedule(init_value=__a , end_value=__a , transition_steps=__a )
lowerCamelCase__: Optional[Any] =optax.linear_schedule(init_value=__a , end_value=1e-7 , transition_steps=__a )
lowerCamelCase__: List[Any] =optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] )
return lr
def lowerCAmelCase_ ( __a , __a , __a , __a , __a ) -> str:
"""simple docstring"""
def weight_decay_mask(__a ):
lowerCamelCase__: List[str] =traverse_util.flatten_dict(__a )
lowerCamelCase__: List[str] ={k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()}
return traverse_util.unflatten_dict(__a )
lowerCamelCase__: Optional[Any] =scheduler_fn(__a , __a , __a , __a )
lowerCamelCase__: Tuple =optax.adamw(learning_rate=__a , weight_decay=__a , mask=__a )
return tx, lr
| 59 | 1 |
from collections import namedtuple
import requests
from lxml import html # type: ignore
__A = namedtuple("covid_data", "cases deaths recovered")
def lowerCAmelCase_ ( __a = "https://www.worldometers.info/coronavirus/" ) -> covid_data:
"""simple docstring"""
lowerCamelCase__: int ="//div[@class = \"maincounter-number\"]/span/text()"
return covid_data(*html.fromstring(requests.get(__a ).content ).xpath(__a ) )
__A = "Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}"
print(fmt.format(*covid_stats()))
| 59 |
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = ["image_processor", "tokenizer"]
lowercase_ = "ChineseCLIPImageProcessor"
lowercase_ = ("BertTokenizer", "BertTokenizerFast")
def __init__(self : Any , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Union[str, Any]=None , **UpperCAmelCase_ : str) ->Dict:
'''simple docstring'''
lowerCamelCase__: str =None
if "feature_extractor" in kwargs:
warnings.warn(
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
" instead." , UpperCAmelCase_ , )
lowerCamelCase__: Tuple =kwargs.pop("feature_extractor")
lowerCamelCase__: Optional[int] =image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError("You need to specify an `image_processor`.")
if tokenizer is None:
raise ValueError("You need to specify a `tokenizer`.")
super().__init__(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Optional[int] =self.image_processor
def __call__(self : int , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[int]:
'''simple docstring'''
if text is None and images is None:
raise ValueError("You have to specify either text or images. Both cannot be none.")
if text is not None:
lowerCamelCase__: Dict =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if images is not None:
lowerCamelCase__: List[str] =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if text is not None and images is not None:
lowerCamelCase__: Union[str, Any] =image_features.pixel_values
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int) ->str:
'''simple docstring'''
return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any]) ->Dict:
'''simple docstring'''
return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_)
@property
def SCREAMING_SNAKE_CASE_ (self : int) ->List[str]:
'''simple docstring'''
lowerCamelCase__: str =self.tokenizer.model_input_names
lowerCamelCase__: Union[str, Any] =self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
@property
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str:
'''simple docstring'''
warnings.warn(
"`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , UpperCAmelCase_ , )
return self.image_processor_class
| 59 | 1 |
import requests
__A = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey="
def lowerCAmelCase_ ( __a ) -> None:
"""simple docstring"""
lowerCamelCase__: Union[str, Any] =requests.get(_NEWS_API + bbc_news_api_key ).json()
# each article in the list is a dict
for i, article in enumerate(bbc_news_page["articles"] , 1 ):
print(F"""{i}.) {article["title"]}""" )
if __name__ == "__main__":
fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
| 59 |
from math import ceil, sqrt
def lowerCAmelCase_ ( __a = 1000000 ) -> int:
"""simple docstring"""
lowerCamelCase__: Any =0
for outer_width in range(3 , (limit // 4) + 2 ):
if outer_width**2 > limit:
lowerCamelCase__: Optional[int] =max(ceil(sqrt(outer_width**2 - limit ) ) , 1 )
else:
lowerCamelCase__: Tuple =1
if (outer_width - hole_width_lower_bound) % 2:
hole_width_lower_bound += 1
answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1
return answer
if __name__ == "__main__":
print(f'{solution() = }')
| 59 | 1 |
import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union
import torch
from filelock import FileLock
from torch.utils.data import Dataset
from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features
__A = logging.get_logger(__name__)
__A = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
__A = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
@dataclass
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
lowercase_ = field(
default=__SCREAMING_SNAKE_CASE , metadata={"help": "Model type selected in the list: " + ", ".join(__SCREAMING_SNAKE_CASE )} )
lowercase_ = field(
default=__SCREAMING_SNAKE_CASE , metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."} )
lowercase_ = 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."
)
} , )
lowercase_ = field(
default=128 , metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."} , )
lowercase_ = field(
default=64 , metadata={
"help": (
"The maximum number of tokens for the question. Questions longer than this will "
"be truncated to this length."
)
} , )
lowercase_ = field(
default=30 , metadata={
"help": (
"The maximum length of an answer that can be generated. This is needed because the start "
"and end predictions are not conditioned on one another."
)
} , )
lowercase_ = field(
default=__SCREAMING_SNAKE_CASE , metadata={"help": "Overwrite the cached training and evaluation sets"} )
lowercase_ = field(
default=__SCREAMING_SNAKE_CASE , metadata={"help": "If true, the SQuAD examples contain some that do not have an answer."} )
lowercase_ = field(
default=0.0 , metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."} )
lowercase_ = field(
default=20 , metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."} )
lowercase_ = field(
default=0 , metadata={
"help": (
"language id of input for language-specific xlm models (see"
" tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"
)
} , )
lowercase_ = field(default=1 , metadata={"help": "multiple threads for converting example to features"} )
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = "train"
lowercase_ = "dev"
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
lowercase_ = 42
def __init__(self : Dict , UpperCAmelCase_ : SquadDataTrainingArguments , UpperCAmelCase_ : PreTrainedTokenizer , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : Union[str, Split] = Split.train , UpperCAmelCase_ : Optional[bool] = False , UpperCAmelCase_ : Optional[str] = None , UpperCAmelCase_ : Optional[str] = "pt" , ) ->Optional[int]:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =args
lowerCamelCase__: int =is_language_sensitive
lowerCamelCase__: Union[str, Any] =SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
if isinstance(UpperCAmelCase_ , UpperCAmelCase_):
try:
lowerCamelCase__: Tuple =Split[mode]
except KeyError:
raise KeyError("mode is not a valid split name")
lowerCamelCase__: str =mode
# Load data features from cache or dataset file
lowerCamelCase__: Union[str, Any] ="v2" if args.version_2_with_negative else "v1"
lowerCamelCase__: Any =os.path.join(
cache_dir if cache_dir is not None else args.data_dir , F"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}""" , )
# Make sure only the first process in distributed training processes the dataset,
# and the others will use the cache.
lowerCamelCase__: List[str] =cached_features_file + ".lock"
with FileLock(UpperCAmelCase_):
if os.path.exists(UpperCAmelCase_) and not args.overwrite_cache:
lowerCamelCase__: Optional[Any] =time.time()
lowerCamelCase__: List[Any] =torch.load(UpperCAmelCase_)
# Legacy cache files have only features, while new cache files
# will have dataset and examples also.
lowerCamelCase__: Dict =self.old_features["features"]
lowerCamelCase__: Tuple =self.old_features.get("dataset" , UpperCAmelCase_)
lowerCamelCase__: Tuple =self.old_features.get("examples" , UpperCAmelCase_)
logger.info(
F"""Loading features from cached file {cached_features_file} [took %.3f s]""" , time.time() - start)
if self.dataset is None or self.examples is None:
logger.warning(
F"""Deleting cached file {cached_features_file} will allow dataset and examples to be cached in"""
" future run")
else:
if mode == Split.dev:
lowerCamelCase__: Dict =self.processor.get_dev_examples(args.data_dir)
else:
lowerCamelCase__: int =self.processor.get_train_examples(args.data_dir)
lowerCamelCase__ , lowerCamelCase__: int =squad_convert_examples_to_features(
examples=self.examples , tokenizer=UpperCAmelCase_ , max_seq_length=args.max_seq_length , doc_stride=args.doc_stride , max_query_length=args.max_query_length , is_training=mode == Split.train , threads=args.threads , return_dataset=UpperCAmelCase_ , )
lowerCamelCase__: Any =time.time()
torch.save(
{"features": self.features, "dataset": self.dataset, "examples": self.examples} , UpperCAmelCase_ , )
# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
logger.info(
F"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]""")
def __len__(self : List[Any]) ->Tuple:
'''simple docstring'''
return len(self.features)
def __getitem__(self : str , UpperCAmelCase_ : Dict) ->Dict[str, torch.Tensor]:
'''simple docstring'''
lowerCamelCase__: str =self.features[i]
lowerCamelCase__: Dict =torch.tensor(feature.input_ids , dtype=torch.long)
lowerCamelCase__: Dict =torch.tensor(feature.attention_mask , dtype=torch.long)
lowerCamelCase__: str =torch.tensor(feature.token_type_ids , dtype=torch.long)
lowerCamelCase__: Union[str, Any] =torch.tensor(feature.cls_index , dtype=torch.long)
lowerCamelCase__: Optional[int] =torch.tensor(feature.p_mask , dtype=torch.float)
lowerCamelCase__: Union[str, Any] =torch.tensor(feature.is_impossible , dtype=torch.float)
lowerCamelCase__: List[str] ={
"input_ids": input_ids,
"attention_mask": attention_mask,
"token_type_ids": token_type_ids,
}
if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
del inputs["token_type_ids"]
if self.args.model_type in ["xlnet", "xlm"]:
inputs.update({"cls_index": cls_index, "p_mask": p_mask})
if self.args.version_2_with_negative:
inputs.update({"is_impossible": is_impossible})
if self.is_language_sensitive:
inputs.update({"langs": (torch.ones(input_ids.shape , dtype=torch.intaa) * self.args.lang_id)})
if self.mode == Split.train:
lowerCamelCase__: int =torch.tensor(feature.start_position , dtype=torch.long)
lowerCamelCase__: int =torch.tensor(feature.end_position , dtype=torch.long)
inputs.update({"start_positions": start_positions, "end_positions": end_positions})
return inputs
| 59 |
def lowerCAmelCase_ ( __a = 50000000 ) -> int:
"""simple docstring"""
lowerCamelCase__: Any =set()
lowerCamelCase__: int =int((limit - 24) ** (1 / 2) )
lowerCamelCase__: Tuple =set(range(3 , prime_square_limit + 1 , 2 ) )
primes.add(2 )
for p in range(3 , prime_square_limit + 1 , 2 ):
if p not in primes:
continue
primes.difference_update(set(range(p * p , prime_square_limit + 1 , __a ) ) )
for primea in primes:
lowerCamelCase__: Optional[int] =primea * primea
for primea in primes:
lowerCamelCase__: List[str] =primea * primea * primea
if square + cube >= limit - 16:
break
for primea in primes:
lowerCamelCase__: int =primea * primea * primea * primea
lowerCamelCase__: Optional[Any] =square + cube + tetr
if total >= limit:
break
ret.add(__a )
return len(__a )
if __name__ == "__main__":
print(f'{solution() = }')
| 59 | 1 |
import copy
from dataclasses import dataclass, field
from typing import ClassVar, Dict
from ..features import ClassLabel, Features, Image
from .base import TaskTemplate
@dataclass(frozen=__SCREAMING_SNAKE_CASE )
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} )
lowercase_ = Features({"image": Image()} )
lowercase_ = Features({"labels": ClassLabel} )
lowercase_ = "image"
lowercase_ = "labels"
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : List[Any]) ->List[str]:
'''simple docstring'''
if self.label_column not in features:
raise ValueError(F"""Column {self.label_column} is not present in features.""")
if not isinstance(features[self.label_column] , UpperCAmelCase_):
raise ValueError(F"""Column {self.label_column} is not a ClassLabel.""")
lowerCamelCase__: int =copy.deepcopy(self)
lowerCamelCase__: Dict =self.label_schema.copy()
lowerCamelCase__: Optional[int] =features[self.label_column]
lowerCamelCase__: Dict =label_schema
return task_template
@property
def SCREAMING_SNAKE_CASE_ (self : Dict) ->Dict[str, str]:
'''simple docstring'''
return {
self.image_column: "image",
self.label_column: "labels",
}
| 59 |
from __future__ import annotations
from decimal import Decimal
from math import * # noqa: F403
from sympy import diff
def lowerCAmelCase_ ( __a , __a , __a = 10**-10 ) -> float:
"""simple docstring"""
lowerCamelCase__: List[str] =a
while True:
lowerCamelCase__: Optional[Any] =Decimal(__a ) - (
Decimal(eval(__a ) ) / Decimal(eval(str(diff(__a ) ) ) ) # noqa: S307
)
# This number dictates the accuracy of the answer
if abs(eval(__a ) ) < precision: # noqa: S307
return float(__a )
# Let's Execute
if __name__ == "__main__":
# Find root of trigonometric function
# Find value of pi
print(f'The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}')
# Find root of polynomial
print(f'The root of x**2 - 5*x + 2 = 0 is {newton_raphson("x**2 - 5*x + 2", 0.4)}')
# Find Square Root of 5
print(f'The root of log(x) - 1 = 0 is {newton_raphson("log(x) - 1", 2)}')
# Exponential Roots
print(f'The root of exp(x) - 1 = 0 is {newton_raphson("exp(x) - 1", 0)}')
| 59 | 1 |
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxSeqaSeqConfigWithPast
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {
"t5-small": "https://huggingface.co/t5-small/resolve/main/config.json",
"t5-base": "https://huggingface.co/t5-base/resolve/main/config.json",
"t5-large": "https://huggingface.co/t5-large/resolve/main/config.json",
"t5-3b": "https://huggingface.co/t5-3b/resolve/main/config.json",
"t5-11b": "https://huggingface.co/t5-11b/resolve/main/config.json",
}
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = "t5"
lowercase_ = ["past_key_values"]
lowercase_ = {"hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"}
def __init__(self : List[str] , UpperCAmelCase_ : int=32_128 , UpperCAmelCase_ : Dict=512 , UpperCAmelCase_ : List[Any]=64 , UpperCAmelCase_ : int=2_048 , UpperCAmelCase_ : Optional[Any]=6 , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : Optional[int]=8 , UpperCAmelCase_ : Dict=32 , UpperCAmelCase_ : List[str]=128 , UpperCAmelCase_ : Dict=0.1 , UpperCAmelCase_ : int=1E-6 , UpperCAmelCase_ : Any=1.0 , UpperCAmelCase_ : Optional[Any]="relu" , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : Any=0 , UpperCAmelCase_ : str=1 , **UpperCAmelCase_ : str , ) ->str:
'''simple docstring'''
lowerCamelCase__: int =vocab_size
lowerCamelCase__: Optional[int] =d_model
lowerCamelCase__: List[str] =d_kv
lowerCamelCase__: Optional[Any] =d_ff
lowerCamelCase__: Tuple =num_layers
lowerCamelCase__: str =(
num_decoder_layers if num_decoder_layers is not None else self.num_layers
) # default = symmetry
lowerCamelCase__: Optional[int] =num_heads
lowerCamelCase__: Optional[Any] =relative_attention_num_buckets
lowerCamelCase__: Optional[int] =relative_attention_max_distance
lowerCamelCase__: Tuple =dropout_rate
lowerCamelCase__: Union[str, Any] =layer_norm_epsilon
lowerCamelCase__: str =initializer_factor
lowerCamelCase__: List[str] =feed_forward_proj
lowerCamelCase__: str =use_cache
lowerCamelCase__: Dict =self.feed_forward_proj.split("-")
lowerCamelCase__: Optional[int] =act_info[-1]
lowerCamelCase__: Optional[Any] =act_info[0] == "gated"
if len(UpperCAmelCase_) > 1 and act_info[0] != "gated" or len(UpperCAmelCase_) > 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":
lowerCamelCase__: Union[str, Any] ="gelu_new"
super().__init__(
pad_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , is_encoder_decoder=UpperCAmelCase_ , **UpperCAmelCase_ , )
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
@property
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Mapping[str, Mapping[int, str]]:
'''simple docstring'''
lowerCamelCase__: Dict ={
"input_ids": {0: "batch", 1: "encoder_sequence"},
"attention_mask": {0: "batch", 1: "encoder_sequence"},
}
if self.use_past:
lowerCamelCase__: Tuple ="past_encoder_sequence + sequence"
lowerCamelCase__: str ={0: "batch"}
lowerCamelCase__: Optional[Any] ={0: "batch", 1: "past_decoder_sequence + sequence"}
else:
lowerCamelCase__: Optional[int] ={0: "batch", 1: "decoder_sequence"}
lowerCamelCase__: Optional[int] ={0: "batch", 1: "decoder_sequence"}
if self.use_past:
self.fill_with_past_key_values_(UpperCAmelCase_ , direction="inputs")
return common_inputs
@property
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->int:
'''simple docstring'''
return 13
| 59 |
import numpy as np
from numpy import ndarray
from scipy.optimize import Bounds, LinearConstraint, minimize
def lowerCAmelCase_ ( __a ) -> float:
"""simple docstring"""
return np.dot(__a , __a )
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__(self : List[str] , *,
UpperCAmelCase_ : float = np.inf , UpperCAmelCase_ : str = "linear" , UpperCAmelCase_ : float = 0.0 , ) ->None:
'''simple docstring'''
lowerCamelCase__: Dict =regularization
lowerCamelCase__: Any =gamma
if kernel == "linear":
lowerCamelCase__: Dict =self.__linear
elif kernel == "rbf":
if self.gamma == 0:
raise ValueError("rbf kernel requires gamma")
if not isinstance(self.gamma , (float, int)):
raise ValueError("gamma must be float or int")
if not self.gamma > 0:
raise ValueError("gamma must be > 0")
lowerCamelCase__: Tuple =self.__rbf
# in the future, there could be a default value like in sklearn
# sklear: def_gamma = 1/(n_features * X.var()) (wiki)
# previously it was 1/(n_features)
else:
lowerCamelCase__: Optional[Any] =F"""Unknown kernel: {kernel}"""
raise ValueError(UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float:
'''simple docstring'''
return np.dot(UpperCAmelCase_ , UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float:
'''simple docstring'''
return np.exp(-(self.gamma * norm_squared(vectora - vectora)))
def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : list[ndarray] , UpperCAmelCase_ : ndarray) ->None:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =observations
lowerCamelCase__: Optional[int] =classes
# using Wolfe's Dual to calculate w.
# Primal problem: minimize 1/2*norm_squared(w)
# constraint: yn(w . xn + b) >= 1
#
# With l a vector
# Dual problem: maximize sum_n(ln) -
# 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm))
# constraint: self.C >= ln >= 0
# and sum_n(ln*yn) = 0
# Then we get w using w = sum_n(ln*yn*xn)
# At the end we can get b ~= mean(yn - w . xn)
#
# Since we use kernels, we only need l_star to calculate b
# and to classify observations
((lowerCamelCase__) , ): List[str] =np.shape(UpperCAmelCase_)
def to_minimize(UpperCAmelCase_ : ndarray) -> float:
lowerCamelCase__: int =0
((lowerCamelCase__) , ): Optional[Any] =np.shape(UpperCAmelCase_)
for i in range(UpperCAmelCase_):
for j in range(UpperCAmelCase_):
s += (
candidate[i]
* candidate[j]
* classes[i]
* classes[j]
* self.kernel(observations[i] , observations[j])
)
return 1 / 2 * s - sum(UpperCAmelCase_)
lowerCamelCase__: List[Any] =LinearConstraint(UpperCAmelCase_ , 0 , 0)
lowerCamelCase__: str =Bounds(0 , self.regularization)
lowerCamelCase__: Union[str, Any] =minimize(
UpperCAmelCase_ , np.ones(UpperCAmelCase_) , bounds=UpperCAmelCase_ , constraints=[ly_contraint]).x
lowerCamelCase__: str =l_star
# calculating mean offset of separation plane to points
lowerCamelCase__: Tuple =0
for i in range(UpperCAmelCase_):
for j in range(UpperCAmelCase_):
s += classes[i] - classes[i] * self.optimum[i] * self.kernel(
observations[i] , observations[j])
lowerCamelCase__: int =s / n
def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : ndarray) ->int:
'''simple docstring'''
lowerCamelCase__: Optional[Any] =sum(
self.optimum[n]
* self.classes[n]
* self.kernel(self.observations[n] , UpperCAmelCase_)
for n in range(len(self.classes)))
return 1 if s + self.offset >= 0 else -1
if __name__ == "__main__":
import doctest
doctest.testmod()
| 59 | 1 |
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = ["image_processor", "tokenizer"]
lowercase_ = "ChineseCLIPImageProcessor"
lowercase_ = ("BertTokenizer", "BertTokenizerFast")
def __init__(self : Any , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Union[str, Any]=None , **UpperCAmelCase_ : str) ->Dict:
'''simple docstring'''
lowerCamelCase__: str =None
if "feature_extractor" in kwargs:
warnings.warn(
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
" instead." , UpperCAmelCase_ , )
lowerCamelCase__: Tuple =kwargs.pop("feature_extractor")
lowerCamelCase__: Optional[int] =image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError("You need to specify an `image_processor`.")
if tokenizer is None:
raise ValueError("You need to specify a `tokenizer`.")
super().__init__(UpperCAmelCase_ , UpperCAmelCase_)
lowerCamelCase__: Optional[int] =self.image_processor
def __call__(self : int , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[int]:
'''simple docstring'''
if text is None and images is None:
raise ValueError("You have to specify either text or images. Both cannot be none.")
if text is not None:
lowerCamelCase__: Dict =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if images is not None:
lowerCamelCase__: List[str] =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_)
if text is not None and images is not None:
lowerCamelCase__: Union[str, Any] =image_features.pixel_values
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int) ->str:
'''simple docstring'''
return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ (self : Any , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any]) ->Dict:
'''simple docstring'''
return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_)
@property
def SCREAMING_SNAKE_CASE_ (self : int) ->List[str]:
'''simple docstring'''
lowerCamelCase__: str =self.tokenizer.model_input_names
lowerCamelCase__: Union[str, Any] =self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
@property
def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str:
'''simple docstring'''
warnings.warn(
"`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , UpperCAmelCase_ , )
return self.image_processor_class
| 59 |
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
__A = logging.getLogger(__name__)
def lowerCAmelCase_ ( __a , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = False , ) -> str:
"""simple docstring"""
lowerCamelCase__: int =bnb_quantization_config.load_in_abit
lowerCamelCase__: Any =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." )
lowerCamelCase__: List[Any] =[]
# custom device map
if isinstance(__a , __a ) and len(device_map.keys() ) > 1:
lowerCamelCase__: Optional[int] =[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:
lowerCamelCase__: Any =get_keys_to_not_convert(__a )
# add cpu modules to skip modules only for 4-bit modules
if load_in_abit:
bnb_quantization_config.skip_modules.extend(__a )
lowerCamelCase__: List[str] =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:
lowerCamelCase__: List[Any] =[]
lowerCamelCase__: int =bnb_quantization_config.keep_in_fpaa_modules
modules_to_not_convert.extend(__a )
# compatibility with peft
lowerCamelCase__: List[str] =load_in_abit
lowerCamelCase__: int =load_in_abit
lowerCamelCase__: Tuple =get_parameter_device(__a )
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." )
lowerCamelCase__: Tuple =replace_with_bnb_layers(__a , __a , modules_to_not_convert=__a )
# convert param to the right dtype
lowerCamelCase__: Dict =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:
lowerCamelCase__: str =name.replace(".weight" , "" ).replace(".bias" , "" )
lowerCamelCase__: Optional[Any] =getattr(__a , __a , __a )
if param is not None:
param.to(torch.floataa )
elif torch.is_floating_point(__a ):
param.to(__a )
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():
lowerCamelCase__: str =replace_with_bnb_layers(
__a , __a , modules_to_not_convert=__a )
lowerCamelCase__: Optional[Any] =get_quantized_model_device_map(
__a , __a , __a , max_memory=__a , no_split_module_classes=__a , )
if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
lowerCamelCase__: Any =True
lowerCamelCase__: List[str] =any(x in list(device_map.values() ) for x in ["cpu", "disk"] )
load_checkpoint_in_model(
__a , __a , __a , dtype=bnb_quantization_config.torch_dtype , offload_folder=__a , offload_state_dict=__a , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , )
return dispatch_model(__a , device_map=__a , offload_dir=__a )
def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , __a=None ) -> str:
"""simple docstring"""
if device_map is None:
if torch.cuda.is_available():
lowerCamelCase__: str ={"": 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(__a , __a ):
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'." )
lowerCamelCase__: Optional[int] ={}
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 )
} )
lowerCamelCase__: Optional[Any] ={}
lowerCamelCase__: str =special_dtypes
lowerCamelCase__: List[str] =no_split_module_classes
lowerCamelCase__: Dict =bnb_quantization_config.target_dtype
# get max_memory for each device.
if device_map != "sequential":
lowerCamelCase__: Optional[Any] =get_balanced_memory(
__a , low_zero=(device_map == "balanced_low_0") , max_memory=__a , **__a , )
lowerCamelCase__: Union[str, Any] =max_memory
lowerCamelCase__: Dict =infer_auto_device_map(__a , **__a )
if isinstance(__a , __a ):
# check if don't have any quantized module on the cpu
lowerCamelCase__: Union[str, Any] =bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules
lowerCamelCase__: List[Any] ={
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(
"\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n " )
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 lowerCAmelCase_ ( __a , __a , __a=None , __a=None ) -> Optional[Any]:
"""simple docstring"""
if modules_to_not_convert is None:
lowerCamelCase__: List[Any] =[]
lowerCamelCase__ , lowerCamelCase__: Any =_replace_with_bnb_layers(
__a , __a , __a , __a )
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 lowerCAmelCase_ ( __a , __a , __a=None , __a=None , ) -> List[Any]:
"""simple docstring"""
lowerCamelCase__: Optional[int] =False
for name, module in model.named_children():
if current_key_name is None:
lowerCamelCase__: Optional[Any] =[]
current_key_name.append(__a )
if isinstance(__a , nn.Linear ) and name not in modules_to_not_convert:
# Check if the current key is not in the `modules_to_not_convert`
lowerCamelCase__: List[str] =".".join(__a )
lowerCamelCase__: Optional[Any] =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:
lowerCamelCase__: int =False
break
if proceed:
# Load bnb module with empty weight and replace ``nn.Linear` module
if bnb_quantization_config.load_in_abit:
lowerCamelCase__: Optional[int] =bnb.nn.LinearabitLt(
module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=__a , threshold=bnb_quantization_config.llm_inta_threshold , )
elif bnb_quantization_config.load_in_abit:
lowerCamelCase__: Dict =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" )
lowerCamelCase__: Dict =module.weight.data
if module.bias is not None:
lowerCamelCase__: List[Any] =module.bias.data
bnb_module.requires_grad_(__a )
setattr(__a , __a , __a )
lowerCamelCase__: int =True
if len(list(module.children() ) ) > 0:
lowerCamelCase__ , lowerCamelCase__: List[str] =_replace_with_bnb_layers(
__a , __a , __a , __a )
lowerCamelCase__: Union[str, Any] =has_been_replaced | _has_been_replaced
# Remove the last key for recursion
current_key_name.pop(-1 )
return model, has_been_replaced
def lowerCAmelCase_ ( __a ) -> List[Any]:
"""simple docstring"""
with init_empty_weights():
lowerCamelCase__: Any =deepcopy(__a ) # this has 0 cost since it is done inside `init_empty_weights` context manager`
lowerCamelCase__: str =find_tied_parameters(__a )
# For compatibility with Accelerate < 0.18
if isinstance(__a , __a ):
lowerCamelCase__: int =sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() )
else:
lowerCamelCase__: str =sum(__a , [] )
lowerCamelCase__: str =len(__a ) > 0
# Check if it is a base model
lowerCamelCase__: Optional[Any] =False
if hasattr(__a , "base_model_prefix" ):
lowerCamelCase__: Union[str, Any] =not hasattr(__a , 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
lowerCamelCase__: Optional[int] =list(model.named_children() )
lowerCamelCase__: Optional[int] =[list_modules[-1][0]]
# add last module together with tied weights
lowerCamelCase__: Union[str, Any] =set(__a ) - set(__a )
lowerCamelCase__: List[str] =list(set(__a ) ) + list(__a )
# remove ".weight" from the keys
lowerCamelCase__: List[Any] =[".weight", ".bias"]
lowerCamelCase__: Tuple =[]
for name in list_untouched:
for name_to_remove in names_to_remove:
if name_to_remove in name:
lowerCamelCase__: Optional[Any] =name.replace(__a , "" )
filtered_module_names.append(__a )
return filtered_module_names
def lowerCAmelCase_ ( __a ) -> Tuple:
"""simple docstring"""
for m in model.modules():
if isinstance(__a , bnb.nn.Linearabit ):
return True
return False
def lowerCAmelCase_ ( __a ) -> List[str]:
"""simple docstring"""
return next(parameter.parameters() ).device
def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a , __a ) -> Any:
"""simple docstring"""
if fpaa_statistics is None:
set_module_tensor_to_device(__a , __a , 0 , dtype=__a , value=__a )
lowerCamelCase__: Dict =param_name
lowerCamelCase__: Tuple =model
if "." in tensor_name:
lowerCamelCase__: Any =tensor_name.split("." )
for split in splits[:-1]:
lowerCamelCase__: Any =getattr(__a , __a )
if new_module is None:
raise ValueError(F"""{module} has no attribute {split}.""" )
lowerCamelCase__: str =new_module
lowerCamelCase__: int =splits[-1]
# offload weights
lowerCamelCase__: str =False
offload_weight(module._parameters[tensor_name] , __a , __a , index=__a )
if hasattr(module._parameters[tensor_name] , "SCB" ):
offload_weight(
module._parameters[tensor_name].SCB , param_name.replace("weight" , "SCB" ) , __a , index=__a , )
else:
offload_weight(__a , __a , __a , index=__a )
offload_weight(__a , param_name.replace("weight" , "SCB" ) , __a , index=__a )
set_module_tensor_to_device(__a , __a , "meta" , dtype=__a , value=torch.empty(*param.size() ) )
| 59 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.