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 |
|---|---|---|---|---|
def _lowercase( __a : str , __a : str ):
assert x is not None
assert y is not None
a__ =len(__a )
a__ =len(__a )
# declaring the array for storing the dp values
a__ =[[0] * (n + 1) for _ in range(m + 1 )] # noqa: E741
for i in range(1 , m + 1 ):
for j in range(1 , n + 1 ):
a__ =1 if x[i - 1] == y[j - 1] else 0
a__ =max(l[i - 1][j] , l[i][j - 1] , l[i - 1][j - 1] + match )
a__ =''
a__ , a__ =m, n
while i > 0 and j > 0:
a__ =1 if x[i - 1] == y[j - 1] else 0
if l[i][j] == l[i - 1][j - 1] + match:
if match == 1:
a__ =x[i - 1] + seq
i -= 1
j -= 1
elif l[i][j] == l[i - 1][j]:
i -= 1
else:
j -= 1
return l[m][n], seq
if __name__ == "__main__":
_lowerCAmelCase: List[Any] = 'AGGTAB'
_lowerCAmelCase: Optional[int] = 'GXTXAYB'
_lowerCAmelCase: Optional[int] = 4
_lowerCAmelCase: List[Any] = 'GTAB'
_lowerCAmelCase , _lowerCAmelCase: Tuple = longest_common_subsequence(a, b)
print('len =', ln, ', sub-sequence =', subseq)
import doctest
doctest.testmod()
| 20 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_lowerCamelCase = logging.get_logger(__name__)
_lowerCamelCase = {
'''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''',
}
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = '''roc_bert'''
def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ):
__SCREAMING_SNAKE_CASE : List[str] = vocab_size
__SCREAMING_SNAKE_CASE : int = max_position_embeddings
__SCREAMING_SNAKE_CASE : List[str] = hidden_size
__SCREAMING_SNAKE_CASE : str = num_hidden_layers
__SCREAMING_SNAKE_CASE : int = num_attention_heads
__SCREAMING_SNAKE_CASE : Any = intermediate_size
__SCREAMING_SNAKE_CASE : Optional[int] = hidden_act
__SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob
__SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob
__SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range
__SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size
__SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps
__SCREAMING_SNAKE_CASE : Optional[int] = use_cache
__SCREAMING_SNAKE_CASE : str = enable_pronunciation
__SCREAMING_SNAKE_CASE : List[str] = enable_shape
__SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim
__SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size
__SCREAMING_SNAKE_CASE : str = shape_embed_dim
__SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size
__SCREAMING_SNAKE_CASE : Tuple = concat_input
__SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type
__SCREAMING_SNAKE_CASE : str = classifier_dropout
super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
| 674 | 0 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_torch_available,
is_vision_available,
)
UpperCAmelCase_ : List[str] = {
"configuration_mobilevit": ["MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileViTConfig", "MobileViTOnnxConfig"],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ : Union[str, Any] = ["MobileViTFeatureExtractor"]
UpperCAmelCase_ : int = ["MobileViTImageProcessor"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ : Dict = [
"MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST",
"MobileViTForImageClassification",
"MobileViTForSemanticSegmentation",
"MobileViTModel",
"MobileViTPreTrainedModel",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ : Tuple = [
"TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFMobileViTForImageClassification",
"TFMobileViTForSemanticSegmentation",
"TFMobileViTModel",
"TFMobileViTPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_mobilevit import MobileViTFeatureExtractor
from .image_processing_mobilevit import MobileViTImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mobilevit import (
MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
MobileViTForImageClassification,
MobileViTForSemanticSegmentation,
MobileViTModel,
MobileViTPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_mobilevit import (
TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFMobileViTForImageClassification,
TFMobileViTForSemanticSegmentation,
TFMobileViTModel,
TFMobileViTPreTrainedModel,
)
else:
import sys
UpperCAmelCase_ : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 21 |
"""simple docstring"""
import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List
import git
import torch
from torch.utils.data import Dataset
from transformers import BartTokenizer, RagTokenizer, TaTokenizer
def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {}
__SCREAMING_SNAKE_CASE : Optional[int] = padding_side
return tokenizer(
[line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , )
def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 )
if attention_mask is None:
return input_ids[:, keep_column_mask]
else:
return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])
class snake_case ( __UpperCAmelCase ):
def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ):
super().__init__()
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' )
__SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' )
__SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file )
__SCREAMING_SNAKE_CASE : List[str] = max_source_length
__SCREAMING_SNAKE_CASE : Dict = max_target_length
assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}'''
__SCREAMING_SNAKE_CASE : Dict = tokenizer
__SCREAMING_SNAKE_CASE : Union[str, Any] = prefix
if n_obs is not None:
__SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs]
__SCREAMING_SNAKE_CASE : List[str] = src_lang
__SCREAMING_SNAKE_CASE : str = tgt_lang
def __len__( self :int ):
return len(self.src_lens )
def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ):
__SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1
__SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' )
__SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' )
assert source_line, f'''empty source line for index {index}'''
assert tgt_line, f'''empty tgt line for index {index}'''
# Need to add eos token manually for T5
if isinstance(self.tokenizer , _lowerCamelCase ):
source_line += self.tokenizer.eos_token
tgt_line += self.tokenizer.eos_token
# Pad source and target to the right
__SCREAMING_SNAKE_CASE : Dict = (
self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer
)
__SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer
__SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' )
__SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' )
__SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze()
__SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze()
__SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze()
return {
"input_ids": source_ids,
"attention_mask": src_mask,
"decoder_input_ids": target_ids,
}
@staticmethod
def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ):
return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()]
def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ):
__SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] )
__SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] )
__SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] )
__SCREAMING_SNAKE_CASE : str = (
self.tokenizer.generator.pad_token_id
if isinstance(self.tokenizer , _lowerCamelCase )
else self.tokenizer.pad_token_id
)
__SCREAMING_SNAKE_CASE : Union[str, Any] = (
self.tokenizer.question_encoder.pad_token_id
if isinstance(self.tokenizer , _lowerCamelCase )
else self.tokenizer.pad_token_id
)
__SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Dict = {
'''input_ids''': source_ids,
'''attention_mask''': source_mask,
'''decoder_input_ids''': y,
}
return batch
_lowerCamelCase = getLogger(__name__)
def lowerCAmelCase_ ( lowercase_ : List[List] ):
'''simple docstring'''
return list(itertools.chain.from_iterable(lowercase_ ) )
def lowerCAmelCase_ ( lowercase_ : str ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = get_git_info()
save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) )
def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ):
'''simple docstring'''
with open(lowercase_ , '''w''' ) as f:
json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ )
def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ):
'''simple docstring'''
with open(lowercase_ ) as f:
return json.load(lowercase_ )
def lowerCAmelCase_ ( ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ )
__SCREAMING_SNAKE_CASE : List[str] = {
'''repo_id''': str(lowercase_ ),
'''repo_sha''': str(repo.head.object.hexsha ),
'''repo_branch''': str(repo.active_branch ),
'''hostname''': str(socket.gethostname() ),
}
return repo_infos
def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ):
'''simple docstring'''
return list(map(lowercase_ , lowercase_ ) )
def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ):
'''simple docstring'''
with open(lowercase_ , '''wb''' ) as f:
return pickle.dump(lowercase_ , lowercase_ )
def lowerCAmelCase_ ( lowercase_ : Any ):
'''simple docstring'''
def remove_articles(lowercase_ : Dict ):
return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ )
def white_space_fix(lowercase_ : Optional[int] ):
return " ".join(text.split() )
def remove_punc(lowercase_ : Any ):
__SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation )
return "".join(ch for ch in text if ch not in exclude )
def lower(lowercase_ : int ):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) )
def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split()
__SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split()
__SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ )
__SCREAMING_SNAKE_CASE : Tuple = sum(common.values() )
if num_same == 0:
return 0
__SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ )
__SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ )
__SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall)
return fa
def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ):
'''simple docstring'''
return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ )
def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ):
'''simple docstring'''
assert len(lowercase_ ) == len(lowercase_ )
__SCREAMING_SNAKE_CASE : Union[str, Any] = 0
for hypo, pred in zip(lowercase_ , lowercase_ ):
em += exact_match_score(lowercase_ , lowercase_ )
if len(lowercase_ ) > 0:
em /= len(lowercase_ )
return {"em": em}
def lowerCAmelCase_ ( lowercase_ : str ):
'''simple docstring'''
return model_prefix.startswith('''rag''' )
def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params}
# T5 models don't have `dropout` param, they have `dropout_rate` instead
__SCREAMING_SNAKE_CASE : Any = '''dropout_rate'''
for p in extra_params:
if getattr(lowercase_ , lowercase_ , lowercase_ ):
if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ):
logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) )
delattr(lowercase_ , lowercase_ )
continue
__SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p]
setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) )
delattr(lowercase_ , lowercase_ )
return hparams, config
| 674 | 0 |
'''simple docstring'''
import argparse
import json
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
from accelerate.utils.deepspeed import DummyOptim, DummyScheduler
_snake_case : List[Any] = 16
_snake_case : Tuple = 32
def snake_case_ (UpperCamelCase : Accelerator , UpperCamelCase : int = 16 , UpperCamelCase : str = "bert-base-cased" ):
'''simple docstring'''
_a = AutoTokenizer.from_pretrained(UpperCamelCase )
_a = load_dataset('''glue''' , '''mrpc''' )
def tokenize_function(UpperCamelCase : Optional[Any] ):
# max_length=None => use the model max length (it's actually the default)
_a = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=UpperCamelCase , max_length=UpperCamelCase )
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
_a = datasets.map(
UpperCamelCase , batched=UpperCamelCase , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , load_from_cache_file=UpperCamelCase )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
_a = tokenized_datasets.rename_column('''label''' , '''labels''' )
def collate_fn(UpperCamelCase : Union[str, Any] ):
# On TPU it's best to pad everything to the same length or training will be very slow.
if accelerator.distributed_type == DistributedType.TPU:
return tokenizer.pad(UpperCamelCase , padding='''max_length''' , max_length=128 , return_tensors='''pt''' )
return tokenizer.pad(UpperCamelCase , padding='''longest''' , return_tensors='''pt''' )
# Instantiate dataloaders.
_a = DataLoader(
tokenized_datasets['''train'''] , shuffle=UpperCamelCase , collate_fn=UpperCamelCase , batch_size=UpperCamelCase )
_a = DataLoader(
tokenized_datasets['''validation'''] , shuffle=UpperCamelCase , collate_fn=UpperCamelCase , batch_size=UpperCamelCase )
return train_dataloader, eval_dataloader
def snake_case_ (UpperCamelCase : Optional[int] , UpperCamelCase : Optional[int] ):
'''simple docstring'''
_a = Accelerator()
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
_a = config['''lr''']
_a = int(config['''num_epochs'''] )
_a = int(config['''seed'''] )
_a = int(config['''batch_size'''] )
_a = args.model_name_or_path
set_seed(UpperCamelCase )
_a , _a = get_dataloaders(UpperCamelCase , UpperCamelCase , UpperCamelCase )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
_a = AutoModelForSequenceClassification.from_pretrained(UpperCamelCase , return_dict=UpperCamelCase )
# Instantiate optimizer
_a = (
AdamW
if accelerator.state.deepspeed_plugin is None
or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config
else DummyOptim
)
_a = optimizer_cls(params=model.parameters() , lr=UpperCamelCase )
if accelerator.state.deepspeed_plugin is not None:
_a = accelerator.state.deepspeed_plugin.deepspeed_config[
'''gradient_accumulation_steps'''
]
else:
_a = 1
_a = (len(UpperCamelCase ) * num_epochs) // gradient_accumulation_steps
# Instantiate scheduler
if (
accelerator.state.deepspeed_plugin is None
or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
):
_a = get_linear_schedule_with_warmup(
optimizer=UpperCamelCase , num_warmup_steps=0 , num_training_steps=UpperCamelCase , )
else:
_a = DummyScheduler(UpperCamelCase , total_num_steps=UpperCamelCase , warmup_num_steps=0 )
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
_a , _a , _a , _a , _a = accelerator.prepare(
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase )
# We need to keep track of how many total steps we have iterated over
_a = 0
# We also need to keep track of the stating epoch so files are named properly
_a = 0
# Now we train the model
_a = evaluate.load('''glue''' , '''mrpc''' )
_a = 0
_a = {}
for epoch in range(UpperCamelCase , UpperCamelCase ):
model.train()
for step, batch in enumerate(UpperCamelCase ):
_a = model(**UpperCamelCase )
_a = outputs.loss
_a = loss / gradient_accumulation_steps
accelerator.backward(UpperCamelCase )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
overall_step += 1
model.eval()
_a = 0
for step, batch in enumerate(UpperCamelCase ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
_a = model(**UpperCamelCase )
_a = outputs.logits.argmax(dim=-1 )
# It is slightly faster to call this once, than multiple times
_a , _a = accelerator.gather(
(predictions, batch['''labels''']) ) # If we are in a multiprocess environment, the last batch has duplicates
if accelerator.use_distributed:
if step == len(UpperCamelCase ) - 1:
_a = predictions[: len(eval_dataloader.dataset ) - samples_seen]
_a = references[: len(eval_dataloader.dataset ) - samples_seen]
else:
samples_seen += references.shape[0]
metric.add_batch(
predictions=UpperCamelCase , references=UpperCamelCase , )
_a = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f'epoch {epoch}:' , UpperCamelCase )
_a = eval_metric['''accuracy''']
if best_performance < eval_metric["accuracy"]:
_a = eval_metric['''accuracy''']
if args.performance_lower_bound is not None:
assert (
args.performance_lower_bound <= best_performance
), f'Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}'
accelerator.wait_for_everyone()
if accelerator.is_main_process:
with open(os.path.join(args.output_dir , '''all_results.json''' ) , '''w''' ) as f:
json.dump(UpperCamelCase , UpperCamelCase )
def snake_case_ ():
'''simple docstring'''
_a = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' )
parser.add_argument(
'''--model_name_or_path''' , type=UpperCamelCase , default='''bert-base-cased''' , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , required=UpperCamelCase , )
parser.add_argument(
'''--output_dir''' , type=UpperCamelCase , default='''.''' , help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''' , )
parser.add_argument(
'''--performance_lower_bound''' , type=UpperCamelCase , default=UpperCamelCase , help='''Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.''' , )
parser.add_argument(
'''--num_epochs''' , type=UpperCamelCase , default=3 , help='''Number of train epochs.''' , )
_a = parser.parse_args()
_a = {'''lr''': 2e-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16}
training_function(UpperCamelCase , UpperCamelCase )
if __name__ == "__main__":
main()
| 22 |
"""simple docstring"""
from collections.abc import Callable
import numpy as np
def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) )
__SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) )
__SCREAMING_SNAKE_CASE : List[Any] = ya
__SCREAMING_SNAKE_CASE : Dict = xa
for k in range(lowercase_ ):
__SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] )
__SCREAMING_SNAKE_CASE : int = y[k] + (
(step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ ))
)
x += step_size
return y
if __name__ == "__main__":
import doctest
doctest.testmod()
| 674 | 0 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_torch_available,
is_vision_available,
)
snake_case__ : Dict = {
"""configuration_efficientformer""": [
"""EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""",
"""EfficientFormerConfig""",
]
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case__ : List[Any] = ["""EfficientFormerImageProcessor"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case__ : Optional[int] = [
"""EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""EfficientFormerForImageClassification""",
"""EfficientFormerForImageClassificationWithTeacher""",
"""EfficientFormerModel""",
"""EfficientFormerPreTrainedModel""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case__ : Dict = [
"""TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""TFEfficientFormerForImageClassification""",
"""TFEfficientFormerForImageClassificationWithTeacher""",
"""TFEfficientFormerModel""",
"""TFEfficientFormerPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_efficientformer import EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientFormerConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .image_processing_efficientformer import EfficientFormerImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_efficientformer import (
EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
EfficientFormerForImageClassification,
EfficientFormerForImageClassificationWithTeacher,
EfficientFormerModel,
EfficientFormerPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_efficientformer import (
TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TFEfficientFormerForImageClassification,
TFEfficientFormerForImageClassificationWithTeacher,
TFEfficientFormerModel,
TFEfficientFormerPreTrainedModel,
)
else:
import sys
snake_case__ : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 23 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...file_utils import _LazyModule, is_torch_available
from ...utils import OptionalDependencyNotAvailable
_lowerCamelCase = {
'''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''],
'''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase = [
'''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''GPTNeoXJapaneseForCausalLM''',
'''GPTNeoXJapaneseLayer''',
'''GPTNeoXJapaneseModel''',
'''GPTNeoXJapanesePreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig
from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_gpt_neox_japanese import (
GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST,
GPTNeoXJapaneseForCausalLM,
GPTNeoXJapaneseLayer,
GPTNeoXJapaneseModel,
GPTNeoXJapanesePreTrainedModel,
)
else:
import sys
_lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 674 | 0 |
'''simple docstring'''
import logging
import math
import os
from dataclasses import dataclass, field
from glob import glob
from typing import Optional
from torch.utils.data import ConcatDataset
import transformers
from transformers import (
CONFIG_MAPPING,
MODEL_WITH_LM_HEAD_MAPPING,
AutoConfig,
AutoModelWithLMHead,
AutoTokenizer,
DataCollatorForLanguageModeling,
DataCollatorForPermutationLanguageModeling,
DataCollatorForWholeWordMask,
HfArgumentParser,
LineByLineTextDataset,
LineByLineWithRefDataset,
PreTrainedTokenizer,
TextDataset,
Trainer,
TrainingArguments,
set_seed,
)
from transformers.trainer_utils import is_main_process
UpperCAmelCase_ : Union[str, Any] = logging.getLogger(__name__)
UpperCAmelCase_ : List[str] = list(MODEL_WITH_LM_HEAD_MAPPING.keys())
UpperCAmelCase_ : Union[str, Any] = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
@dataclass
class lowerCAmelCase :
__lowercase : Optional[str] = field(
default=__lowerCAmelCase , metadata={
'''help''': (
'''The model checkpoint for weights initialization. Leave None if you want to train a model from'''
''' scratch.'''
)
} , )
__lowercase : Optional[str] = field(
default=__lowerCAmelCase , metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(__lowerCAmelCase)} , )
__lowercase : Optional[str] = field(
default=__lowerCAmelCase , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''})
__lowercase : Optional[str] = field(
default=__lowerCAmelCase , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''})
__lowercase : Optional[str] = field(
default=__lowerCAmelCase , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , )
@dataclass
class lowerCAmelCase :
__lowercase : Optional[str] = field(
default=__lowerCAmelCase , metadata={'''help''': '''The input training data file (a text file).'''})
__lowercase : Optional[str] = field(
default=__lowerCAmelCase , metadata={
'''help''': (
'''The input training data files (multiple files in glob format). '''
'''Very often splitting large files to smaller files can prevent tokenizer going out of memory'''
)
} , )
__lowercase : Optional[str] = field(
default=__lowerCAmelCase , metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''} , )
__lowercase : Optional[str] = field(
default=__lowerCAmelCase , metadata={'''help''': '''An optional input train ref data file for whole word mask in Chinese.'''} , )
__lowercase : Optional[str] = field(
default=__lowerCAmelCase , metadata={'''help''': '''An optional input eval ref data file for whole word mask in Chinese.'''} , )
__lowercase : bool = field(
default=__lowerCAmelCase , metadata={'''help''': '''Whether distinct lines of text in the dataset are to be handled as distinct sequences.'''} , )
__lowercase : bool = field(
default=__lowerCAmelCase , metadata={'''help''': '''Train with masked-language modeling loss instead of language modeling.'''})
__lowercase : bool = field(default=__lowerCAmelCase , metadata={'''help''': '''Whether ot not to use whole word mask.'''})
__lowercase : float = field(
default=0.15 , metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''})
__lowercase : float = field(
default=1 / 6 , metadata={
'''help''': (
'''Ratio of length of a span of masked tokens to surrounding context length for permutation language'''
''' modeling.'''
)
} , )
__lowercase : int = field(
default=5 , metadata={'''help''': '''Maximum length of a span of masked tokens for permutation language modeling.'''})
__lowercase : int = field(
default=-1 , metadata={
'''help''': (
'''Optional input sequence length after tokenization.'''
'''The training dataset will be truncated in block of this size for training.'''
'''Default to the model max input length for single sentence inputs (take into account special tokens).'''
)
} , )
__lowercase : bool = field(
default=__lowerCAmelCase , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''})
def _UpperCamelCase (_lowerCamelCase : DataTrainingArguments , _lowerCamelCase : PreTrainedTokenizer , _lowerCamelCase : bool = False , _lowerCamelCase : Optional[str] = None , )-> int:
'''simple docstring'''
def _dataset(_lowerCamelCase : Any , _lowerCamelCase : List[Any]=None ):
if args.line_by_line:
if ref_path is not None:
if not args.whole_word_mask or not args.mlm:
raise ValueError('''You need to set world whole masking and mlm to True for Chinese Whole Word Mask''' )
return LineByLineWithRefDataset(
tokenizer=_lowerCamelCase , file_path=_lowerCamelCase , block_size=args.block_size , ref_path=_lowerCamelCase , )
return LineByLineTextDataset(tokenizer=_lowerCamelCase , file_path=_lowerCamelCase , block_size=args.block_size )
else:
return TextDataset(
tokenizer=_lowerCamelCase , file_path=_lowerCamelCase , block_size=args.block_size , overwrite_cache=args.overwrite_cache , cache_dir=_lowerCamelCase , )
if evaluate:
return _dataset(args.eval_data_file , args.eval_ref_file )
elif args.train_data_files:
return ConcatDataset([_dataset(_lowerCamelCase ) for f in glob(args.train_data_files )] )
else:
return _dataset(args.train_data_file , args.train_ref_file )
def _UpperCamelCase ()-> Any:
'''simple docstring'''
__snake_case = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
__snake_case , __snake_case , __snake_case = parser.parse_args_into_dataclasses()
if data_args.eval_data_file is None and training_args.do_eval:
raise ValueError(
'''Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file '''
'''or remove the --do_eval argument.''' )
if (
os.path.exists(training_args.output_dir )
and os.listdir(training_args.output_dir )
and training_args.do_train
and not training_args.overwrite_output_dir
):
raise ValueError(
f'''Output directory ({training_args.output_dir}) already exists and is not empty. Use'''
''' --overwrite_output_dir to overcome.''' )
# Setup logging
logging.basicConfig(
format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , )
logger.warning(
'''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , )
# Set the verbosity to info of the Transformers logger (on main process only):
if is_main_process(training_args.local_rank ):
transformers.utils.logging.set_verbosity_info()
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
logger.info('''Training/evaluation parameters %s''' , _lowerCamelCase )
# Set seed
set_seed(training_args.seed )
# Load pretrained model and tokenizer
#
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
if model_args.config_name:
__snake_case = AutoConfig.from_pretrained(model_args.config_name , cache_dir=model_args.cache_dir )
elif model_args.model_name_or_path:
__snake_case = AutoConfig.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir )
else:
__snake_case = CONFIG_MAPPING[model_args.model_type]()
logger.warning('''You are instantiating a new config instance from scratch.''' )
if model_args.tokenizer_name:
__snake_case = AutoTokenizer.from_pretrained(model_args.tokenizer_name , cache_dir=model_args.cache_dir )
elif model_args.model_name_or_path:
__snake_case = AutoTokenizer.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir )
else:
raise ValueError(
'''You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another'''
''' script, save it,and load it from here, using --tokenizer_name''' )
if model_args.model_name_or_path:
__snake_case = AutoModelWithLMHead.from_pretrained(
model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=_lowerCamelCase , cache_dir=model_args.cache_dir , )
else:
logger.info('''Training new model from scratch''' )
__snake_case = AutoModelWithLMHead.from_config(_lowerCamelCase )
model.resize_token_embeddings(len(_lowerCamelCase ) )
if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm:
raise ValueError(
'''BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the'''
'''--mlm flag (masked language modeling).''' )
if data_args.block_size <= 0:
__snake_case = tokenizer.max_len
# Our input block size will be the max possible for the model
else:
__snake_case = min(data_args.block_size , tokenizer.max_len )
# Get datasets
__snake_case = (
get_dataset(_lowerCamelCase , tokenizer=_lowerCamelCase , cache_dir=model_args.cache_dir ) if training_args.do_train else None
)
__snake_case = (
get_dataset(_lowerCamelCase , tokenizer=_lowerCamelCase , evaluate=_lowerCamelCase , cache_dir=model_args.cache_dir )
if training_args.do_eval
else None
)
if config.model_type == "xlnet":
__snake_case = DataCollatorForPermutationLanguageModeling(
tokenizer=_lowerCamelCase , plm_probability=data_args.plm_probability , max_span_length=data_args.max_span_length , )
else:
if data_args.mlm and data_args.whole_word_mask:
__snake_case = DataCollatorForWholeWordMask(
tokenizer=_lowerCamelCase , mlm_probability=data_args.mlm_probability )
else:
__snake_case = DataCollatorForLanguageModeling(
tokenizer=_lowerCamelCase , mlm=data_args.mlm , mlm_probability=data_args.mlm_probability )
# Initialize our Trainer
__snake_case = Trainer(
model=_lowerCamelCase , args=_lowerCamelCase , data_collator=_lowerCamelCase , train_dataset=_lowerCamelCase , eval_dataset=_lowerCamelCase , prediction_loss_only=_lowerCamelCase , )
# Training
if training_args.do_train:
__snake_case = (
model_args.model_name_or_path
if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path )
else None
)
trainer.train(model_path=_lowerCamelCase )
trainer.save_model()
# For convenience, we also re-save the tokenizer to the same directory,
# so that you can share your model easily on huggingface.co/models =)
if trainer.is_world_master():
tokenizer.save_pretrained(training_args.output_dir )
# Evaluation
__snake_case = {}
if training_args.do_eval:
logger.info('''*** Evaluate ***''' )
__snake_case = trainer.evaluate()
__snake_case = math.exp(eval_output['''eval_loss'''] )
__snake_case = {'''perplexity''': perplexity}
__snake_case = os.path.join(training_args.output_dir , '''eval_results_lm.txt''' )
if trainer.is_world_master():
with open(_lowerCamelCase , '''w''' ) as writer:
logger.info('''***** Eval results *****''' )
for key in sorted(result.keys() ):
logger.info(''' %s = %s''' , _lowerCamelCase , str(result[key] ) )
writer.write('''%s = %s\n''' % (key, str(result[key] )) )
results.update(_lowerCamelCase )
return results
def _UpperCamelCase (_lowerCamelCase : List[Any] )-> Optional[Any]:
'''simple docstring'''
main()
if __name__ == "__main__":
main()
| 24 |
"""simple docstring"""
from __future__ import annotations
from typing import Any
class snake_case :
def __init__( self :Optional[Any] , _lowerCamelCase :int ):
__SCREAMING_SNAKE_CASE : int = num_of_nodes
__SCREAMING_SNAKE_CASE : list[list[int]] = []
__SCREAMING_SNAKE_CASE : dict[int, int] = {}
def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ):
self.m_edges.append([u_node, v_node, weight] )
def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ):
if self.m_component[u_node] == u_node:
return u_node
return self.find_component(self.m_component[u_node] )
def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ):
if self.m_component[u_node] != u_node:
for k in self.m_component:
__SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ):
if component_size[u_node] <= component_size[v_node]:
__SCREAMING_SNAKE_CASE : List[Any] = v_node
component_size[v_node] += component_size[u_node]
self.set_component(_lowerCamelCase )
elif component_size[u_node] >= component_size[v_node]:
__SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase )
component_size[u_node] += component_size[v_node]
self.set_component(_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
__SCREAMING_SNAKE_CASE : Optional[int] = []
__SCREAMING_SNAKE_CASE : str = 0
__SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes
# A list of components (initialized to all of the nodes)
for node in range(self.m_num_of_nodes ):
self.m_component.update({node: node} )
component_size.append(1 )
__SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes
while num_of_components > 1:
for edge in self.m_edges:
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge
__SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u]
__SCREAMING_SNAKE_CASE : int = self.m_component[v]
if u_component != v_component:
for component in (u_component, v_component):
if (
minimum_weight_edge[component] == -1
or minimum_weight_edge[component][2] > w
):
__SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w]
for edge in minimum_weight_edge:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge
__SCREAMING_SNAKE_CASE : Tuple = self.m_component[u]
__SCREAMING_SNAKE_CASE : int = self.m_component[v]
if u_component != v_component:
mst_weight += w
self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' )
num_of_components -= 1
__SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes
print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' )
def lowerCAmelCase_ ( ):
'''simple docstring'''
if __name__ == "__main__":
import doctest
doctest.testmod()
| 674 | 0 |
import warnings
from pathlib import Path
from typing import List, Tuple, Union
import fire
from torch import nn
from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel
from transformers.utils import logging
a_ = logging.get_logger(__name__)
def lowerCamelCase__ ( _a , _a , _a):
SCREAMING_SNAKE_CASE : Dict = nn.ModuleList([src_layers[i] for i in layers_to_copy])
assert len(_a) == len(_a), f"{len(_a)} != {len(_a)}"
dest_layers.load_state_dict(layers_to_copy.state_dict())
a_ = {
# maps num layers in teacher -> num_layers in student -> which teacher layers to copy.
# 12: bart, 16: pegasus, 6: marian/Helsinki-NLP
12: {
1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher
2: [0, 6],
3: [0, 6, 11],
4: [0, 4, 8, 11],
6: [0, 2, 4, 7, 9, 11],
9: [0, 1, 2, 4, 5, 7, 9, 10, 11],
12: list(range(12)),
},
16: { # maps num layers in student -> which teacher layers to copy
1: [0],
2: [0, 15],
3: [0, 8, 15],
4: [0, 5, 10, 15],
6: [0, 3, 6, 9, 12, 15],
8: [0, 2, 4, 6, 8, 10, 12, 15],
9: [0, 1, 3, 5, 7, 9, 11, 13, 15],
12: [0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15],
16: list(range(16)),
},
6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))},
}
a_ = {
# maps num layers in student -> which teacher layers to copy.
6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]},
12: {1: [11], 2: [5, 11], 3: [3, 7, 11], 6: [1, 3, 5, 8, 10, 11]},
16: {1: [15], 4: [4, 9, 12, 15], 8: [1, 3, 5, 7, 9, 11, 13, 15]},
}
def lowerCamelCase__ ( _a , _a):
try:
SCREAMING_SNAKE_CASE : Any = LAYERS_TO_COPY[n_teacher][n_student]
return val
except KeyError:
if n_student != n_teacher:
warnings.warn(
f"no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first"
f" {n_student}")
return list(range(_a))
def lowerCamelCase__ ( _a , _a):
if n_student > n_teacher:
raise ValueError(f"Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}")
elif n_teacher == n_student:
return list(range(_a))
elif n_student == 1:
return [n_teacher - 1]
else:
return LAYERS_TO_SUPERVISE[n_teacher][n_student]
def lowerCamelCase__ ( _a , _a = "student" , _a = None , _a = None , _a=False , _a=None , _a=None , **_a , ):
SCREAMING_SNAKE_CASE : Dict = "encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher."
assert (e is not None) or (d is not None), _msg
if isinstance(_a , _a):
AutoTokenizer.from_pretrained(_a).save_pretrained(_a) # purely for convenience
SCREAMING_SNAKE_CASE : str = AutoModelForSeqaSeqLM.from_pretrained(_a).eval()
else:
assert isinstance(_a , _a), f"teacher must be a model or string got type {type(_a)}"
SCREAMING_SNAKE_CASE : Optional[int] = teacher.config.to_diff_dict()
try:
SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : str = teacher.config.encoder_layers, teacher.config.decoder_layers
if e is None:
SCREAMING_SNAKE_CASE : List[str] = teacher_e
if d is None:
SCREAMING_SNAKE_CASE : Optional[Any] = teacher_d
init_kwargs.update({"encoder_layers": e, "decoder_layers": d})
except AttributeError: # T5
if hasattr(teacher.config , "num_encoder_layers"):
SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : str = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers
else:
SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Tuple = teacher.config.num_layers, teacher.config.num_decoder_layers
if e is None:
SCREAMING_SNAKE_CASE : Optional[Any] = teacher_e
if d is None:
SCREAMING_SNAKE_CASE : List[Any] = teacher_d
if hasattr(teacher.config , "num_encoder_layers"):
init_kwargs.update({"num_encoder_layers": e, "num_decoder_layers": d})
else:
init_kwargs.update({"num_layers": e, "num_decoder_layers": d})
# Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs
init_kwargs.update(_a)
# Copy weights
SCREAMING_SNAKE_CASE : Tuple = teacher.config_class(**_a)
SCREAMING_SNAKE_CASE : Any = AutoModelForSeqaSeqLM.from_config(_a)
# Start by copying the full teacher state dict this will copy the first N teacher layers to the student.
SCREAMING_SNAKE_CASE : List[str] = student.load_state_dict(teacher.state_dict() , strict=_a)
assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys.
if copy_first_teacher_layers: # Our copying is done. We just log and save
SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[int] = list(range(_a)), list(range(_a))
logger.info(
f"Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to"
f" {save_path}")
student.save_pretrained(_a)
return student, e_layers_to_copy, d_layers_to_copy
# Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer.
if e_layers_to_copy is None:
SCREAMING_SNAKE_CASE : List[int] = pick_layers_to_copy(_a , _a)
if d_layers_to_copy is None:
SCREAMING_SNAKE_CASE : List[int] = pick_layers_to_copy(_a , _a)
try:
if hasattr(
_a , "prophetnet"): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers
copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , _a)
copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , _a)
else:
copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , _a)
copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , _a)
except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block
copy_layers(teacher.encoder.block , student.encoder.block , _a)
copy_layers(teacher.decoder.block , student.decoder.block , _a)
logger.info(
f"Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}")
SCREAMING_SNAKE_CASE : Optional[int] = {
"teacher_type": teacher.config.model_type,
"copied_encoder_layers": e_layers_to_copy,
"copied_decoder_layers": d_layers_to_copy,
}
student.save_pretrained(_a)
# Save information about copying for easier reproducibility
return student, e_layers_to_copy, d_layers_to_copy
if __name__ == "__main__":
fire.Fire(create_student_by_copying_alternating_layers) | 25 |
"""simple docstring"""
import argparse
import pickle
import numpy as np
import torch
from torch import nn
from transformers import ReformerConfig, ReformerModelWithLMHead
from transformers.utils import logging
logging.set_verbosity_info()
def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ):
'''simple docstring'''
assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match'''
__SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ )
if bias is not None:
assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match'''
__SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ )
def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] )
__SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] )
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] )
set_param(
torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , )
def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] )
__SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] )
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] )
__SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] )
set_param(
torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , )
def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = weights[0][0][0]
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] )
__SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] )
set_param(
torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , )
# lsh weights + output
__SCREAMING_SNAKE_CASE : Tuple = weights[0][1]
if len(lowercase_ ) < 4:
set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ )
else:
set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ )
# intermediate weighs
__SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2]
# Chunked Feed Forward
if len(lowercase_ ) == 4:
__SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2]
# layernorm 2
__SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] )
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] )
set_param(
torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , )
# intermediate dense
__SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] )
set_param(
torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , )
# intermediate out
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] )
__SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] )
set_param(
torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , )
def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Dict = torch_model.reformer
# word embeds
__SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] )
set_param(
torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , )
if isinstance(weights[3] , lowercase_ ):
__SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings
for emb_idx in range(len(position_embeddings.weights ) ):
__SCREAMING_SNAKE_CASE : Dict = np.asarray(weights[3][emb_idx][0] )
assert (
position_embeddings.weights[emb_idx].shape == emb_weights.shape
), F'''{position_embeddings[emb_idx]} emb does not match'''
__SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) )
__SCREAMING_SNAKE_CASE : List[Any] = weights[5]
assert len(torch_model_reformer.encoder.layers ) * 4 == len(
lowercase_ ), "HF and trax model do not have the same number of layers"
for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)]
set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ )
# output layer norm
__SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] )
set_param(
torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , )
# output embeddings
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] )
__SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] )
set_param(
torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , )
def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ )
print(F'''Building PyTorch model from configuration: {config}''' )
__SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ )
with open(lowercase_ , '''rb''' ) as f:
__SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights''']
set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size )
# Save pytorch-model
print(F'''Save PyTorch model to {pytorch_dump_path}''' )
torch.save(model.state_dict() , lowercase_ )
if __name__ == "__main__":
_lowerCamelCase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--trax_model_pkl_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.'''
)
parser.add_argument(
'''--config_file''',
default=None,
type=str,
required=True,
help=(
'''The config json file corresponding to the pre-trained Reformer model. \n'''
'''This specifies the model architecture.'''
),
)
parser.add_argument(
'''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
)
_lowerCamelCase = parser.parse_args()
convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
| 674 | 0 |
'''simple docstring'''
import json
import os
import unittest
from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer
from ...test_tokenization_common import TokenizerTesterMixin
class _A ( __lowercase , unittest.TestCase ):
lowercase__: Optional[Any] = CTRLTokenizer
lowercase__: Dict = False
lowercase__: List[Any] = False
def lowercase__ ( self : List[str] ) -> str:
"""simple docstring"""
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
__snake_case : Any = ["""adapt""", """re@@""", """a@@""", """apt""", """c@@""", """t""", """<unk>"""]
__snake_case : Optional[Any] = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) )
__snake_case : Optional[Any] = ["""#version: 0.2""", """a p""", """ap t</w>""", """r e""", """a d""", """ad apt</w>""", """"""]
__snake_case : int = {"""unk_token""": """<unk>"""}
__snake_case : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] )
__snake_case : Tuple = 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(__magic_name__ ) + """\n""" )
with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp:
fp.write("""\n""".join(__magic_name__ ) )
def lowercase__ ( self : Union[str, Any] , **__magic_name__ : List[Any] ) -> Optional[Any]:
"""simple docstring"""
kwargs.update(self.special_tokens_map )
return CTRLTokenizer.from_pretrained(self.tmpdirname , **__magic_name__ )
def lowercase__ ( self : Tuple , __magic_name__ : Tuple ) -> List[Any]:
"""simple docstring"""
__snake_case : Tuple = """adapt react readapt apt"""
__snake_case : Tuple = """adapt react readapt apt"""
return input_text, output_text
def lowercase__ ( self : Union[str, Any] ) -> str:
"""simple docstring"""
__snake_case : int = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map )
__snake_case : str = """adapt react readapt apt"""
__snake_case : List[str] = """adapt re@@ a@@ c@@ t re@@ adapt apt""".split()
__snake_case : List[str] = tokenizer.tokenize(__magic_name__ )
self.assertListEqual(__magic_name__ , __magic_name__ )
__snake_case : Union[str, Any] = tokens + [tokenizer.unk_token]
__snake_case : Union[str, Any] = [0, 1, 2, 4, 5, 1, 0, 3, 6]
self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__ ) , __magic_name__ )
| 26 |
"""simple docstring"""
from typing import Callable, Optional, Union
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_lowerCamelCase = logging.get_logger(__name__)
_lowerCamelCase = {
'''microsoft/xprophetnet-large-wiki100-cased''': (
'''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json'''
),
}
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = '''xlm-prophetnet'''
lowerCamelCase__ = ['''past_key_values''']
lowerCamelCase__ = {
'''num_attention_heads''': '''num_encoder_attention_heads''',
}
def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size
__SCREAMING_SNAKE_CASE : Optional[int] = hidden_size
__SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim
__SCREAMING_SNAKE_CASE : str = num_encoder_layers
__SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads
__SCREAMING_SNAKE_CASE : str = decoder_ffn_dim
__SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers
__SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads
__SCREAMING_SNAKE_CASE : Dict = max_position_embeddings
__SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter)
__SCREAMING_SNAKE_CASE : Any = activation_function
# parameters for xlmprophetnet
__SCREAMING_SNAKE_CASE : List[Any] = ngram
__SCREAMING_SNAKE_CASE : int = num_buckets
__SCREAMING_SNAKE_CASE : List[str] = relative_max_distance
__SCREAMING_SNAKE_CASE : str = disable_ngram_loss
__SCREAMING_SNAKE_CASE : Optional[int] = eps
# 3 Types of Dropout
__SCREAMING_SNAKE_CASE : int = attention_dropout
__SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout
__SCREAMING_SNAKE_CASE : Dict = dropout
__SCREAMING_SNAKE_CASE : Any = use_cache
super().__init__(
pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , )
@property
def SCREAMING_SNAKE_CASE_ ( self :int ):
return self.num_encoder_layers + self.num_decoder_layers
@num_hidden_layers.setter
def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ):
raise NotImplementedError(
'''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and'''
''' `num_decoder_layers`.''' )
| 674 | 0 |
import numpy as np
def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> np.array:
"""simple docstring"""
return (2 / (1 + np.exp(-2 * vector ))) - 1
if __name__ == "__main__":
import doctest
doctest.testmod()
| 27 |
"""simple docstring"""
import ast
import os
import re
import shutil
import tempfile
import unittest
from unittest import mock
import torch
from accelerate.test_utils.examples import compare_against_test
from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow
from accelerate.utils import write_basic_config
# DataLoaders built from `test_samples/MRPC` for quick testing
# Should mock `{script_name}.get_dataloaders` via:
# @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders)
_lowerCamelCase = [
'''cross_validation.py''',
'''gradient_accumulation.py''',
'''local_sgd.py''',
'''multi_process_metrics.py''',
'''memory.py''',
'''automatic_gradient_accumulation.py''',
'''fsdp_with_peak_mem_tracking.py''',
'''deepspeed_with_config_support.py''',
'''megatron_lm_gpt_pretraining.py''',
]
class snake_case ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ):
__SCREAMING_SNAKE_CASE : List[str] = None
__SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) )
__SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' )
for item in os.listdir(_lowerCamelCase ):
if item not in EXCLUDE_EXAMPLES:
__SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase )
if os.path.isfile(_lowerCamelCase ) and ".py" in item_path:
with self.subTest(
tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ):
__SCREAMING_SNAKE_CASE : Tuple = compare_against_test(
os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase )
if special_strings is not None:
for string in special_strings:
__SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' )
self.assertEqual(_lowerCamelCase , '''''' )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase )
self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) )
__SCREAMING_SNAKE_CASE : Optional[int] = [
''' ''' * 1_6 + '''{\n\n''',
''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''',
''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''',
''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''',
''' ''' * 2_0 + '''"epoch": epoch,\n\n''',
''' ''' * 1_6 + '''},\n\n''',
''' ''' * 1_6 + '''step=epoch,\n''',
''' ''' * 1_2,
''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''',
]
self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
@mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} )
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = False
@classmethod
def SCREAMING_SNAKE_CASE_ ( cls :Dict ):
super().setUpClass()
__SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp()
__SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' )
write_basic_config(save_location=cls.configPath )
__SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath]
@classmethod
def SCREAMING_SNAKE_CASE_ ( cls :Dict ):
super().tearDownClass()
shutil.rmtree(cls._tmpdir )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
__SCREAMING_SNAKE_CASE : str = f'''
examples/by_feature/checkpointing.py
--checkpointing_steps epoch
--output_dir {self.tmpdir}
'''.split()
run_command(self._launch_args + testargs )
self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
__SCREAMING_SNAKE_CASE : Optional[Any] = f'''
examples/by_feature/checkpointing.py
--checkpointing_steps 1
--output_dir {self.tmpdir}
'''.split()
__SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs )
self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
__SCREAMING_SNAKE_CASE : Optional[int] = f'''
examples/by_feature/checkpointing.py
--resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )}
'''.split()
__SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase )
self.assertNotIn('''epoch 0:''' , _lowerCamelCase )
self.assertIn('''epoch 1:''' , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Optional[int] = f'''
examples/by_feature/checkpointing.py
--resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )}
'''.split()
__SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase )
if torch.cuda.is_available():
__SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count()
else:
__SCREAMING_SNAKE_CASE : Optional[int] = 1
if num_processes > 1:
self.assertNotIn('''epoch 0:''' , _lowerCamelCase )
self.assertIn('''epoch 1:''' , _lowerCamelCase )
else:
self.assertIn('''epoch 0:''' , _lowerCamelCase )
self.assertIn('''epoch 1:''' , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE : Optional[Any] = '''
examples/by_feature/cross_validation.py
--num_folds 2
'''.split()
with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1]
__SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase )
self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 )
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py''']
run_command(self._launch_args + testargs )
@require_trackers
@mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
with tempfile.TemporaryDirectory() as tmpdir:
__SCREAMING_SNAKE_CASE : int = f'''
examples/by_feature/tracking.py
--with_tracking
--project_dir {tmpdir}
'''.split()
run_command(self._launch_args + testargs )
self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py''']
run_command(self._launch_args + testargs )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
__SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py''']
run_command(self._launch_args + testargs )
| 674 | 0 |
'''simple docstring'''
from typing import Any
def lowercase__( __UpperCamelCase: list ):
"""simple docstring"""
if not input_list:
return []
SCREAMING_SNAKE_CASE : Union[str, Any] = [input_list.count(__UpperCamelCase ) for value in input_list]
SCREAMING_SNAKE_CASE : Any = max(__UpperCamelCase ) # Gets the maximum count in the input list.
# Gets values of modes
return sorted({input_list[i] for i, value in enumerate(__UpperCamelCase ) if value == y} )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 28 |
"""simple docstring"""
import argparse
import logging
import os
import time
import timeit
import datasets
import numpy as np
import pycuda.autoinit # noqa: F401
import pycuda.driver as cuda
import tensorrt as trt
import torch
from absl import logging as absl_logging
from accelerate import Accelerator
from datasets import load_dataset, load_metric
from torch.utils.data import DataLoader
from utils_qa import postprocess_qa_predictions
import transformers
from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed
from transformers.trainer_pt_utils import nested_concat, nested_truncate
_lowerCamelCase = trt.Logger(trt.Logger.WARNING)
_lowerCamelCase = absl_logging.get_absl_logger()
absl_logger.setLevel(logging.WARNING)
_lowerCamelCase = logging.getLogger(__name__)
_lowerCamelCase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--onnx_model_path''',
default=None,
type=str,
required=True,
help='''Path to ONNX model: ''',
)
parser.add_argument(
'''--output_dir''',
default=None,
type=str,
required=True,
help='''The output directory where the model checkpoints and predictions will be written.''',
)
# Other parameters
parser.add_argument(
'''--tokenizer_name''',
default='''''',
type=str,
required=True,
help='''Pretrained tokenizer name or path if not the same as model_name''',
)
parser.add_argument(
'''--version_2_with_negative''',
action='''store_true''',
help='''If true, the SQuAD examples contain some that do not have an answer.''',
)
parser.add_argument(
'''--null_score_diff_threshold''',
type=float,
default=0.0,
help='''If null_score - best_non_null is greater than the threshold predict null.''',
)
parser.add_argument(
'''--max_seq_length''',
default=3_84,
type=int,
help=(
'''The maximum total input sequence length after WordPiece tokenization. Sequences '''
'''longer than this will be truncated, and sequences shorter than this will be padded.'''
),
)
parser.add_argument(
'''--doc_stride''',
default=1_28,
type=int,
help='''When splitting up a long document into chunks, how much stride to take between chunks.''',
)
parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''')
parser.add_argument(
'''--n_best_size''',
default=20,
type=int,
help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''',
)
parser.add_argument(
'''--max_answer_length''',
default=30,
type=int,
help=(
'''The maximum length of an answer that can be generated. This is needed because the start '''
'''and end predictions are not conditioned on one another.'''
),
)
parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''')
parser.add_argument(
'''--dataset_name''',
type=str,
default=None,
required=True,
help='''The name of the dataset to use (via the datasets library).''',
)
parser.add_argument(
'''--dataset_config_name''',
type=str,
default=None,
help='''The configuration name of the dataset to use (via the datasets library).''',
)
parser.add_argument(
'''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.'''
)
parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''')
parser.add_argument(
'''--fp16''',
action='''store_true''',
help='''Whether to use 16-bit (mixed) precision instead of 32-bit''',
)
parser.add_argument(
'''--int8''',
action='''store_true''',
help='''Whether to use INT8''',
)
_lowerCamelCase = parser.parse_args()
if args.tokenizer_name:
_lowerCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True)
else:
raise ValueError(
'''You are instantiating a new tokenizer from scratch. This is not supported by this script.'''
'''You can do it from another script, save it, and load it from here, using --tokenizer_name.'''
)
logger.info('''Training/evaluation parameters %s''', args)
_lowerCamelCase = args.per_device_eval_batch_size
_lowerCamelCase = (args.eval_batch_size, args.max_seq_length)
# TRT Engine properties
_lowerCamelCase = True
_lowerCamelCase = '''temp_engine/bert-fp32.engine'''
if args.fpaa:
_lowerCamelCase = '''temp_engine/bert-fp16.engine'''
if args.inta:
_lowerCamelCase = '''temp_engine/bert-int8.engine'''
# import ONNX file
if not os.path.exists('''temp_engine'''):
os.makedirs('''temp_engine''')
_lowerCamelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser(
network, TRT_LOGGER
) as parser:
with open(args.onnx_model_path, '''rb''') as model:
if not parser.parse(model.read()):
for error in range(parser.num_errors):
print(parser.get_error(error))
# Query input names and shapes from parsed TensorRT network
_lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)]
_lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"]
with builder.create_builder_config() as config:
_lowerCamelCase = 1 << 50
if STRICT_TYPES:
config.set_flag(trt.BuilderFlag.STRICT_TYPES)
if args.fpaa:
config.set_flag(trt.BuilderFlag.FPaa)
if args.inta:
config.set_flag(trt.BuilderFlag.INTa)
_lowerCamelCase = builder.create_optimization_profile()
config.add_optimization_profile(profile)
for i in range(len(input_names)):
profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE)
_lowerCamelCase = builder.build_engine(network, config)
# serialize_engine and store in file (can be directly loaded and deserialized):
with open(engine_name, '''wb''') as f:
f.write(engine.serialize())
def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa )
# Copy inputs
cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase_ )
cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase_ )
cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase_ )
# start time
__SCREAMING_SNAKE_CASE : Tuple = time.time()
# Run inference
context.execute_async(
bindings=[int(lowercase_ ) for d_inp in d_inputs] + [int(lowercase_ ), int(lowercase_ )] , stream_handle=stream.handle )
# Transfer predictions back from GPU
cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ )
cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ )
# Synchronize the stream and take time
stream.synchronize()
# end time
__SCREAMING_SNAKE_CASE : List[str] = time.time()
__SCREAMING_SNAKE_CASE : int = end_time - start_time
__SCREAMING_SNAKE_CASE : int = (h_outputa, h_outputa)
# print(outputs)
return outputs, infer_time
# Initialize the accelerator. We will let the accelerator handle device placement for us in this example.
_lowerCamelCase = Accelerator()
# Make one log on every process with the configuration for debugging.
logging.basicConfig(
format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''',
datefmt='''%m/%d/%Y %H:%M:%S''',
level=logging.INFO,
)
# Setup logging, we only want one process per machine to log things on the screen.
# accelerator.is_local_main_process is only True for one process per machine.
logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR)
if accelerator.is_local_main_process:
datasets.utils.logging.set_verbosity_warning()
transformers.utils.logging.set_verbosity_info()
else:
datasets.utils.logging.set_verbosity_error()
transformers.utils.logging.set_verbosity_error()
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
# (the dataset will be downloaded automatically from the datasets Hub).
#
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
# 'text' is found. You can easily tweak this behavior (see below).
if args.dataset_name is not None:
# Downloading and loading a dataset from the hub.
_lowerCamelCase = load_dataset(args.dataset_name, args.dataset_config_name)
else:
raise ValueError('''Evaluation requires a dataset name''')
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
# Preprocessing the datasets.
# Preprocessing is slighlty different for training and evaluation.
_lowerCamelCase = raw_datasets['''validation'''].column_names
_lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0]
_lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1]
_lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2]
# Padding side determines if we do (question|context) or (context|question).
_lowerCamelCase = tokenizer.padding_side == '''right'''
if args.max_seq_length > tokenizer.model_max_length:
logger.warning(
f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the'
f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.'
)
_lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length)
def lowerCAmelCase_ ( lowercase_ : Tuple ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = [q.lstrip() for q in examples[question_column_name]]
# Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results
# in one example possible giving several features when a context is long, each of those features having a
# context that overlaps a bit the context of the previous feature.
__SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer(
examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=lowercase_ , stride=args.doc_stride , return_overflowing_tokens=lowercase_ , return_offsets_mapping=lowercase_ , padding='''max_length''' , )
# Since one example might give us several features if it has a long context, we need a map from a feature to
# its corresponding example. This key gives us just that.
__SCREAMING_SNAKE_CASE : Optional[int] = tokenized_examples.pop('''overflow_to_sample_mapping''' )
# For evaluation, we will need to convert our predictions to substrings of the context, so we keep the
# corresponding example_id and we will store the offset mappings.
__SCREAMING_SNAKE_CASE : Any = []
for i in range(len(tokenized_examples['''input_ids'''] ) ):
# Grab the sequence corresponding to that example (to know what is the context and what is the question).
__SCREAMING_SNAKE_CASE : int = tokenized_examples.sequence_ids(lowercase_ )
__SCREAMING_SNAKE_CASE : str = 1 if pad_on_right else 0
# One example can give several spans, this is the index of the example containing this span of text.
__SCREAMING_SNAKE_CASE : str = sample_mapping[i]
tokenized_examples["example_id"].append(examples['''id'''][sample_index] )
# Set to None the offset_mapping that are not part of the context so it's easy to determine if a token
# position is part of the context or not.
__SCREAMING_SNAKE_CASE : List[str] = [
(o if sequence_ids[k] == context_index else None)
for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] )
]
return tokenized_examples
_lowerCamelCase = raw_datasets['''validation''']
# Validation Feature Creation
_lowerCamelCase = eval_examples.map(
prepare_validation_features,
batched=True,
num_proc=args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not args.overwrite_cache,
desc='''Running tokenizer on validation dataset''',
)
_lowerCamelCase = default_data_collator
_lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping'''])
_lowerCamelCase = DataLoader(
eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size
)
def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Tuple = postprocess_qa_predictions(
examples=lowercase_ , features=lowercase_ , predictions=lowercase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase_ , )
# Format the result to the format the metric expects.
if args.version_2_with_negative:
__SCREAMING_SNAKE_CASE : Union[str, Any] = [
{'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items()
]
else:
__SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()]
__SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples]
return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ )
_lowerCamelCase = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''')
# Evaluation!
logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path)
with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine(
f.read()
) as engine, engine.create_execution_context() as context:
# setup for TRT inferrence
for i in range(len(input_names)):
context.set_binding_shape(i, INPUT_SHAPE)
assert context.all_binding_shapes_specified
def lowerCAmelCase_ ( lowercase_ : Any ):
'''simple docstring'''
return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize
# Allocate device memory for inputs and outputs.
_lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)]
# Allocate output buffer
_lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa)
_lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa)
_lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes)
_lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes)
# Create a stream in which to copy inputs/outputs and run inference.
_lowerCamelCase = cuda.Stream()
# Evaluation
logger.info('''***** Running Evaluation *****''')
logger.info(f' Num examples = {len(eval_dataset)}')
logger.info(f' Batch size = {args.per_device_eval_batch_size}')
_lowerCamelCase = 0.0
_lowerCamelCase = 0
_lowerCamelCase = timeit.default_timer()
_lowerCamelCase = None
for step, batch in enumerate(eval_dataloader):
_lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream)
total_time += infer_time
niter += 1
_lowerCamelCase , _lowerCamelCase = outputs
_lowerCamelCase = torch.tensor(start_logits)
_lowerCamelCase = torch.tensor(end_logits)
# necessary to pad predictions and labels for being gathered
_lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00)
_lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00)
_lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy())
_lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00)
if all_preds is not None:
_lowerCamelCase = nested_truncate(all_preds, len(eval_dataset))
_lowerCamelCase = timeit.default_timer() - start_time
logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset))
# Inference time from TRT
logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 10_00 / niter))
logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00))
logger.info('''Total Number of Inference = %d''', niter)
_lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds)
_lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids)
logger.info(f'Evaluation metrics: {eval_metric}')
| 674 | 0 |
"""simple docstring"""
import json
import os
from typing import Optional, Tuple
import regex as re
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
A_ = logging.get_logger(__name__)
A_ = {
"""vocab_file""": """vocab.json""",
"""merges_file""": """merges.txt""",
}
A_ = {
"""vocab_file""": {"""ctrl""": """https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json"""},
"""merges_file""": {"""ctrl""": """https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt"""},
}
A_ = {
"""ctrl""": 256,
}
A_ = {
"""Pregnancy""": 16_8629,
"""Christianity""": 7675,
"""Explain""": 10_6423,
"""Fitness""": 6_3440,
"""Saving""": 6_3163,
"""Ask""": 2_7171,
"""Ass""": 9_5985,
"""Joke""": 16_3509,
"""Questions""": 4_5622,
"""Thoughts""": 4_9605,
"""Retail""": 5_2342,
"""Feminism""": 16_4338,
"""Writing""": 1_1992,
"""Atheism""": 19_2263,
"""Netflix""": 4_8616,
"""Computing""": 3_9639,
"""Opinion""": 4_3213,
"""Alone""": 4_4967,
"""Funny""": 5_8917,
"""Gaming""": 4_0358,
"""Human""": 4088,
"""India""": 1331,
"""Joker""": 7_7138,
"""Diet""": 3_6206,
"""Legal""": 1_1859,
"""Norman""": 4939,
"""Tip""": 7_2689,
"""Weight""": 5_2343,
"""Movies""": 4_6273,
"""Running""": 2_3425,
"""Science""": 2090,
"""Horror""": 3_7793,
"""Confession""": 6_0572,
"""Finance""": 1_2250,
"""Politics""": 1_6360,
"""Scary""": 19_1985,
"""Support""": 1_2654,
"""Technologies""": 3_2516,
"""Teenage""": 6_6160,
"""Event""": 3_2769,
"""Learned""": 6_7460,
"""Notion""": 18_2770,
"""Wikipedia""": 3_7583,
"""Books""": 6665,
"""Extract""": 7_6050,
"""Confessions""": 10_2701,
"""Conspiracy""": 7_5932,
"""Links""": 6_3674,
"""Narcissus""": 15_0425,
"""Relationship""": 5_4766,
"""Relationships""": 13_4796,
"""Reviews""": 4_1671,
"""News""": 4256,
"""Translation""": 2_6820,
"""multilingual""": 12_8406,
}
def lowercase ( lowerCAmelCase__ ):
lowerCamelCase_ = set()
lowerCamelCase_ = word[0]
for char in word[1:]:
pairs.add((prev_char, char) )
lowerCamelCase_ = char
lowerCamelCase_ = set(lowerCAmelCase__ )
return pairs
class __lowerCamelCase ( lowerCAmelCase ):
a__: Optional[Any] = VOCAB_FILES_NAMES
a__: List[Any] = PRETRAINED_VOCAB_FILES_MAP
a__: Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
a__: str = CONTROL_CODES
def __init__( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase="<unk>" , **UpperCAmelCase ):
super().__init__(unk_token=UpperCAmelCase , **UpperCAmelCase )
with open(UpperCAmelCase , encoding='''utf-8''' ) as vocab_handle:
lowerCamelCase_ = json.load(UpperCAmelCase )
lowerCamelCase_ = {v: k for k, v in self.encoder.items()}
with open(UpperCAmelCase , encoding='''utf-8''' ) as merges_handle:
lowerCamelCase_ = merges_handle.read().split('''\n''' )[1:-1]
lowerCamelCase_ = [tuple(merge.split() ) for merge in merges]
lowerCamelCase_ = dict(zip(UpperCAmelCase , range(len(UpperCAmelCase ) ) ) )
lowerCamelCase_ = {}
@property
def UpperCAmelCase__ ( self ):
return len(self.encoder )
def UpperCAmelCase__ ( self ):
return dict(self.encoder , **self.added_tokens_encoder )
def UpperCAmelCase__ ( self , UpperCAmelCase ):
if token in self.cache:
return self.cache[token]
lowerCamelCase_ = tuple(UpperCAmelCase )
lowerCamelCase_ = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] )
lowerCamelCase_ = get_pairs(UpperCAmelCase )
if not pairs:
return token
while True:
lowerCamelCase_ = min(UpperCAmelCase , key=lambda UpperCAmelCase : self.bpe_ranks.get(UpperCAmelCase , float('''inf''' ) ) )
if bigram not in self.bpe_ranks:
break
lowerCamelCase_ , lowerCamelCase_ = bigram
lowerCamelCase_ = []
lowerCamelCase_ = 0
while i < len(UpperCAmelCase ):
try:
lowerCamelCase_ = word.index(UpperCAmelCase , UpperCAmelCase )
except ValueError:
new_word.extend(word[i:] )
break
else:
new_word.extend(word[i:j] )
lowerCamelCase_ = j
if word[i] == first and i < len(UpperCAmelCase ) - 1 and word[i + 1] == second:
new_word.append(first + second )
i += 2
else:
new_word.append(word[i] )
i += 1
lowerCamelCase_ = tuple(UpperCAmelCase )
lowerCamelCase_ = new_word
if len(UpperCAmelCase ) == 1:
break
else:
lowerCamelCase_ = get_pairs(UpperCAmelCase )
lowerCamelCase_ = '''@@ '''.join(UpperCAmelCase )
lowerCamelCase_ = word[:-4]
lowerCamelCase_ = word
return word
def UpperCAmelCase__ ( self , UpperCAmelCase ):
lowerCamelCase_ = []
lowerCamelCase_ = re.findall(r'''\S+\n?''' , UpperCAmelCase )
for token in words:
split_tokens.extend(list(self.bpe(UpperCAmelCase ).split(''' ''' ) ) )
return split_tokens
def UpperCAmelCase__ ( self , UpperCAmelCase ):
return self.encoder.get(UpperCAmelCase , self.encoder.get(self.unk_token ) )
def UpperCAmelCase__ ( self , UpperCAmelCase ):
return self.decoder.get(UpperCAmelCase , self.unk_token )
def UpperCAmelCase__ ( self , UpperCAmelCase ):
lowerCamelCase_ = ''' '''.join(UpperCAmelCase ).replace('''@@ ''' , '''''' ).strip()
return out_string
def UpperCAmelCase__ ( self , UpperCAmelCase , UpperCAmelCase = None ):
if not os.path.isdir(UpperCAmelCase ):
logger.error(f"Vocabulary path ({save_directory}) should be a directory" )
return
lowerCamelCase_ = os.path.join(
UpperCAmelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
lowerCamelCase_ = os.path.join(
UpperCAmelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] )
with open(UpperCAmelCase , '''w''' , encoding='''utf-8''' ) as f:
f.write(json.dumps(self.encoder , indent=2 , sort_keys=UpperCAmelCase , ensure_ascii=UpperCAmelCase ) + '''\n''' )
lowerCamelCase_ = 0
with open(UpperCAmelCase , '''w''' , encoding='''utf-8''' ) as writer:
writer.write('''#version: 0.2\n''' )
for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda UpperCAmelCase : kv[1] ):
if index != token_index:
logger.warning(
f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
''' Please check that the tokenizer is not corrupted!''' )
lowerCamelCase_ = token_index
writer.write(''' '''.join(UpperCAmelCase ) + '''\n''' )
index += 1
return vocab_file, merge_file
# def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):
# filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens))
# tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens)
# tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far)
# return ''.join(tokens_generated_so_far)
| 29 |
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import is_tf_available, is_torch_available
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow
if is_tf_available():
from transformers import (
AutoConfig,
BertConfig,
GPTaConfig,
TaConfig,
TFAutoModel,
TFAutoModelForCausalLM,
TFAutoModelForMaskedLM,
TFAutoModelForPreTraining,
TFAutoModelForQuestionAnswering,
TFAutoModelForSeqaSeqLM,
TFAutoModelForSequenceClassification,
TFAutoModelWithLMHead,
TFBertForMaskedLM,
TFBertForPreTraining,
TFBertForQuestionAnswering,
TFBertForSequenceClassification,
TFBertModel,
TFGPTaLMHeadModel,
TFRobertaForMaskedLM,
TFTaForConditionalGeneration,
)
from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST
from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST
from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST
if is_torch_available():
from transformers import (
AutoModel,
AutoModelForCausalLM,
AutoModelForMaskedLM,
AutoModelForPreTraining,
AutoModelForQuestionAnswering,
AutoModelForSeqaSeqLM,
AutoModelForSequenceClassification,
AutoModelWithLMHead,
BertForMaskedLM,
BertForPreTraining,
BertForQuestionAnswering,
BertForSequenceClassification,
BertModel,
GPTaLMHeadModel,
RobertaForMaskedLM,
TaForConditionalGeneration,
)
@is_pt_tf_cross_test
class snake_case ( unittest.TestCase ):
@slow
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
__SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
__SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Any ):
for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :int ):
for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
__SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
__SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
| 674 | 0 |
from functools import reduce
__a = (
'73167176531330624919225119674426574742355349194934'
'96983520312774506326239578318016984801869478851843'
'85861560789112949495459501737958331952853208805511'
'12540698747158523863050715693290963295227443043557'
'66896648950445244523161731856403098711121722383113'
'62229893423380308135336276614282806444486645238749'
'30358907296290491560440772390713810515859307960866'
'70172427121883998797908792274921901699720888093776'
'65727333001053367881220235421809751254540594752243'
'52584907711670556013604839586446706324415722155397'
'53697817977846174064955149290862569321978468622482'
'83972241375657056057490261407972968652414535100474'
'82166370484403199890008895243450658541227588666881'
'16427171479924442928230863465674813919123162824586'
'17866458359124566529476545682848912883142607690042'
'24219022671055626321111109370544217506941658960408'
'07198403850962455444362981230987879927244284909188'
'84580156166097919133875499200524063689912560717606'
'05886116467109405077541002256983155200055935729725'
'71636269561882670428252483600823257530420752963450'
)
def lowerCamelCase__ ( _lowercase = N ):
'''simple docstring'''
return max(
# mypy cannot properly interpret reduce
int(reduce(lambda _lowercase , _lowercase : str(int(_lowercase ) * int(_lowercase ) ) , n[i : i + 13] ) )
for i in range(len(_lowercase ) - 12 ) )
if __name__ == "__main__":
print(F"""{solution() = }""") | 30 |
"""simple docstring"""
import os
import re
import warnings
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
if TYPE_CHECKING:
from ...tokenization_utils_base import TextInput
from ...utils import logging
_lowerCamelCase = logging.get_logger(__name__)
_lowerCamelCase = {'''vocab_file''': '''spiece.model'''}
_lowerCamelCase = {
'''vocab_file''': {
'''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''',
'''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''',
'''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''',
'''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''',
'''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''',
}
}
# TODO(PVP) - this should be removed in Transformers v5
_lowerCamelCase = {
'''t5-small''': 5_12,
'''t5-base''': 5_12,
'''t5-large''': 5_12,
'''t5-3b''': 5_12,
'''t5-11b''': 5_12,
}
_lowerCamelCase = '''▁'''
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = VOCAB_FILES_NAMES
lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP
lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowerCamelCase__ = ['''input_ids''', '''attention_mask''']
def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ):
# Add extra_ids to the special token list
if extra_ids > 0 and additional_special_tokens is None:
__SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )]
elif extra_ids > 0 and additional_special_tokens is not None:
# Check that we have the right number of extra_id special tokens
__SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) )
if extra_tokens != extra_ids:
raise ValueError(
f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are'''
''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids'''
''' tokens''' )
if legacy:
logger.warning_once(
f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to'''
''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' )
__SCREAMING_SNAKE_CASE : Optional[Any] = legacy
__SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , )
__SCREAMING_SNAKE_CASE : Tuple = vocab_file
__SCREAMING_SNAKE_CASE : List[str] = extra_ids
__SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(_lowerCamelCase )
@staticmethod
def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ):
if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes:
__SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path]
if init_max_model_length is not None and init_max_model_length != max_model_length:
return init_max_model_length
elif init_max_model_length is None:
warnings.warn(
'''This tokenizer was incorrectly instantiated with a model max length of'''
f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this'''
''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with'''
''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on'''
f''' {pretrained_model_name_or_path} automatically truncating your input to'''
f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences'''
f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with'''
''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please'''
''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , )
return max_model_length
@property
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
return self.sp_model.get_piece_size() + self._extra_ids
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ):
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase )
# normal case: some special tokens
if token_ids_a is None:
return ([0] * len(_lowerCamelCase )) + [1]
return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1]
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
return list(
set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()]
def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ):
if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id:
warnings.warn(
f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated'''
''' eos tokens being added.''' )
return token_ids
else:
return token_ids + [self.eos_token_id]
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ):
__SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id]
if token_ids_a is None:
return len(token_ids_a + eos ) * [0]
return len(token_ids_a + eos + token_ids_a + eos ) * [0]
def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ):
__SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase )
if token_ids_a is None:
return token_ids_a
else:
__SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase )
return token_ids_a + token_ids_a
def __getstate__( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Any = self.__dict__.copy()
__SCREAMING_SNAKE_CASE : List[str] = None
return state
def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ):
__SCREAMING_SNAKE_CASE : Tuple = d
# for backward compatibility
if not hasattr(self , '''sp_model_kwargs''' ):
__SCREAMING_SNAKE_CASE : Optional[int] = {}
__SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ):
# Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at
# the beginning of the text
if not self.legacy:
__SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' )
return super().tokenize(_lowerCamelCase , **_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ):
if not self.legacy:
__SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase )
if is_first:
__SCREAMING_SNAKE_CASE : str = text[1:]
__SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase )
if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ):
__SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:]
return tokens
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ):
if token.startswith('''<extra_id_''' ):
__SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) )
return self.vocab_size - num - 1
return self.sp_model.piece_to_id(_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ):
if index < self.sp_model.get_piece_size():
__SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase )
else:
__SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>'''
return token
def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ):
__SCREAMING_SNAKE_CASE : str = []
__SCREAMING_SNAKE_CASE : Dict = ''''''
__SCREAMING_SNAKE_CASE : Dict = False
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
if not prev_is_special:
out_string += " "
out_string += self.sp_model.decode(_lowerCamelCase ) + token
__SCREAMING_SNAKE_CASE : List[str] = True
__SCREAMING_SNAKE_CASE : str = []
else:
current_sub_tokens.append(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = False
out_string += self.sp_model.decode(_lowerCamelCase )
return out_string.strip()
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ):
if not os.path.isdir(_lowerCamelCase ):
logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' )
return
__SCREAMING_SNAKE_CASE : List[str] = os.path.join(
_lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , _lowerCamelCase )
elif not os.path.isfile(self.vocab_file ):
with open(_lowerCamelCase , '''wb''' ) as fi:
__SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto()
fi.write(_lowerCamelCase )
return (out_vocab_file,)
| 674 | 0 |
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
convert_to_rgb,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
OPENAI_CLIP_MEAN,
OPENAI_CLIP_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
lowerCamelCase__ : int = logging.get_logger(__name__)
if is_vision_available():
import PIL
class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE ):
'''simple docstring'''
lowercase_ = ["pixel_values"]
def __init__( self : List[str] , _lowerCAmelCase : bool = True , _lowerCAmelCase : Dict[str, int] = None , _lowerCAmelCase : PILImageResampling = PILImageResampling.BICUBIC , _lowerCAmelCase : bool = True , _lowerCAmelCase : Dict[str, int] = None , _lowerCAmelCase : bool = True , _lowerCAmelCase : Union[int, float] = 1 / 255 , _lowerCAmelCase : bool = True , _lowerCAmelCase : Optional[Union[float, List[float]]] = None , _lowerCAmelCase : Optional[Union[float, List[float]]] = None , _lowerCAmelCase : bool = True , **_lowerCAmelCase : Optional[Any] , ):
super().__init__(**_lowerCAmelCase )
SCREAMING_SNAKE_CASE_ = size if size is not None else {'shortest_edge': 224}
SCREAMING_SNAKE_CASE_ = get_size_dict(_lowerCAmelCase , default_to_square=_lowerCAmelCase )
SCREAMING_SNAKE_CASE_ = crop_size if crop_size is not None else {'height': 224, 'width': 224}
SCREAMING_SNAKE_CASE_ = get_size_dict(_lowerCAmelCase , default_to_square=_lowerCAmelCase , param_name='crop_size' )
SCREAMING_SNAKE_CASE_ = do_resize
SCREAMING_SNAKE_CASE_ = size
SCREAMING_SNAKE_CASE_ = resample
SCREAMING_SNAKE_CASE_ = do_center_crop
SCREAMING_SNAKE_CASE_ = crop_size
SCREAMING_SNAKE_CASE_ = do_rescale
SCREAMING_SNAKE_CASE_ = rescale_factor
SCREAMING_SNAKE_CASE_ = do_normalize
SCREAMING_SNAKE_CASE_ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
SCREAMING_SNAKE_CASE_ = image_std if image_std is not None else OPENAI_CLIP_STD
SCREAMING_SNAKE_CASE_ = do_convert_rgb
def lowerCAmelCase_ ( self : Tuple , _lowerCAmelCase : np.ndarray , _lowerCAmelCase : Dict[str, int] , _lowerCAmelCase : PILImageResampling = PILImageResampling.BICUBIC , _lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_lowerCAmelCase : List[str] , ):
SCREAMING_SNAKE_CASE_ = get_size_dict(_lowerCAmelCase , default_to_square=_lowerCAmelCase )
if "shortest_edge" not in size:
raise ValueError(F"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}" )
SCREAMING_SNAKE_CASE_ = get_resize_output_image_size(_lowerCAmelCase , size=size['shortest_edge'] , default_to_square=_lowerCAmelCase )
return resize(_lowerCAmelCase , size=_lowerCAmelCase , resample=_lowerCAmelCase , data_format=_lowerCAmelCase , **_lowerCAmelCase )
def lowerCAmelCase_ ( self : Union[str, Any] , _lowerCAmelCase : np.ndarray , _lowerCAmelCase : Dict[str, int] , _lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_lowerCAmelCase : Any , ):
SCREAMING_SNAKE_CASE_ = get_size_dict(_lowerCAmelCase )
if "height" not in size or "width" not in size:
raise ValueError(F"The `size` parameter must contain the keys (height, width). Got {size.keys()}" )
return center_crop(_lowerCAmelCase , size=(size['height'], size['width']) , data_format=_lowerCAmelCase , **_lowerCAmelCase )
def lowerCAmelCase_ ( self : Tuple , _lowerCAmelCase : np.ndarray , _lowerCAmelCase : Union[int, float] , _lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_lowerCAmelCase : Any , ):
return rescale(_lowerCAmelCase , scale=_lowerCAmelCase , data_format=_lowerCAmelCase , **_lowerCAmelCase )
def lowerCAmelCase_ ( self : List[Any] , _lowerCAmelCase : np.ndarray , _lowerCAmelCase : Union[float, List[float]] , _lowerCAmelCase : Union[float, List[float]] , _lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_lowerCAmelCase : List[Any] , ):
return normalize(_lowerCAmelCase , mean=_lowerCAmelCase , std=_lowerCAmelCase , data_format=_lowerCAmelCase , **_lowerCAmelCase )
def lowerCAmelCase_ ( self : Any , _lowerCAmelCase : ImageInput , _lowerCAmelCase : bool = None , _lowerCAmelCase : Dict[str, int] = None , _lowerCAmelCase : PILImageResampling = None , _lowerCAmelCase : bool = None , _lowerCAmelCase : int = None , _lowerCAmelCase : bool = None , _lowerCAmelCase : float = None , _lowerCAmelCase : bool = None , _lowerCAmelCase : Optional[Union[float, List[float]]] = None , _lowerCAmelCase : Optional[Union[float, List[float]]] = None , _lowerCAmelCase : bool = None , _lowerCAmelCase : Optional[Union[str, TensorType]] = None , _lowerCAmelCase : Optional[ChannelDimension] = ChannelDimension.FIRST , **_lowerCAmelCase : Union[str, Any] , ):
SCREAMING_SNAKE_CASE_ = do_resize if do_resize is not None else self.do_resize
SCREAMING_SNAKE_CASE_ = size if size is not None else self.size
SCREAMING_SNAKE_CASE_ = get_size_dict(_lowerCAmelCase , param_name='size' , default_to_square=_lowerCAmelCase )
SCREAMING_SNAKE_CASE_ = resample if resample is not None else self.resample
SCREAMING_SNAKE_CASE_ = do_center_crop if do_center_crop is not None else self.do_center_crop
SCREAMING_SNAKE_CASE_ = crop_size if crop_size is not None else self.crop_size
SCREAMING_SNAKE_CASE_ = get_size_dict(_lowerCAmelCase , param_name='crop_size' , default_to_square=_lowerCAmelCase )
SCREAMING_SNAKE_CASE_ = do_rescale if do_rescale is not None else self.do_rescale
SCREAMING_SNAKE_CASE_ = rescale_factor if rescale_factor is not None else self.rescale_factor
SCREAMING_SNAKE_CASE_ = do_normalize if do_normalize is not None else self.do_normalize
SCREAMING_SNAKE_CASE_ = image_mean if image_mean is not None else self.image_mean
SCREAMING_SNAKE_CASE_ = image_std if image_std is not None else self.image_std
SCREAMING_SNAKE_CASE_ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
SCREAMING_SNAKE_CASE_ = make_list_of_images(_lowerCAmelCase )
if not valid_images(_lowerCAmelCase ):
raise ValueError(
'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
'torch.Tensor, tf.Tensor or jax.ndarray.' )
if do_resize and size is None:
raise ValueError('Size must be specified if do_resize is True.' )
if do_center_crop and crop_size is None:
raise ValueError('Crop size must be specified if do_center_crop is True.' )
if do_rescale and rescale_factor is None:
raise ValueError('Rescale factor must be specified if do_rescale is True.' )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError('Image mean and std must be specified if do_normalize is True.' )
# PIL RGBA images are converted to RGB
if do_convert_rgb:
SCREAMING_SNAKE_CASE_ = [convert_to_rgb(_lowerCAmelCase ) for image in images]
# All transformations expect numpy arrays.
SCREAMING_SNAKE_CASE_ = [to_numpy_array(_lowerCAmelCase ) for image in images]
if do_resize:
SCREAMING_SNAKE_CASE_ = [self.resize(image=_lowerCAmelCase , size=_lowerCAmelCase , resample=_lowerCAmelCase ) for image in images]
if do_center_crop:
SCREAMING_SNAKE_CASE_ = [self.center_crop(image=_lowerCAmelCase , size=_lowerCAmelCase ) for image in images]
if do_rescale:
SCREAMING_SNAKE_CASE_ = [self.rescale(image=_lowerCAmelCase , scale=_lowerCAmelCase ) for image in images]
if do_normalize:
SCREAMING_SNAKE_CASE_ = [self.normalize(image=_lowerCAmelCase , mean=_lowerCAmelCase , std=_lowerCAmelCase ) for image in images]
SCREAMING_SNAKE_CASE_ = [to_channel_dimension_format(_lowerCAmelCase , _lowerCAmelCase ) for image in images]
SCREAMING_SNAKE_CASE_ = {'pixel_values': images}
return BatchFeature(data=_lowerCAmelCase , tensor_type=_lowerCAmelCase ) | 31 |
"""simple docstring"""
import os
import pytest
import yaml
from datasets.features.features import Features, Value
from datasets.info import DatasetInfo, DatasetInfosDict
@pytest.mark.parametrize(
'''files''' , [
['''full:README.md''', '''dataset_infos.json'''],
['''empty:README.md''', '''dataset_infos.json'''],
['''dataset_infos.json'''],
['''full:README.md'''],
] , )
def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' )
if "full:README.md" in files:
with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f:
f.write('''---\ndataset_info:\n dataset_size: 42\n---''' )
if "empty:README.md" in files:
with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f:
f.write('''''' )
# we want to support dataset_infos.json for backward compatibility
if "dataset_infos.json" in files:
with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f:
f.write('''{"default": {"dataset_size": 42}}''' )
__SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ )
assert dataset_infos
assert dataset_infos["default"].dataset_size == 42
@pytest.mark.parametrize(
'''dataset_info''' , [
DatasetInfo(),
DatasetInfo(
description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ),
] , )
def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ )
dataset_info.write_to_directory(lowercase_ )
__SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ )
assert dataset_info == reloaded
assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) )
def lowerCAmelCase_ ( ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Tuple = DatasetInfo(
description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , )
__SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict()
assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML )
for key in DatasetInfo._INCLUDED_INFO_IN_YAML:
assert key in dataset_info_yaml_dict
assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) )
__SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ )
__SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ )
assert dataset_info_yaml_dict == reloaded
def lowerCAmelCase_ ( ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo()
__SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict()
assert dataset_info_yaml_dict == {}
@pytest.mark.parametrize(
'''dataset_infos_dict''' , [
DatasetInfosDict(),
DatasetInfosDict({'''default''': DatasetInfo()} ),
DatasetInfosDict({'''my_config_name''': DatasetInfo()} ),
DatasetInfosDict(
{
'''default''': DatasetInfo(
description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , )
} ),
DatasetInfosDict(
{
'''v1''': DatasetInfo(dataset_size=42 ),
'''v2''': DatasetInfo(dataset_size=1337 ),
} ),
] , )
def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ )
dataset_infos_dict.write_to_directory(lowercase_ )
__SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ )
# the config_name of the dataset_infos_dict take over the attribute
for config_name, dataset_info in dataset_infos_dict.items():
__SCREAMING_SNAKE_CASE : Optional[int] = config_name
# the yaml representation doesn't include fields like description or citation
# so we just test that we can recover what we can from the yaml
__SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() )
assert dataset_infos_dict == reloaded
if dataset_infos_dict:
assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
| 674 | 0 |
import unittest
from transformers import BigBirdTokenizer, BigBirdTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin
UpperCAmelCase_ = "▁"
UpperCAmelCase_ = get_tests_dir("fixtures/test_sentencepiece.model")
@require_sentencepiece
@require_tokenizers
class __UpperCamelCase ( A__ , unittest.TestCase ):
__A : Tuple = BigBirdTokenizer
__A : List[str] = BigBirdTokenizerFast
__A : List[Any] = True
__A : List[Any] = True
def UpperCamelCase( self ):
super().setUp()
_UpperCAmelCase = self.tokenizer_class(_UpperCamelCase , keep_accents=_UpperCamelCase )
tokenizer.save_pretrained(self.tmpdirname )
def UpperCamelCase( self ):
_UpperCAmelCase = '''<s>'''
_UpperCAmelCase = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(_UpperCamelCase ) , _UpperCamelCase )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(_UpperCamelCase ) , _UpperCamelCase )
def UpperCamelCase( self ):
_UpperCAmelCase = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , '''<unk>''' )
self.assertEqual(vocab_keys[1] , '''<s>''' )
self.assertEqual(vocab_keys[-1] , '''[MASK]''' )
self.assertEqual(len(_UpperCamelCase ) , 1004 )
def UpperCamelCase( self ):
self.assertEqual(self.get_tokenizer().vocab_size , 1000 )
def UpperCamelCase( self ):
if not self.test_rust_tokenizer:
return
_UpperCAmelCase = self.get_tokenizer()
_UpperCAmelCase = self.get_rust_tokenizer()
_UpperCAmelCase = '''I was born in 92000, and this is falsé.'''
_UpperCAmelCase = tokenizer.tokenize(_UpperCamelCase )
_UpperCAmelCase = rust_tokenizer.tokenize(_UpperCamelCase )
self.assertListEqual(_UpperCamelCase , _UpperCamelCase )
_UpperCAmelCase = tokenizer.encode(_UpperCamelCase , add_special_tokens=_UpperCamelCase )
_UpperCAmelCase = rust_tokenizer.encode(_UpperCamelCase , add_special_tokens=_UpperCamelCase )
self.assertListEqual(_UpperCamelCase , _UpperCamelCase )
_UpperCAmelCase = self.get_rust_tokenizer()
_UpperCAmelCase = tokenizer.encode(_UpperCamelCase )
_UpperCAmelCase = rust_tokenizer.encode(_UpperCamelCase )
self.assertListEqual(_UpperCamelCase , _UpperCamelCase )
def UpperCamelCase( self ):
_UpperCAmelCase = BigBirdTokenizer(_UpperCamelCase , keep_accents=_UpperCamelCase )
_UpperCAmelCase = tokenizer.tokenize('''This is a test''' )
self.assertListEqual(_UpperCamelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(_UpperCamelCase ) , [285, 46, 10, 170, 382] , )
_UpperCAmelCase = 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''',
'''é''',
'''.''',
] , )
_UpperCAmelCase = tokenizer.convert_tokens_to_ids(_UpperCamelCase )
self.assertListEqual(
_UpperCamelCase , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , )
_UpperCAmelCase = 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 UpperCamelCase( self ):
return BigBirdTokenizer.from_pretrained('''google/bigbird-roberta-base''' )
@slow
def UpperCamelCase( self ):
_UpperCAmelCase = '''Hello World!'''
_UpperCAmelCase = [65, 18536, 2260, 101, 66]
self.assertListEqual(_UpperCamelCase , self.big_tokenizer.encode(_UpperCamelCase ) )
@slow
def UpperCamelCase( self ):
_UpperCAmelCase = (
'''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will'''
''' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth'''
)
# fmt: off
_UpperCAmelCase = [65, 871, 419, 358, 946, 991, 2521, 452, 358, 1357, 387, 7751, 3536, 112, 985, 456, 126, 865, 938, 5400, 5734, 458, 1368, 467, 786, 2462, 5246, 1159, 633, 865, 4519, 457, 582, 852, 2557, 427, 916, 508, 405, 34324, 497, 391, 408, 11342, 1244, 385, 100, 938, 985, 456, 574, 362, 12597, 3200, 3129, 1172, 66] # noqa: E231
# fmt: on
self.assertListEqual(_UpperCamelCase , self.big_tokenizer.encode(_UpperCamelCase ) )
@require_torch
@slow
def UpperCamelCase( self ):
import torch
from transformers import BigBirdConfig, BigBirdModel
# Build sequence
_UpperCAmelCase = list(self.big_tokenizer.get_vocab().keys() )[:10]
_UpperCAmelCase = ''' '''.join(_UpperCamelCase )
_UpperCAmelCase = self.big_tokenizer.encode_plus(_UpperCamelCase , return_tensors='''pt''' , return_token_type_ids=_UpperCamelCase )
_UpperCAmelCase = self.big_tokenizer.batch_encode_plus(
[sequence + ''' ''' + sequence] , return_tensors='''pt''' , return_token_type_ids=_UpperCamelCase )
_UpperCAmelCase = BigBirdConfig(attention_type='''original_full''' )
_UpperCAmelCase = BigBirdModel(_UpperCamelCase )
assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size
with torch.no_grad():
model(**_UpperCamelCase )
model(**_UpperCamelCase )
@slow
def UpperCamelCase( self ):
_UpperCAmelCase = BigBirdTokenizer.from_pretrained('''google/bigbird-roberta-base''' )
_UpperCAmelCase = tokenizer.decode(tokenizer('''Paris is the [MASK].''' ).input_ids )
self.assertTrue(decoded_text == '''[CLS] Paris is the[MASK].[SEP]''' )
@slow
def UpperCamelCase( self ):
# fmt: off
_UpperCAmelCase = {'''input_ids''': [[65, 39286, 458, 36335, 2001, 456, 13073, 13266, 455, 113, 7746, 1741, 11157, 391, 13073, 13266, 455, 113, 3967, 35412, 113, 4936, 109, 3870, 2377, 113, 30084, 45720, 458, 134, 17496, 112, 503, 11672, 113, 118, 112, 5665, 13347, 38687, 112, 1496, 31389, 112, 3268, 47264, 134, 962, 112, 16377, 8035, 23130, 430, 12169, 15518, 28592, 458, 146, 41697, 109, 391, 12169, 15518, 16689, 458, 146, 41358, 109, 452, 726, 4034, 111, 763, 35412, 5082, 388, 1903, 111, 9051, 391, 2870, 48918, 1900, 1123, 550, 998, 112, 9586, 15985, 455, 391, 410, 22955, 37636, 114, 66], [65, 448, 17496, 419, 3663, 385, 763, 113, 27533, 2870, 3283, 13043, 1639, 24713, 523, 656, 24013, 18550, 2521, 517, 27014, 21244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 11786, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [65, 484, 2169, 7687, 21932, 18146, 726, 363, 17032, 3391, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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='''google/bigbird-roberta-base''' , revision='''215c99f1600e06f83acce68422f2035b2b5c3510''' , ) | 32 |
"""simple docstring"""
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 snake_case ( __UpperCAmelCase , __UpperCAmelCase ):
@register_to_config
def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ):
super().__init__()
__SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) )
__SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) )
def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ):
__SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) )
__SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) )
return self
def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ):
__SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std
return embeds
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ):
__SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean
return embeds
| 674 | 0 |
import argparse
import re
import numpy as np
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import (
SamConfig,
SamImageProcessor,
SamModel,
SamProcessor,
SamVisionConfig,
)
lowerCamelCase__ : List[Any] = {
"""iou_prediction_head.layers.0""": """iou_prediction_head.proj_in""",
"""iou_prediction_head.layers.1""": """iou_prediction_head.layers.0""",
"""iou_prediction_head.layers.2""": """iou_prediction_head.proj_out""",
"""mask_decoder.output_upscaling.0""": """mask_decoder.upscale_conv1""",
"""mask_decoder.output_upscaling.1""": """mask_decoder.upscale_layer_norm""",
"""mask_decoder.output_upscaling.3""": """mask_decoder.upscale_conv2""",
"""mask_downscaling.0""": """mask_embed.conv1""",
"""mask_downscaling.1""": """mask_embed.layer_norm1""",
"""mask_downscaling.3""": """mask_embed.conv2""",
"""mask_downscaling.4""": """mask_embed.layer_norm2""",
"""mask_downscaling.6""": """mask_embed.conv3""",
"""point_embeddings""": """point_embed""",
"""pe_layer.positional_encoding_gaussian_matrix""": """shared_embedding.positional_embedding""",
"""image_encoder""": """vision_encoder""",
"""neck.0""": """neck.conv1""",
"""neck.1""": """neck.layer_norm1""",
"""neck.2""": """neck.conv2""",
"""neck.3""": """neck.layer_norm2""",
"""patch_embed.proj""": """patch_embed.projection""",
""".norm""": """.layer_norm""",
"""blocks""": """layers""",
}
def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> List[Any]:
snake_case__ = {}
state_dict.pop('''pixel_mean''' , __lowerCAmelCase )
state_dict.pop('''pixel_std''' , __lowerCAmelCase )
snake_case__ = r'''.*.output_hypernetworks_mlps.(\d+).layers.(\d+).*'''
for key, value in state_dict.items():
for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
if key_to_modify in key:
snake_case__ = key.replace(__lowerCAmelCase , __lowerCAmelCase )
if re.match(__lowerCAmelCase , __lowerCAmelCase ):
snake_case__ = int(re.match(__lowerCAmelCase , __lowerCAmelCase ).group(2 ) )
if layer_nb == 0:
snake_case__ = key.replace('''layers.0''' , '''proj_in''' )
elif layer_nb == 1:
snake_case__ = key.replace('''layers.1''' , '''layers.0''' )
elif layer_nb == 2:
snake_case__ = key.replace('''layers.2''' , '''proj_out''' )
snake_case__ = value
snake_case__ = model_state_dict[
'''prompt_encoder.shared_embedding.positional_embedding'''
]
return model_state_dict
def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase="ybelkada/segment-anything" ) -> Tuple:
snake_case__ = hf_hub_download(__lowerCAmelCase , F"""checkpoints/{model_name}.pth""" )
if "sam_vit_b" in model_name:
snake_case__ = SamConfig()
elif "sam_vit_l" in model_name:
snake_case__ = SamVisionConfig(
hidden_size=1024 , num_hidden_layers=24 , num_attention_heads=16 , global_attn_indexes=[5, 11, 17, 23] , )
snake_case__ = SamConfig(
vision_config=__lowerCAmelCase , )
elif "sam_vit_h" in model_name:
snake_case__ = SamVisionConfig(
hidden_size=1280 , num_hidden_layers=32 , num_attention_heads=16 , global_attn_indexes=[7, 15, 23, 31] , )
snake_case__ = SamConfig(
vision_config=__lowerCAmelCase , )
snake_case__ = torch.load(__lowerCAmelCase , map_location='''cpu''' )
snake_case__ = replace_keys(__lowerCAmelCase )
snake_case__ = SamImageProcessor()
snake_case__ = SamProcessor(image_processor=__lowerCAmelCase )
snake_case__ = SamModel(__lowerCAmelCase )
hf_model.load_state_dict(__lowerCAmelCase )
snake_case__ = hf_model.to('''cuda''' )
snake_case__ = '''https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png'''
snake_case__ = Image.open(requests.get(__lowerCAmelCase , stream=__lowerCAmelCase ).raw ).convert('''RGB''' )
snake_case__ = [[[400, 650]]]
snake_case__ = [[1]]
snake_case__ = processor(images=np.array(__lowerCAmelCase ) , return_tensors='''pt''' ).to('''cuda''' )
with torch.no_grad():
snake_case__ = hf_model(**__lowerCAmelCase )
snake_case__ = output.iou_scores.squeeze()
if model_name == "sam_vit_h_4b8939":
assert scores[-1].item() == 0.579_8902_5115_9668
snake_case__ = processor(
images=np.array(__lowerCAmelCase ) , input_points=__lowerCAmelCase , input_labels=__lowerCAmelCase , return_tensors='''pt''' ).to('''cuda''' )
with torch.no_grad():
snake_case__ = hf_model(**__lowerCAmelCase )
snake_case__ = output.iou_scores.squeeze()
assert scores[-1].item() == 0.9712_6030_9219_3604
snake_case__ = ((75, 275, 1725, 850),)
snake_case__ = processor(images=np.array(__lowerCAmelCase ) , input_boxes=__lowerCAmelCase , return_tensors='''pt''' ).to('''cuda''' )
with torch.no_grad():
snake_case__ = hf_model(**__lowerCAmelCase )
snake_case__ = output.iou_scores.squeeze()
assert scores[-1].item() == 0.8686_0156_0592_6514
# Test with 2 points and 1 image.
snake_case__ = [[[400, 650], [800, 650]]]
snake_case__ = [[1, 1]]
snake_case__ = processor(
images=np.array(__lowerCAmelCase ) , input_points=__lowerCAmelCase , input_labels=__lowerCAmelCase , return_tensors='''pt''' ).to('''cuda''' )
with torch.no_grad():
snake_case__ = hf_model(**__lowerCAmelCase )
snake_case__ = output.iou_scores.squeeze()
assert scores[-1].item() == 0.9936_0477_9243_4692
if __name__ == "__main__":
lowerCamelCase__ : Tuple = argparse.ArgumentParser()
lowerCamelCase__ : int = ["""sam_vit_b_01ec64""", """sam_vit_h_4b8939""", """sam_vit_l_0b3195"""]
parser.add_argument(
"""--model_name""",
default="""sam_vit_h_4b8939""",
choices=choices,
type=str,
help="""Path to hf config.json of model to convert""",
)
parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
parser.add_argument(
"""--push_to_hub""",
action="""store_true""",
help="""Whether to push the model and processor to the hub after converting""",
)
parser.add_argument(
"""--model_hub_id""",
default="""ybelkada/segment-anything""",
choices=choices,
type=str,
help="""Path to hf config.json of model to convert""",
)
lowerCamelCase__ : Union[str, Any] = parser.parse_args()
convert_sam_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub, args.model_hub_id)
| 33 |
"""simple docstring"""
import argparse
import torch
from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert
from transformers.utils import logging
logging.set_verbosity_info()
def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ )
print(F'''Building PyTorch model from configuration: {config}''' )
__SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ )
# Load weights from tf checkpoint
load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ )
# Save pytorch-model
print(F'''Save PyTorch model to {pytorch_dump_path}''' )
torch.save(model.state_dict() , lowercase_ )
if __name__ == "__main__":
_lowerCamelCase = 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(
'''--bert_config_file''',
default=None,
type=str,
required=True,
help=(
'''The config json file corresponding to the pre-trained BERT model. \n'''
'''This specifies the model architecture.'''
),
)
parser.add_argument(
'''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
)
_lowerCamelCase = parser.parse_args()
convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
| 674 | 0 |
"""simple docstring"""
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE_ = {
'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json',
'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json',
'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json',
'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json',
'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json',
'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json',
'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json',
'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json',
'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json',
}
class snake_case_ ( lowerCamelCase_ ):
"""simple docstring"""
A_ = '''xmod'''
def __init__( self , lowerCamelCase_=3_0_5_2_2 , lowerCamelCase_=7_6_8 , lowerCamelCase_=1_2 , lowerCamelCase_=1_2 , lowerCamelCase_=3_0_7_2 , lowerCamelCase_="gelu" , lowerCamelCase_=0.1 , lowerCamelCase_=0.1 , lowerCamelCase_=5_1_2 , lowerCamelCase_=2 , lowerCamelCase_=0.02 , lowerCamelCase_=1e-12 , lowerCamelCase_=1 , lowerCamelCase_=0 , lowerCamelCase_=2 , lowerCamelCase_="absolute" , lowerCamelCase_=True , lowerCamelCase_=None , lowerCamelCase_=False , lowerCamelCase_=2 , lowerCamelCase_=False , lowerCamelCase_=True , lowerCamelCase_=True , lowerCamelCase_=("en_XX",) , lowerCamelCase_=None , **lowerCamelCase_ , ) -> Dict:
super().__init__(pad_token_id=lowerCamelCase_ , bos_token_id=lowerCamelCase_ , eos_token_id=lowerCamelCase_ , **lowerCamelCase_)
UpperCamelCase = vocab_size
UpperCamelCase = hidden_size
UpperCamelCase = num_hidden_layers
UpperCamelCase = num_attention_heads
UpperCamelCase = hidden_act
UpperCamelCase = intermediate_size
UpperCamelCase = hidden_dropout_prob
UpperCamelCase = attention_probs_dropout_prob
UpperCamelCase = max_position_embeddings
UpperCamelCase = type_vocab_size
UpperCamelCase = initializer_range
UpperCamelCase = layer_norm_eps
UpperCamelCase = position_embedding_type
UpperCamelCase = use_cache
UpperCamelCase = classifier_dropout
UpperCamelCase = pre_norm
UpperCamelCase = adapter_reduction_factor
UpperCamelCase = adapter_layer_norm
UpperCamelCase = adapter_reuse_layer_norm
UpperCamelCase = ln_before_adapter
UpperCamelCase = list(lowerCamelCase_)
UpperCamelCase = default_language
class snake_case_ ( lowerCamelCase_ ):
"""simple docstring"""
@property
def UpperCAmelCase__ ( self) -> Mapping[str, Mapping[int, str]]:
if self.task == "multiple-choice":
UpperCamelCase = {0: '''batch''', 1: '''choice''', 2: '''sequence'''}
else:
UpperCamelCase = {0: '''batch''', 1: '''sequence'''}
return OrderedDict(
[
('''input_ids''', dynamic_axis),
('''attention_mask''', dynamic_axis),
]) | 34 |
"""simple docstring"""
# 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 numpy as np
import torch
from ..models.clipseg import CLIPSegForImageSegmentation
from ..utils import is_vision_available, requires_backends
from .base import PipelineTool
if is_vision_available():
from PIL import Image
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = (
'''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.'''
'''It takes two arguments named `image` which should be the original image, and `label` which should be a text '''
'''describing the elements what should be identified in the segmentation mask. The tool returns the mask.'''
)
lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined'''
lowerCamelCase__ = '''image_segmenter'''
lowerCamelCase__ = CLIPSegForImageSegmentation
lowerCamelCase__ = ['''image''', '''text''']
lowerCamelCase__ = ['''image''']
def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ):
requires_backends(self , ['''vision'''] )
super().__init__(*_lowerCamelCase , **_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ):
return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ):
with torch.no_grad():
__SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits
return logits
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ):
__SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy()
__SCREAMING_SNAKE_CASE : str = 0
__SCREAMING_SNAKE_CASE : str = 1
return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
| 674 | 0 |
import argparse
import os
import re
import packaging.version
a_ :int = 'examples/'
a_ :Dict = {
'examples': (re.compile(r'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")\n'),
'init': (re.compile(r'^__version__\s+=\s+"([^"]+)"\s*$', re.MULTILINE), '__version__ = "VERSION"\n'),
'setup': (re.compile(r'^(\s*)version\s*=\s*"[^"]+",', re.MULTILINE), r'\1version="VERSION",'),
'doc': (re.compile(r'^(\s*)release\s*=\s*"[^"]+"$', re.MULTILINE), 'release = "VERSION"\n'),
}
a_ :Union[str, Any] = {
'init': 'src/transformers/__init__.py',
'setup': 'setup.py',
}
a_ :List[str] = 'README.md'
def a ( A__ , A__ , A__ ) -> Dict:
'''simple docstring'''
with open(A__ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f:
SCREAMING_SNAKE_CASE__ : Any = f.read()
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = REPLACE_PATTERNS[pattern]
SCREAMING_SNAKE_CASE__ : Tuple = replace.replace('''VERSION''' , A__ )
SCREAMING_SNAKE_CASE__ : int = re_pattern.sub(A__ , A__ )
with open(A__ , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f:
f.write(A__ )
def a ( A__ ) -> List[Any]:
'''simple docstring'''
for folder, directories, fnames in os.walk(A__ ):
# Removing some of the folders with non-actively maintained examples from the walk
if "research_projects" in directories:
directories.remove('''research_projects''' )
if "legacy" in directories:
directories.remove('''legacy''' )
for fname in fnames:
if fname.endswith('''.py''' ):
update_version_in_file(os.path.join(A__ , A__ ) , A__ , pattern='''examples''' )
def a ( A__ , A__=False ) -> Union[str, Any]:
'''simple docstring'''
for pattern, fname in REPLACE_FILES.items():
update_version_in_file(A__ , A__ , A__ )
if not patch:
update_version_in_examples(A__ )
def a ( ) -> Optional[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : List[str] = '''🤗 Transformers currently provides the following architectures'''
SCREAMING_SNAKE_CASE__ : Optional[int] = '''1. Want to contribute a new model?'''
with open(A__ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f:
SCREAMING_SNAKE_CASE__ : str = f.readlines()
# Find the start of the list.
SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0
while not lines[start_index].startswith(_start_prompt ):
start_index += 1
start_index += 1
SCREAMING_SNAKE_CASE__ : List[Any] = start_index
# Update the lines in the model list.
while not lines[index].startswith(_end_prompt ):
if lines[index].startswith('''1.''' ):
SCREAMING_SNAKE_CASE__ : Any = lines[index].replace(
'''https://huggingface.co/docs/transformers/main/model_doc''' , '''https://huggingface.co/docs/transformers/model_doc''' , )
index += 1
with open(A__ , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f:
f.writelines(A__ )
def a ( ) -> Dict:
'''simple docstring'''
with open(REPLACE_FILES['''init'''] , '''r''' ) as f:
SCREAMING_SNAKE_CASE__ : Tuple = f.read()
SCREAMING_SNAKE_CASE__ : int = REPLACE_PATTERNS['''init'''][0].search(A__ ).groups()[0]
return packaging.version.parse(A__ )
def a ( A__=False ) -> Any:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Any = get_version()
if patch and default_version.is_devrelease:
raise ValueError('''Can\'t create a patch version from the dev branch, checkout a released version!''' )
if default_version.is_devrelease:
SCREAMING_SNAKE_CASE__ : Dict = default_version.base_version
elif patch:
SCREAMING_SNAKE_CASE__ : int = f"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}"""
else:
SCREAMING_SNAKE_CASE__ : List[str] = f"""{default_version.major}.{default_version.minor + 1}.0"""
# Now let's ask nicely if that's the right one.
SCREAMING_SNAKE_CASE__ : Union[str, Any] = input(f"""Which version are you releasing? [{default_version}]""" )
if len(A__ ) == 0:
SCREAMING_SNAKE_CASE__ : Union[str, Any] = default_version
print(f"""Updating version to {version}.""" )
global_version_update(A__ , patch=A__ )
if not patch:
print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' )
clean_main_ref_in_model_list()
def a ( ) -> str:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Dict = get_version()
SCREAMING_SNAKE_CASE__ : List[str] = f"""{current_version.major}.{current_version.minor + 1}.0.dev0"""
SCREAMING_SNAKE_CASE__ : List[Any] = current_version.base_version
# Check with the user we got that right.
SCREAMING_SNAKE_CASE__ : Any = input(f"""Which version are we developing now? [{dev_version}]""" )
if len(A__ ) == 0:
SCREAMING_SNAKE_CASE__ : List[str] = dev_version
print(f"""Updating version to {version}.""" )
global_version_update(A__ )
print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' )
clean_main_ref_in_model_list()
if __name__ == "__main__":
a_ :Optional[Any] = argparse.ArgumentParser()
parser.add_argument('--post_release', action='store_true', help='Whether this is pre or post release.')
parser.add_argument('--patch', action='store_true', help='Whether or not this is a patch release.')
a_ :int = parser.parse_args()
if not args.post_release:
pre_release_work(patch=args.patch)
elif args.patch:
print('Nothing to do after a patch :-)')
else:
post_release_work()
| 35 |
"""simple docstring"""
import json
import os
import shutil
import tempfile
import unittest
import numpy as np
from transformers import BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer
from transformers.testing_utils import require_tokenizers, require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available
if is_vision_available():
from PIL import Image
from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor
@require_tokenizers
@require_vision
class snake_case ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp()
# fmt: off
__SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''']
# fmt: on
__SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer:
vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) )
__SCREAMING_SNAKE_CASE : Optional[int] = {
'''do_resize''': True,
'''size''': {'''height''': 1_8, '''width''': 1_8},
'''do_normalize''': True,
'''image_mean''': [0.5, 0.5, 0.5],
'''image_std''': [0.5, 0.5, 0.5],
}
__SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase )
with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp:
json.dump(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ):
return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ):
return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
shutil.rmtree(self.tmpdirname )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )]
__SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def SCREAMING_SNAKE_CASE_ ( self :int ):
__SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor()
__SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
processor.save_pretrained(self.tmpdirname )
__SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() )
self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) )
self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() )
self.assertIsInstance(processor.image_processor , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
__SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor(
tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
__SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' )
__SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 )
__SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(
self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :int ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor()
__SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs()
__SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' )
__SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''np''' )
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
__SCREAMING_SNAKE_CASE : Any = self.get_image_processor()
__SCREAMING_SNAKE_CASE : Any = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer'''
__SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE : str = self.get_image_processor()
__SCREAMING_SNAKE_CASE : int = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = '''lower newer'''
__SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs()
__SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase )
self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] )
# test if it raises when no input is passed
with self.assertRaises(_lowerCamelCase ):
processor()
def SCREAMING_SNAKE_CASE_ ( self :Any ):
__SCREAMING_SNAKE_CASE : Dict = self.get_image_processor()
__SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
__SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase )
self.assertListEqual(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
__SCREAMING_SNAKE_CASE : str = self.get_image_processor()
__SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = '''lower newer'''
__SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs()
__SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase )
self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
| 674 | 0 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
__lowercase : Any = {
'''configuration_roformer''': ['''ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RoFormerConfig''', '''RoFormerOnnxConfig'''],
'''tokenization_roformer''': ['''RoFormerTokenizer'''],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowercase : Optional[Any] = ['''RoFormerTokenizerFast''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowercase : Optional[Any] = [
'''ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''RoFormerForCausalLM''',
'''RoFormerForMaskedLM''',
'''RoFormerForMultipleChoice''',
'''RoFormerForQuestionAnswering''',
'''RoFormerForSequenceClassification''',
'''RoFormerForTokenClassification''',
'''RoFormerLayer''',
'''RoFormerModel''',
'''RoFormerPreTrainedModel''',
'''load_tf_weights_in_roformer''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowercase : int = [
'''TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TFRoFormerForCausalLM''',
'''TFRoFormerForMaskedLM''',
'''TFRoFormerForMultipleChoice''',
'''TFRoFormerForQuestionAnswering''',
'''TFRoFormerForSequenceClassification''',
'''TFRoFormerForTokenClassification''',
'''TFRoFormerLayer''',
'''TFRoFormerModel''',
'''TFRoFormerPreTrainedModel''',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowercase : List[str] = [
'''FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''FlaxRoFormerForMaskedLM''',
'''FlaxRoFormerForMultipleChoice''',
'''FlaxRoFormerForQuestionAnswering''',
'''FlaxRoFormerForSequenceClassification''',
'''FlaxRoFormerForTokenClassification''',
'''FlaxRoFormerModel''',
'''FlaxRoFormerPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig
from .tokenization_roformer import RoFormerTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_roformer_fast import RoFormerTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_roformer import (
ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
RoFormerForCausalLM,
RoFormerForMaskedLM,
RoFormerForMultipleChoice,
RoFormerForQuestionAnswering,
RoFormerForSequenceClassification,
RoFormerForTokenClassification,
RoFormerLayer,
RoFormerModel,
RoFormerPreTrainedModel,
load_tf_weights_in_roformer,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_roformer import (
TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TFRoFormerForCausalLM,
TFRoFormerForMaskedLM,
TFRoFormerForMultipleChoice,
TFRoFormerForQuestionAnswering,
TFRoFormerForSequenceClassification,
TFRoFormerForTokenClassification,
TFRoFormerLayer,
TFRoFormerModel,
TFRoFormerPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_roformer import (
FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
FlaxRoFormerForMaskedLM,
FlaxRoFormerForMultipleChoice,
FlaxRoFormerForQuestionAnswering,
FlaxRoFormerForSequenceClassification,
FlaxRoFormerForTokenClassification,
FlaxRoFormerModel,
FlaxRoFormerPreTrainedModel,
)
else:
import sys
__lowercase : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 36 |
"""simple docstring"""
import inspect
import unittest
import numpy as np
from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel
if is_vision_available():
from transformers import MaskFormerImageProcessor
if is_vision_available():
from PIL import Image
class snake_case :
def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ):
__SCREAMING_SNAKE_CASE : List[str] = parent
__SCREAMING_SNAKE_CASE : Tuple = batch_size
__SCREAMING_SNAKE_CASE : Optional[Any] = is_training
__SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss
__SCREAMING_SNAKE_CASE : List[str] = num_queries
__SCREAMING_SNAKE_CASE : Optional[int] = num_channels
__SCREAMING_SNAKE_CASE : List[Any] = min_size
__SCREAMING_SNAKE_CASE : int = max_size
__SCREAMING_SNAKE_CASE : Any = num_labels
__SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size
def SCREAMING_SNAKE_CASE_ ( self :Any ):
__SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to(
_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = (
torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5
).float()
__SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long()
__SCREAMING_SNAKE_CASE : str = self.get_config()
return config, pixel_values, pixel_mask, mask_labels, class_labels
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
return MaskFormerConfig.from_backbone_and_decoder_configs(
backbone_config=SwinConfig(
depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig(
decoder_ffn_dim=1_2_8 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , )
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs()
__SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
return config, inputs_dict
def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states
__SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states
__SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states
self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers )
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ):
with torch.no_grad():
__SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
__SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase )
# the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
# encoder and pixel decoder
self.parent.assertEqual(
output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , )
# let's ensure the other two hidden state exists
self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(output.encoder_last_hidden_state is not None )
if output_hidden_states:
self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ):
__SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
def comm_check_on_output(_lowerCamelCase :Optional[Any] ):
# let's still check that all the required stuff is there
self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.encoder_last_hidden_state is not None )
# okay, now we need to check the logits shape
# due to the encoder compression, masks have a //4 spatial size
self.parent.assertEqual(
result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , )
# + 1 for null class
self.parent.assertEqual(
result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) )
with torch.no_grad():
__SCREAMING_SNAKE_CASE : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase )
comm_check_on_output(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Dict = model(
pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase )
comm_check_on_output(_lowerCamelCase )
self.parent.assertTrue(result.loss is not None )
self.parent.assertEqual(result.loss.shape , torch.Size([1] ) )
@require_torch
class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ):
lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
lowerCamelCase__ = (
{'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation}
if is_torch_available()
else {}
)
lowerCamelCase__ = False
lowerCamelCase__ = False
lowerCamelCase__ = False
lowerCamelCase__ = False
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
__SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self )
__SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
self.config_tester.run_common_tests()
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
__SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase )
@unittest.skip(reason='''MaskFormer does not use inputs_embeds''' )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
pass
@unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' )
def SCREAMING_SNAKE_CASE_ ( self :int ):
pass
@unittest.skip(reason='''MaskFormer is not a generative model''' )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
pass
@unittest.skip(reason='''MaskFormer does not use token embeddings''' )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
pass
@require_torch_multi_gpu
@unittest.skip(
reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
pass
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
pass
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__SCREAMING_SNAKE_CASE : Tuple = model_class(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()]
__SCREAMING_SNAKE_CASE : Optional[Any] = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
for model_name in ["facebook/maskformer-swin-small-coco"]:
__SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2
__SCREAMING_SNAKE_CASE : Dict = {
'''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ),
'''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ),
'''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(),
}
__SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase )
self.assertTrue(outputs.loss is not None )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__SCREAMING_SNAKE_CASE : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase )
self.assertTrue(outputs.attentions is not None )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
if not self.model_tester.is_training:
return
# only MaskFormerForInstanceSegmentation has the loss
__SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1]
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs()
__SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase )
model.to(_lowerCamelCase )
model.train()
__SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss
loss.backward()
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# only MaskFormerForInstanceSegmentation has the loss
__SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1]
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs()
__SCREAMING_SNAKE_CASE : Tuple = True
__SCREAMING_SNAKE_CASE : List[str] = True
__SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase )
model.to(_lowerCamelCase )
model.train()
__SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = outputs.encoder_hidden_states[0]
encoder_hidden_states.retain_grad()
__SCREAMING_SNAKE_CASE : str = outputs.pixel_decoder_hidden_states[0]
pixel_decoder_hidden_states.retain_grad()
# we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
__SCREAMING_SNAKE_CASE : Optional[int] = outputs.transformer_decoder_hidden_states[0]
transformer_decoder_hidden_states.retain_grad()
__SCREAMING_SNAKE_CASE : int = outputs.attentions[0]
attentions.retain_grad()
outputs.loss.backward(retain_graph=_lowerCamelCase )
self.assertIsNotNone(encoder_hidden_states.grad )
self.assertIsNotNone(pixel_decoder_hidden_states.grad )
self.assertIsNotNone(transformer_decoder_hidden_states.grad )
self.assertIsNotNone(attentions.grad )
_lowerCamelCase = 1e-4
def lowerCAmelCase_ ( ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_vision
@slow
class snake_case ( unittest.TestCase ):
@cached_property
def SCREAMING_SNAKE_CASE_ ( self :str ):
return (
MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' )
if is_vision_available()
else None
)
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = self.default_image_processor
__SCREAMING_SNAKE_CASE : Tuple = prepare_img()
__SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 )
# check size
self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) )
with torch.no_grad():
__SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor(
[[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase )
self.assertTrue(
torch.allclose(
outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
__SCREAMING_SNAKE_CASE : Any = torch.tensor(
[[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase )
self.assertTrue(
torch.allclose(
outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
__SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(
[[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase )
self.assertTrue(
torch.allclose(
outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
__SCREAMING_SNAKE_CASE : Tuple = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
.to(_lowerCamelCase )
.eval()
)
__SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor
__SCREAMING_SNAKE_CASE : Tuple = prepare_img()
__SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 )
# check size
self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) )
with torch.no_grad():
__SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase )
# masks_queries_logits
__SCREAMING_SNAKE_CASE : Any = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
__SCREAMING_SNAKE_CASE : List[Any] = [
[-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3],
[-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5],
[-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2],
]
__SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
# class_queries_logits
__SCREAMING_SNAKE_CASE : List[Any] = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
__SCREAMING_SNAKE_CASE : List[str] = torch.tensor(
[
[1.65_12e00, -5.25_72e00, -3.35_19e00],
[3.61_69e-02, -5.90_25e00, -2.93_13e00],
[1.07_66e-04, -7.76_30e00, -5.12_63e00],
] ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
def SCREAMING_SNAKE_CASE_ ( self :Any ):
__SCREAMING_SNAKE_CASE : Tuple = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' )
.to(_lowerCamelCase )
.eval()
)
__SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor
__SCREAMING_SNAKE_CASE : str = prepare_img()
__SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 )
# check size
self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) )
with torch.no_grad():
__SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase )
# masks_queries_logits
__SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
__SCREAMING_SNAKE_CASE : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]]
__SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
# class_queries_logits
__SCREAMING_SNAKE_CASE : int = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
__SCREAMING_SNAKE_CASE : List[str] = torch.tensor(
[[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
def SCREAMING_SNAKE_CASE_ ( self :int ):
__SCREAMING_SNAKE_CASE : int = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
.to(_lowerCamelCase )
.eval()
)
__SCREAMING_SNAKE_CASE : Any = self.default_image_processor
__SCREAMING_SNAKE_CASE : int = image_processor(
[np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , )
__SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']]
__SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']]
with torch.no_grad():
__SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase )
self.assertTrue(outputs.loss is not None )
| 674 | 0 |
import unittest
from transformers import is_tf_available
from transformers.testing_utils import require_tf
if is_tf_available():
import tensorflow as tf
from tensorflow.python.eager import context
from tensorflow.python.framework import ops
from transformers import GradientAccumulator, create_optimizer
@require_tf
class A__ ( unittest.TestCase ):
"""simple docstring"""
def _UpperCamelCase( self : Optional[Any] , lowerCamelCase__ : List[str] , lowerCamelCase__ : List[str] , lowerCamelCase__ : List[Any] ):
self.assertEqual(len(lowerCamelCase__ ) , len(lowerCamelCase__ ) )
for a, b in zip(lowerCamelCase__ , lowerCamelCase__ ):
self.assertAlmostEqual(lowerCamelCase__ , lowerCamelCase__ , delta=lowerCamelCase__ )
def _UpperCamelCase( self : Union[str, Any] ):
a__ : List[str] = GradientAccumulator()
accumulator([tf.constant([1.0, 2.0] )] )
accumulator([tf.constant([-2.0, 1.0] )] )
accumulator([tf.constant([-1.0, 2.0] )] )
with self.assertRaises(lowerCamelCase__ ):
accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] )
self.assertEqual(accumulator.step , 3 )
self.assertEqual(len(accumulator.gradients ) , 1 )
self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1E-2 )
accumulator.reset()
self.assertEqual(accumulator.step , 0 )
self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1E-2 )
def _UpperCamelCase( self : List[Any] ):
a__ : Tuple = None
ops.enable_eager_execution_internal()
a__ : Dict = tf.config.list_physical_devices("CPU" )
if len(lowerCamelCase__ ) == 1:
tf.config.set_logical_device_configuration(
physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] )
a__ : Optional[int] = tf.config.list_logical_devices(device_type="CPU" )
a__ : Tuple = tf.distribute.MirroredStrategy(devices=devices[:2] )
with strategy.scope():
a__ : List[Any] = GradientAccumulator()
a__ : str = tf.Variable([4.0, 3.0] )
a__, a__ : Union[str, Any] = create_optimizer(5E-5 , 10 , 5 )
a__ : Optional[int] = tf.Variable([0.0, 0.0] , trainable=lowerCamelCase__ )
def accumulate_on_replica(lowerCamelCase__ : Any ):
accumulator([gradient] )
def apply_on_replica():
optimizer.apply_gradients(list(zip(accumulator.gradients , [variable] ) ) )
@tf.function
def accumulate(lowerCamelCase__ : Any , lowerCamelCase__ : Optional[Any] ):
with strategy.scope():
a__ : Tuple = strategy.experimental_local_results(lowerCamelCase__ )
local_variables[0].assign(lowerCamelCase__ )
local_variables[1].assign(lowerCamelCase__ )
strategy.run(lowerCamelCase__ , args=(gradient_placeholder,) )
@tf.function
def apply_grad():
with strategy.scope():
strategy.run(lowerCamelCase__ )
def _check_local_values(lowerCamelCase__ : Tuple , lowerCamelCase__ : Optional[int] ):
a__ : Optional[int] = strategy.experimental_local_results(accumulator._gradients[0] )
self.assertListAlmostEqual(values[0].value() , lowerCamelCase__ , tol=1E-2 )
self.assertListAlmostEqual(values[1].value() , lowerCamelCase__ , tol=1E-2 )
accumulate([1.0, 2.0] , [-1.0, 1.0] )
accumulate([3.0, -1.0] , [-1.0, -1.0] )
accumulate([-2.0, 2.0] , [3.0, -2.0] )
self.assertEqual(accumulator.step , 3 )
_check_local_values([2.0, 3.0] , [1.0, -2.0] )
apply_grad()
self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1E-2 )
accumulator.reset()
self.assertEqual(accumulator.step , 0 )
_check_local_values([0.0, 0.0] , [0.0, 0.0] )
| 37 |
"""simple docstring"""
import contextlib
import importlib
import io
import unittest
import transformers
# Try to import everything from transformers to ensure every object can be loaded.
from transformers import * # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available
if is_torch_available():
from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification
if is_tf_available():
from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification
if is_flax_available():
from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification
_lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co
_lowerCamelCase = '''main'''
# Default branch name
_lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'''
# One particular commit (not the top of `main`)
_lowerCamelCase = '''aaaaaaa'''
# This commit does not exist, so we should 404.
_lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684'''
# Sha-1 of config.json on the top of `main`, for checking purposes
_lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'''
@contextlib.contextmanager
def lowerCAmelCase_ ( ):
'''simple docstring'''
print('''Welcome!''' )
yield
print('''Bye!''' )
@contextlib.contextmanager
def lowerCAmelCase_ ( ):
'''simple docstring'''
print('''Bonjour!''' )
yield
print('''Au revoir!''' )
class snake_case ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
# If the spec is missing, importlib would not be able to import the module dynamically.
assert transformers.__spec__ is not None
assert importlib.util.find_spec('''transformers''' ) is not None
class snake_case ( unittest.TestCase ):
@unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO )
def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ):
with ContextManagers([] ):
print('''Transformers are awesome!''' )
# The print statement adds a new line at the end of the output
self.assertEqual(mock_stdout.getvalue() , '''Transformers are awesome!\n''' )
@unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO )
def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ):
with ContextManagers([context_en()] ):
print('''Transformers are awesome!''' )
# The output should be wrapped with an English welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , '''Welcome!\nTransformers are awesome!\nBye!\n''' )
@unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO )
def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ):
with ContextManagers([context_fr(), context_en()] ):
print('''Transformers are awesome!''' )
# The output should be wrapped with an English and French welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , '''Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n''' )
@require_torch
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] )
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] )
self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] )
class snake_case ( __UpperCAmelCase ):
pass
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] )
@require_tf
def SCREAMING_SNAKE_CASE_ ( self :int ):
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] )
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] )
self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] )
class snake_case ( __UpperCAmelCase ):
pass
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] )
@require_flax
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
# Flax models don't have labels
self.assertEqual(find_labels(_lowerCamelCase ) , [] )
self.assertEqual(find_labels(_lowerCamelCase ) , [] )
self.assertEqual(find_labels(_lowerCamelCase ) , [] )
class snake_case ( __UpperCAmelCase ):
pass
self.assertEqual(find_labels(_lowerCamelCase ) , [] )
| 674 | 0 |
'''simple docstring'''
import math
def UpperCamelCase__ ( __magic_name__ : float , __magic_name__ : float ) -> float:
'''simple docstring'''
return math.pow(__magic_name__ , 2 ) - a
def UpperCamelCase__ ( __magic_name__ : float ) -> float:
'''simple docstring'''
return 2 * x
def UpperCamelCase__ ( __magic_name__ : float ) -> float:
'''simple docstring'''
snake_case__ : Optional[int] = 2.0
while start <= a:
snake_case__ : Any = math.pow(__magic_name__ , 2 )
return start
def UpperCamelCase__ ( __magic_name__ : float , __magic_name__ : int = 99_99 , __magic_name__ : float = 0.00_0000_0000_0001 ) -> float:
'''simple docstring'''
if a < 0:
raise ValueError("""math domain error""" )
snake_case__ : Tuple = get_initial_point(__magic_name__ )
for _ in range(__magic_name__ ):
snake_case__ : Union[str, Any] = value
snake_case__ : int = value - fx(__magic_name__ , __magic_name__ ) / fx_derivative(__magic_name__ )
if abs(prev_value - value ) < tolerance:
return value
return value
if __name__ == "__main__":
from doctest import testmod
testmod()
| 38 |
"""simple docstring"""
import json
import pathlib
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import YolosImageProcessor
class snake_case ( unittest.TestCase ):
def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ):
# by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
__SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3}
__SCREAMING_SNAKE_CASE : List[str] = parent
__SCREAMING_SNAKE_CASE : Dict = batch_size
__SCREAMING_SNAKE_CASE : str = num_channels
__SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution
__SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution
__SCREAMING_SNAKE_CASE : Tuple = do_resize
__SCREAMING_SNAKE_CASE : Union[str, Any] = size
__SCREAMING_SNAKE_CASE : int = do_normalize
__SCREAMING_SNAKE_CASE : List[Any] = image_mean
__SCREAMING_SNAKE_CASE : Tuple = image_std
__SCREAMING_SNAKE_CASE : Dict = do_rescale
__SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor
__SCREAMING_SNAKE_CASE : List[Any] = do_pad
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
return {
"do_resize": self.do_resize,
"size": self.size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_rescale": self.do_rescale,
"rescale_factor": self.rescale_factor,
"do_pad": self.do_pad,
}
def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ):
if not batched:
__SCREAMING_SNAKE_CASE : str = image_inputs[0]
if isinstance(_lowerCamelCase , Image.Image ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size
else:
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2]
if w < h:
__SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w )
__SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge''']
elif w > h:
__SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge''']
__SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h )
else:
__SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge''']
__SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge''']
else:
__SCREAMING_SNAKE_CASE : Optional[Any] = []
for image in image_inputs:
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] )
expected_values.append((expected_height, expected_width) )
__SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0]
__SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1]
return expected_height, expected_width
@require_torch
@require_vision
class snake_case ( __UpperCAmelCase , unittest.TestCase ):
lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
__SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self )
@property
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
return self.image_processor_tester.prepare_image_processor_dict()
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
__SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) )
self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) )
self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) )
self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) )
self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} )
self.assertEqual(image_processor.do_pad , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict(
self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase )
self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} )
self.assertEqual(image_processor.do_pad , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
pass
def SCREAMING_SNAKE_CASE_ ( self :int ):
# Initialize image_processing
__SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
__SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , Image.Image )
# Test not batched input
__SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# Initialize image_processing
__SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
__SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , np.ndarray )
# Test not batched input
__SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def SCREAMING_SNAKE_CASE_ ( self :Any ):
# Initialize image_processing
__SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
__SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , torch.Tensor )
# Test not batched input
__SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
# Initialize image_processings
__SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict )
__SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase )
# create random PyTorch tensors
__SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , torch.Tensor )
# Test whether the method "pad" and calling the image processor return the same tensors
__SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' )
__SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' )
self.assertTrue(
torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) )
@slow
def SCREAMING_SNAKE_CASE_ ( self :int ):
# prepare image and target
__SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f:
__SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() )
__SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target}
# encode them
__SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' )
__SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' )
# verify pixel values
__SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] )
self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] )
self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) )
# verify area
__SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) )
# verify boxes
__SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] )
self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) )
# verify image_id
__SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) )
# verify is_crowd
__SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) )
# verify class_labels
__SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) )
# verify orig_size
__SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) )
# verify size
__SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# prepare image, target and masks_path
__SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f:
__SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() )
__SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target}
__SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' )
# encode them
__SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' )
__SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' )
# verify pixel values
__SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] )
self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] )
self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) )
# verify area
__SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) )
# verify boxes
__SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] )
self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) )
# verify image_id
__SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) )
# verify is_crowd
__SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) )
# verify class_labels
__SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) )
# verify masks
__SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3
self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase )
# verify orig_size
__SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) )
# verify size
__SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
| 674 | 0 |
import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import cached_download, hf_hub_download, hf_hub_url
from PIL import Image
from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinConfig
from transformers.utils import logging
logging.set_verbosity_info()
lowerCAmelCase_ = logging.get_logger(__name__)
def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ):
snake_case_ = SwinConfig(
embed_dim=192 , depths=(2, 2, 18, 2) , num_heads=(6, 12, 24, 48) , window_size=12 , out_features=['''stage2''', '''stage3''', '''stage4'''] , )
snake_case_ = DetaConfig(
backbone_config=SCREAMING_SNAKE_CASE__ , num_queries=900 , encoder_ffn_dim=2048 , decoder_ffn_dim=2048 , num_feature_levels=5 , assign_first_stage=SCREAMING_SNAKE_CASE__ , with_box_refine=SCREAMING_SNAKE_CASE__ , two_stage=SCREAMING_SNAKE_CASE__ , )
# set labels
snake_case_ = '''huggingface/label-files'''
if "o365" in model_name:
snake_case_ = 366
snake_case_ = '''object365-id2label.json'''
else:
snake_case_ = 91
snake_case_ = '''coco-detection-id2label.json'''
snake_case_ = num_labels
snake_case_ = json.load(open(cached_download(hf_hub_url(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) ) , '''r''' ) )
snake_case_ = {int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()}
snake_case_ = idalabel
snake_case_ = {v: k for k, v in idalabel.items()}
return config
def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ):
snake_case_ = []
# stem
# fmt: off
rename_keys.append(('''backbone.0.body.patch_embed.proj.weight''', '''model.backbone.model.embeddings.patch_embeddings.projection.weight''') )
rename_keys.append(('''backbone.0.body.patch_embed.proj.bias''', '''model.backbone.model.embeddings.patch_embeddings.projection.bias''') )
rename_keys.append(('''backbone.0.body.patch_embed.norm.weight''', '''model.backbone.model.embeddings.norm.weight''') )
rename_keys.append(('''backbone.0.body.patch_embed.norm.bias''', '''model.backbone.model.embeddings.norm.bias''') )
# stages
for i in range(len(config.backbone_config.depths ) ):
for j in range(config.backbone_config.depths[i] ):
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm1.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm1.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_bias_table''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_index''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.proj.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.proj.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm2.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm2.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.weight''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.bias''') )
if i < 3:
rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.reduction.weight''', F'''model.backbone.model.encoder.layers.{i}.downsample.reduction.weight''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.norm.weight''', F'''model.backbone.model.encoder.layers.{i}.downsample.norm.weight''') )
rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.norm.bias''', F'''model.backbone.model.encoder.layers.{i}.downsample.norm.bias''') )
rename_keys.append(('''backbone.0.body.norm1.weight''', '''model.backbone.model.hidden_states_norms.stage2.weight''') )
rename_keys.append(('''backbone.0.body.norm1.bias''', '''model.backbone.model.hidden_states_norms.stage2.bias''') )
rename_keys.append(('''backbone.0.body.norm2.weight''', '''model.backbone.model.hidden_states_norms.stage3.weight''') )
rename_keys.append(('''backbone.0.body.norm2.bias''', '''model.backbone.model.hidden_states_norms.stage3.bias''') )
rename_keys.append(('''backbone.0.body.norm3.weight''', '''model.backbone.model.hidden_states_norms.stage4.weight''') )
rename_keys.append(('''backbone.0.body.norm3.bias''', '''model.backbone.model.hidden_states_norms.stage4.bias''') )
# transformer encoder
for i in range(config.encoder_layers ):
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight''', F'''model.encoder.layers.{i}.self_attn.sampling_offsets.weight''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias''', F'''model.encoder.layers.{i}.self_attn.sampling_offsets.bias''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.attention_weights.weight''', F'''model.encoder.layers.{i}.self_attn.attention_weights.weight''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.attention_weights.bias''', F'''model.encoder.layers.{i}.self_attn.attention_weights.bias''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.value_proj.weight''', F'''model.encoder.layers.{i}.self_attn.value_proj.weight''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.value_proj.bias''', F'''model.encoder.layers.{i}.self_attn.value_proj.bias''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.output_proj.weight''', F'''model.encoder.layers.{i}.self_attn.output_proj.weight''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.output_proj.bias''', F'''model.encoder.layers.{i}.self_attn.output_proj.bias''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.norm1.weight''', F'''model.encoder.layers.{i}.self_attn_layer_norm.weight''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.norm1.bias''', F'''model.encoder.layers.{i}.self_attn_layer_norm.bias''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.weight''', F'''model.encoder.layers.{i}.fc1.weight''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.bias''', F'''model.encoder.layers.{i}.fc1.bias''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.weight''', F'''model.encoder.layers.{i}.fc2.weight''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.bias''', F'''model.encoder.layers.{i}.fc2.bias''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.weight''', F'''model.encoder.layers.{i}.final_layer_norm.weight''') )
rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.bias''', F'''model.encoder.layers.{i}.final_layer_norm.bias''') )
# transformer decoder
for i in range(config.decoder_layers ):
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight''', F'''model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias''', F'''model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.attention_weights.weight''', F'''model.decoder.layers.{i}.encoder_attn.attention_weights.weight''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.attention_weights.bias''', F'''model.decoder.layers.{i}.encoder_attn.attention_weights.bias''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.value_proj.weight''', F'''model.decoder.layers.{i}.encoder_attn.value_proj.weight''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.value_proj.bias''', F'''model.decoder.layers.{i}.encoder_attn.value_proj.bias''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.output_proj.weight''', F'''model.decoder.layers.{i}.encoder_attn.output_proj.weight''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.output_proj.bias''', F'''model.decoder.layers.{i}.encoder_attn.output_proj.bias''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.norm1.weight''', F'''model.decoder.layers.{i}.encoder_attn_layer_norm.weight''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.norm1.bias''', F'''model.decoder.layers.{i}.encoder_attn_layer_norm.bias''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.self_attn.out_proj.weight''', F'''model.decoder.layers.{i}.self_attn.out_proj.weight''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.self_attn.out_proj.bias''', F'''model.decoder.layers.{i}.self_attn.out_proj.bias''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.norm2.weight''', F'''model.decoder.layers.{i}.self_attn_layer_norm.weight''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.norm2.bias''', F'''model.decoder.layers.{i}.self_attn_layer_norm.bias''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.weight''', F'''model.decoder.layers.{i}.fc1.weight''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.bias''', F'''model.decoder.layers.{i}.fc1.bias''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.weight''', F'''model.decoder.layers.{i}.fc2.weight''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.bias''', F'''model.decoder.layers.{i}.fc2.bias''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.weight''', F'''model.decoder.layers.{i}.final_layer_norm.weight''') )
rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.bias''', F'''model.decoder.layers.{i}.final_layer_norm.bias''') )
# fmt: on
return rename_keys
def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
snake_case_ = dct.pop(SCREAMING_SNAKE_CASE__ )
snake_case_ = val
def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
snake_case_ = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )]
for i in range(len(backbone_config.depths ) ):
snake_case_ = num_features[i]
for j in range(backbone_config.depths[i] ):
# fmt: off
# read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias)
snake_case_ = state_dict.pop(F'''backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.weight''' )
snake_case_ = state_dict.pop(F'''backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.bias''' )
# next, add query, keys and values (in that order) to the state dict
snake_case_ = in_proj_weight[:dim, :]
snake_case_ = in_proj_bias[: dim]
snake_case_ = in_proj_weight[
dim : dim * 2, :
]
snake_case_ = in_proj_bias[
dim : dim * 2
]
snake_case_ = in_proj_weight[
-dim :, :
]
snake_case_ = in_proj_bias[-dim :]
# fmt: on
def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
# transformer decoder self-attention layers
snake_case_ = config.d_model
for i in range(config.decoder_layers ):
# read in weights + bias of input projection layer of self-attention
snake_case_ = state_dict.pop(F'''transformer.decoder.layers.{i}.self_attn.in_proj_weight''' )
snake_case_ = state_dict.pop(F'''transformer.decoder.layers.{i}.self_attn.in_proj_bias''' )
# next, add query, keys and values (in that order) to the state dict
snake_case_ = in_proj_weight[:hidden_size, :]
snake_case_ = in_proj_bias[:hidden_size]
snake_case_ = in_proj_weight[
hidden_size : hidden_size * 2, :
]
snake_case_ = in_proj_bias[hidden_size : hidden_size * 2]
snake_case_ = in_proj_weight[-hidden_size:, :]
snake_case_ = in_proj_bias[-hidden_size:]
def __SCREAMING_SNAKE_CASE ():
snake_case_ = '''http://images.cocodataset.org/val2017/000000039769.jpg'''
snake_case_ = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw )
return im
@torch.no_grad()
def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
snake_case_ = get_deta_config(SCREAMING_SNAKE_CASE__ )
# load original state dict
if model_name == "deta-swin-large":
snake_case_ = hf_hub_download(repo_id='''nielsr/deta-checkpoints''' , filename='''adet_swin_ft.pth''' )
elif model_name == "deta-swin-large-o365":
snake_case_ = hf_hub_download(repo_id='''jozhang97/deta-swin-l-o365''' , filename='''deta_swin_pt_o365.pth''' )
else:
raise ValueError(F'''Model name {model_name} not supported''' )
snake_case_ = torch.load(SCREAMING_SNAKE_CASE__ , map_location='''cpu''' )['''model''']
# original state dict
for name, param in state_dict.items():
print(SCREAMING_SNAKE_CASE__ , param.shape )
# rename keys
snake_case_ = create_rename_keys(SCREAMING_SNAKE_CASE__ )
for src, dest in rename_keys:
rename_key(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
read_in_swin_q_k_v(SCREAMING_SNAKE_CASE__ , config.backbone_config )
read_in_decoder_q_k_v(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
# fix some prefixes
for key in state_dict.copy().keys():
if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key:
snake_case_ = state_dict.pop(SCREAMING_SNAKE_CASE__ )
snake_case_ = val
if "input_proj" in key:
snake_case_ = state_dict.pop(SCREAMING_SNAKE_CASE__ )
snake_case_ = val
if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key:
snake_case_ = state_dict.pop(SCREAMING_SNAKE_CASE__ )
snake_case_ = val
# finally, create HuggingFace model and load state dict
snake_case_ = DetaForObjectDetection(SCREAMING_SNAKE_CASE__ )
model.load_state_dict(SCREAMING_SNAKE_CASE__ )
model.eval()
snake_case_ = '''cuda''' if torch.cuda.is_available() else '''cpu'''
model.to(SCREAMING_SNAKE_CASE__ )
# load image processor
snake_case_ = DetaImageProcessor(format='''coco_detection''' )
# verify our conversion on image
snake_case_ = prepare_img()
snake_case_ = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' )
snake_case_ = encoding['''pixel_values''']
snake_case_ = model(pixel_values.to(SCREAMING_SNAKE_CASE__ ) )
# verify logits
print('''Logits:''' , outputs.logits[0, :3, :3] )
print('''Boxes:''' , outputs.pred_boxes[0, :3, :3] )
if model_name == "deta-swin-large":
snake_case_ = torch.tensor(
[[-7.6308, -2.8485, -5.3737], [-7.2037, -4.5505, -4.8027], [-7.2943, -4.2611, -4.6617]] )
snake_case_ = torch.tensor([[0.4987, 0.4969, 0.9999], [0.2549, 0.5498, 0.4805], [0.5498, 0.2757, 0.0569]] )
elif model_name == "deta-swin-large-o365":
snake_case_ = torch.tensor(
[[-8.0122, -3.5720, -4.9717], [-8.1547, -3.6886, -4.6389], [-7.6610, -3.6194, -5.0134]] )
snake_case_ = torch.tensor([[0.2523, 0.5549, 0.4881], [0.7715, 0.4149, 0.4601], [0.5503, 0.2753, 0.0575]] )
assert torch.allclose(outputs.logits[0, :3, :3] , expected_logits.to(SCREAMING_SNAKE_CASE__ ) , atol=1E-4 )
assert torch.allclose(outputs.pred_boxes[0, :3, :3] , expected_boxes.to(SCREAMING_SNAKE_CASE__ ) , atol=1E-4 )
print('''Everything ok!''' )
if pytorch_dump_folder_path:
# Save model and processor
logger.info(F'''Saving PyTorch model and processor to {pytorch_dump_folder_path}...''' )
Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ )
model.save_pretrained(SCREAMING_SNAKE_CASE__ )
processor.save_pretrained(SCREAMING_SNAKE_CASE__ )
# Push to hub
if push_to_hub:
print('''Pushing model and processor to hub...''' )
model.push_to_hub(F'''jozhang97/{model_name}''' )
processor.push_to_hub(F'''jozhang97/{model_name}''' )
if __name__ == "__main__":
lowerCAmelCase_ = argparse.ArgumentParser()
parser.add_argument(
'''--model_name''',
type=str,
default='''deta-swin-large''',
choices=['''deta-swin-large''', '''deta-swin-large-o365'''],
help='''Name of the model you\'d like to convert.''',
)
parser.add_argument(
'''--pytorch_dump_folder_path''',
default=None,
type=str,
help='''Path to the folder to output PyTorch model.''',
)
parser.add_argument(
'''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.'''
)
lowerCAmelCase_ = parser.parse_args()
convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub) | 39 |
"""simple docstring"""
from __future__ import annotations
def lowerCAmelCase_ ( lowercase_ : int ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ )
return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' )
def lowerCAmelCase_ ( ):
'''simple docstring'''
for base_num in range(9999 , 4999 , -1 ):
__SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num
if is_9_pandigital(lowercase_ ):
return candidate
for base_num in range(333 , 99 , -1 ):
__SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num
if is_9_pandigital(lowercase_ ):
return candidate
return None
if __name__ == "__main__":
print(f'{solution() = }')
| 674 | 0 |
def UpperCamelCase ( snake_case__ : list[list[int | float]] ) -> int:
UpperCamelCase : Tuple = len(snake_case__ )
UpperCamelCase : Tuple = len(matrix[0] )
UpperCamelCase : Tuple = min(snake_case__ , snake_case__ )
for row in range(snake_case__ ):
# Check if diagonal element is not zero
if matrix[row][row] != 0:
# Eliminate all the elements below the diagonal
for col in range(row + 1 , snake_case__ ):
UpperCamelCase : Dict = matrix[col][row] / matrix[row][row]
for i in range(snake_case__ , snake_case__ ):
matrix[col][i] -= multiplier * matrix[row][i]
else:
# Find a non-zero diagonal element to swap rows
UpperCamelCase : Optional[int] = True
for i in range(row + 1 , snake_case__ ):
if matrix[i][row] != 0:
UpperCamelCase , UpperCamelCase : Union[str, Any] = matrix[i], matrix[row]
UpperCamelCase : List[str] = False
break
if reduce:
rank -= 1
for i in range(snake_case__ ):
UpperCamelCase : Optional[Any] = matrix[i][rank]
# Reduce the row pointer by one to stay on the same row
row -= 1
return rank
if __name__ == "__main__":
import doctest
doctest.testmod()
| 40 |
"""simple docstring"""
import json
import sys
import tempfile
import unittest
from pathlib import Path
import transformers
from transformers import (
CONFIG_MAPPING,
IMAGE_PROCESSOR_MAPPING,
AutoConfig,
AutoImageProcessor,
CLIPConfig,
CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER
sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils'''))
from test_module.custom_configuration import CustomConfig # noqa E402
from test_module.custom_image_processing import CustomImageProcessor # noqa E402
class snake_case ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE_ ( self :int ):
__SCREAMING_SNAKE_CASE : Tuple = 0
def SCREAMING_SNAKE_CASE_ ( self :Any ):
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :int ):
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json'''
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) )
__SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# Ensure we can load the image processor from the feature extractor config
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json'''
__SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json'''
json.dump(
{'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) )
__SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :int ):
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : str = CLIPConfig()
# Create a dummy config file with image_proceesor_type
__SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json'''
__SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) )
# remove image_processor_type to make sure config.json alone is enough to load image processor locally
__SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict()
config_dict.pop('''image_processor_type''' )
__SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase )
# save in new folder
model_config.save_pretrained(_lowerCamelCase )
config.save_pretrained(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase )
# make sure private variable is not incorrectly saved
__SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() )
self.assertTrue('''_processor_class''' not in dict_as_saved )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , )
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
with self.assertRaisesRegex(
_lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ):
__SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
with self.assertRaisesRegex(
_lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ):
__SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
with self.assertRaisesRegex(
_lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ):
__SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
# If remote code is not set, we will time out when asking whether to load the model.
with self.assertRaises(_lowerCamelCase ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' )
# If remote code is disabled, we can't load this config.
with self.assertRaises(_lowerCamelCase ):
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
# Test image processor can be reloaded.
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase )
self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
try:
AutoConfig.register('''custom''' , _lowerCamelCase )
AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase )
# Trying to register something existing in the Transformers library will raise an error
with self.assertRaises(_lowerCamelCase ):
AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase )
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json'''
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json'''
json.dump(
{'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) )
__SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase )
# Now that the config is registered, it can be used as any other config with the auto-API
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = True
try:
AutoConfig.register('''custom''' , _lowerCamelCase )
AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase )
# If remote code is not set, the default is to use local
__SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
self.assertTrue(image_processor.is_local )
# If remote code is disabled, we load the local one.
__SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
self.assertTrue(image_processor.is_local )
# If remote is enabled, we load from the Hub
__SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
self.assertTrue(not hasattr(_lowerCamelCase , '''is_local''' ) )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
| 674 | 0 |
'''simple docstring'''
import logging
import os
import threading
import time
try:
import warnings
except ImportError:
lowerCAmelCase__ = None
try:
import msvcrt
except ImportError:
lowerCAmelCase__ = None
try:
import fcntl
except ImportError:
lowerCAmelCase__ = None
# Backward compatibility
# ------------------------------------------------
try:
TimeoutError
except NameError:
lowerCAmelCase__ = OSError
# Data
# ------------------------------------------------
lowerCAmelCase__ = [
'''Timeout''',
'''BaseFileLock''',
'''WindowsFileLock''',
'''UnixFileLock''',
'''SoftFileLock''',
'''FileLock''',
]
lowerCAmelCase__ = '''3.0.12'''
lowerCAmelCase__ = None
def _A ( ):
"""simple docstring"""
global _logger
__lowercase = _logger or logging.getLogger(__name__ )
return _logger
class lowercase_ (lowerCamelCase__ ):
"""simple docstring"""
def __init__( self : Any ,lowercase__ : Optional[Any] ):
__lowercase = lock_file
return None
def __str__( self : Optional[int] ):
__lowercase = F"The file lock '{self.lock_file}' could not be acquired."
return temp
class lowercase_ :
"""simple docstring"""
def __init__( self : Optional[Any] ,lowercase__ : int ):
__lowercase = lock
return None
def __enter__( self : int ):
return self.lock
def __exit__( self : Any ,lowercase__ : Optional[Any] ,lowercase__ : int ,lowercase__ : Optional[Any] ):
self.lock.release()
return None
class lowercase_ :
"""simple docstring"""
def __init__( self : Dict ,lowercase__ : Union[str, Any] ,lowercase__ : int=-1 ,lowercase__ : List[Any]=None ):
__lowercase = max_filename_length if max_filename_length is not None else 2_5_5
# Hash the filename if it's too long
__lowercase = self.hash_filename_if_too_long(lowercase__ ,lowercase__ )
# The path to the lock file.
__lowercase = lock_file
# The file descriptor for the *_lock_file* as it is returned by the
# os.open() function.
# This file lock is only NOT None, if the object currently holds the
# lock.
__lowercase = None
# The default timeout value.
__lowercase = timeout
# We use this lock primarily for the lock counter.
__lowercase = threading.Lock()
# The lock counter is used for implementing the nested locking
# mechanism. Whenever the lock is acquired, the counter is increased and
# the lock is only released, when this value is 0 again.
__lowercase = 0
return None
@property
def SCREAMING_SNAKE_CASE ( self : List[Any] ):
return self._lock_file
@property
def SCREAMING_SNAKE_CASE ( self : Dict ):
return self._timeout
@timeout.setter
def SCREAMING_SNAKE_CASE ( self : Dict ,lowercase__ : Optional[Any] ):
__lowercase = float(lowercase__ )
return None
def SCREAMING_SNAKE_CASE ( self : List[Any] ):
raise NotImplementedError()
def SCREAMING_SNAKE_CASE ( self : str ):
raise NotImplementedError()
@property
def SCREAMING_SNAKE_CASE ( self : List[str] ):
return self._lock_file_fd is not None
def SCREAMING_SNAKE_CASE ( self : Tuple ,lowercase__ : Optional[int]=None ,lowercase__ : Dict=0.0_5 ):
# Use the default timeout, if no timeout is provided.
if timeout is None:
__lowercase = self.timeout
# Increment the number right at the beginning.
# We can still undo it, if something fails.
with self._thread_lock:
self._lock_counter += 1
__lowercase = id(self )
__lowercase = self._lock_file
__lowercase = time.time()
try:
while True:
with self._thread_lock:
if not self.is_locked:
logger().debug(F"Attempting to acquire lock {lock_id} on {lock_filename}" )
self._acquire()
if self.is_locked:
logger().debug(F"Lock {lock_id} acquired on {lock_filename}" )
break
elif timeout >= 0 and time.time() - start_time > timeout:
logger().debug(F"Timeout on acquiring lock {lock_id} on {lock_filename}" )
raise Timeout(self._lock_file )
else:
logger().debug(
F"Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ..." )
time.sleep(lowercase__ )
except: # noqa
# Something did go wrong, so decrement the counter.
with self._thread_lock:
__lowercase = max(0 ,self._lock_counter - 1 )
raise
return _Acquire_ReturnProxy(lock=self )
def SCREAMING_SNAKE_CASE ( self : List[Any] ,lowercase__ : List[Any]=False ):
with self._thread_lock:
if self.is_locked:
self._lock_counter -= 1
if self._lock_counter == 0 or force:
__lowercase = id(self )
__lowercase = self._lock_file
logger().debug(F"Attempting to release lock {lock_id} on {lock_filename}" )
self._release()
__lowercase = 0
logger().debug(F"Lock {lock_id} released on {lock_filename}" )
return None
def __enter__( self : List[Any] ):
self.acquire()
return self
def __exit__( self : Any ,lowercase__ : str ,lowercase__ : int ,lowercase__ : int ):
self.release()
return None
def __del__( self : int ):
self.release(force=lowercase__ )
return None
def SCREAMING_SNAKE_CASE ( self : Optional[int] ,lowercase__ : str ,lowercase__ : int ):
__lowercase = os.path.basename(lowercase__ )
if len(lowercase__ ) > max_length and max_length > 0:
__lowercase = os.path.dirname(lowercase__ )
__lowercase = str(hash(lowercase__ ) )
__lowercase = filename[: max_length - len(lowercase__ ) - 8] + '''...''' + hashed_filename + '''.lock'''
return os.path.join(lowercase__ ,lowercase__ )
else:
return path
class lowercase_ (lowerCamelCase__ ):
"""simple docstring"""
def __init__( self : Union[str, Any] ,lowercase__ : str ,lowercase__ : Optional[Any]=-1 ,lowercase__ : List[str]=None ):
from .file_utils import relative_to_absolute_path
super().__init__(lowercase__ ,timeout=lowercase__ ,max_filename_length=lowercase__ )
__lowercase = '''\\\\?\\''' + relative_to_absolute_path(self.lock_file )
def SCREAMING_SNAKE_CASE ( self : str ):
__lowercase = os.O_RDWR | os.O_CREAT | os.O_TRUNC
try:
__lowercase = os.open(self._lock_file ,lowercase__ )
except OSError:
pass
else:
try:
msvcrt.locking(lowercase__ ,msvcrt.LK_NBLCK ,1 )
except OSError:
os.close(lowercase__ )
else:
__lowercase = fd
return None
def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ):
__lowercase = self._lock_file_fd
__lowercase = None
msvcrt.locking(lowercase__ ,msvcrt.LK_UNLCK ,1 )
os.close(lowercase__ )
try:
os.remove(self._lock_file )
# Probably another instance of the application
# that acquired the file lock.
except OSError:
pass
return None
class lowercase_ (lowerCamelCase__ ):
"""simple docstring"""
def __init__( self : Dict ,lowercase__ : int ,lowercase__ : Union[str, Any]=-1 ,lowercase__ : Union[str, Any]=None ):
__lowercase = os.statvfs(os.path.dirname(lowercase__ ) ).f_namemax
super().__init__(lowercase__ ,timeout=lowercase__ ,max_filename_length=lowercase__ )
def SCREAMING_SNAKE_CASE ( self : Dict ):
__lowercase = os.O_RDWR | os.O_CREAT | os.O_TRUNC
__lowercase = os.open(self._lock_file ,lowercase__ )
try:
fcntl.flock(lowercase__ ,fcntl.LOCK_EX | fcntl.LOCK_NB )
except OSError:
os.close(lowercase__ )
else:
__lowercase = fd
return None
def SCREAMING_SNAKE_CASE ( self : List[Any] ):
# Do not remove the lockfile:
#
# https://github.com/benediktschmitt/py-filelock/issues/31
# https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition
__lowercase = self._lock_file_fd
__lowercase = None
fcntl.flock(lowercase__ ,fcntl.LOCK_UN )
os.close(lowercase__ )
return None
class lowercase_ (lowerCamelCase__ ):
"""simple docstring"""
def SCREAMING_SNAKE_CASE ( self : Optional[Any] ):
__lowercase = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
try:
__lowercase = os.open(self._lock_file ,lowercase__ )
except OSError:
pass
else:
__lowercase = fd
return None
def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ):
os.close(self._lock_file_fd )
__lowercase = None
try:
os.remove(self._lock_file )
# The file is already deleted and that's what we want.
except OSError:
pass
return None
lowerCAmelCase__ = None
if msvcrt:
lowerCAmelCase__ = WindowsFileLock
elif fcntl:
lowerCAmelCase__ = UnixFileLock
else:
lowerCAmelCase__ = SoftFileLock
if warnings is not None:
warnings.warn('''only soft file lock is available''')
| 41 |
"""simple docstring"""
from __future__ import annotations
from typing import Any
class snake_case ( __UpperCAmelCase ):
pass
class snake_case :
def __init__( self :List[Any] , _lowerCamelCase :Any ):
__SCREAMING_SNAKE_CASE : Any = data
__SCREAMING_SNAKE_CASE : Node | None = None
def __iter__( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : List[str] = self
__SCREAMING_SNAKE_CASE : List[str] = []
while node:
if node in visited:
raise ContainsLoopError
visited.append(_lowerCamelCase )
yield node.data
__SCREAMING_SNAKE_CASE : List[str] = node.next_node
@property
def SCREAMING_SNAKE_CASE_ ( self :Any ):
try:
list(self )
return False
except ContainsLoopError:
return True
if __name__ == "__main__":
_lowerCamelCase = Node(1)
_lowerCamelCase = Node(2)
_lowerCamelCase = Node(3)
_lowerCamelCase = Node(4)
print(root_node.has_loop) # False
_lowerCamelCase = root_node.next_node
print(root_node.has_loop) # True
_lowerCamelCase = Node(5)
_lowerCamelCase = Node(6)
_lowerCamelCase = Node(5)
_lowerCamelCase = Node(6)
print(root_node.has_loop) # False
_lowerCamelCase = Node(1)
print(root_node.has_loop) # False
| 674 | 0 |
'''simple docstring'''
from typing import List, Optional, Tuple, Union
import torch
from ...models import UNetaDModel
from ...schedulers import ScoreSdeVeScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class UpperCAmelCase ( UpperCAmelCase__ ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ = 42
SCREAMING_SNAKE_CASE_ = 42
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str:
'''simple docstring'''
super().__init__()
self.register_modules(unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ )
@torch.no_grad()
def __call__( self , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 2000 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , **SCREAMING_SNAKE_CASE_ , ) -> Union[ImagePipelineOutput, Tuple]:
'''simple docstring'''
lowerCamelCase_ = self.unet.config.sample_size
lowerCamelCase_ = (batch_size, 3, img_size, img_size)
lowerCamelCase_ = self.unet
lowerCamelCase_ = randn_tensor(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ) * self.scheduler.init_noise_sigma
lowerCamelCase_ = sample.to(self.device )
self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ )
self.scheduler.set_sigmas(SCREAMING_SNAKE_CASE_ )
for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ):
lowerCamelCase_ = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device )
# correction step
for _ in range(self.scheduler.config.correct_steps ):
lowerCamelCase_ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample
lowerCamelCase_ = self.scheduler.step_correct(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ).prev_sample
# prediction step
lowerCamelCase_ = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample
lowerCamelCase_ = self.scheduler.step_pred(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ )
lowerCamelCase_ ,lowerCamelCase_ = output.prev_sample, output.prev_sample_mean
lowerCamelCase_ = sample_mean.clamp(0 , 1 )
lowerCamelCase_ = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
lowerCamelCase_ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ )
if not return_dict:
return (sample,)
return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE_ )
| 42 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_lowerCamelCase = logging.get_logger(__name__)
_lowerCamelCase = {
'''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''',
}
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = '''roc_bert'''
def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ):
__SCREAMING_SNAKE_CASE : List[str] = vocab_size
__SCREAMING_SNAKE_CASE : int = max_position_embeddings
__SCREAMING_SNAKE_CASE : List[str] = hidden_size
__SCREAMING_SNAKE_CASE : str = num_hidden_layers
__SCREAMING_SNAKE_CASE : int = num_attention_heads
__SCREAMING_SNAKE_CASE : Any = intermediate_size
__SCREAMING_SNAKE_CASE : Optional[int] = hidden_act
__SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob
__SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob
__SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range
__SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size
__SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps
__SCREAMING_SNAKE_CASE : Optional[int] = use_cache
__SCREAMING_SNAKE_CASE : str = enable_pronunciation
__SCREAMING_SNAKE_CASE : List[str] = enable_shape
__SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim
__SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size
__SCREAMING_SNAKE_CASE : str = shape_embed_dim
__SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size
__SCREAMING_SNAKE_CASE : Tuple = concat_input
__SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type
__SCREAMING_SNAKE_CASE : str = classifier_dropout
super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
| 674 | 0 |
import os
from shutil import copyfile
from typing import List, Optional, Tuple
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging
if is_sentencepiece_available():
from .tokenization_pegasus import PegasusTokenizer
else:
lowerCAmelCase = None
lowerCAmelCase = logging.get_logger(__name__)
lowerCAmelCase = '▁'
lowerCAmelCase = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'}
lowerCAmelCase = {
'vocab_file': {'google/pegasus-xsum': 'https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'},
'tokenizer_file': {
'google/pegasus-xsum': 'https://huggingface.co/google/pegasus-xsum/resolve/main/tokenizer.json'
},
}
lowerCAmelCase = {
'google/pegasus-xsum': 512,
}
class _a ( UpperCamelCase__ ):
_lowercase : Optional[int] = VOCAB_FILES_NAMES
_lowercase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP
_lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_lowercase : Optional[int] = PegasusTokenizer
_lowercase : Tuple = ['''input_ids''', '''attention_mask''']
def __init__( self: List[str] , UpperCamelCase_: int=None , UpperCamelCase_: Dict=None , UpperCamelCase_: Tuple="<pad>" , UpperCamelCase_: Dict="</s>" , UpperCamelCase_: Tuple="<unk>" , UpperCamelCase_: Optional[int]="<mask_2>" , UpperCamelCase_: Dict="<mask_1>" , UpperCamelCase_: Any=None , UpperCamelCase_: int=103 , **UpperCamelCase_: List[str] , ) -> Optional[int]:
"""simple docstring"""
lowercase__ = offset
if additional_special_tokens is not None:
if not isinstance(UpperCamelCase_ , UpperCamelCase_ ):
raise TypeError(
f'additional_special_tokens should be of type {type(UpperCamelCase_ )}, but is'
f' {type(UpperCamelCase_ )}' )
lowercase__ = (
([mask_token_sent] + additional_special_tokens)
if mask_token_sent not in additional_special_tokens and mask_token_sent is not None
else additional_special_tokens
)
# fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken
additional_special_tokens_extended += [
f'<unk_{i}>' for i in range(len(UpperCamelCase_ ) , self.offset - 1 )
]
if len(set(UpperCamelCase_ ) ) != len(UpperCamelCase_ ):
raise ValueError(
'''Please make sure that the provided additional_special_tokens do not contain an incorrectly'''
f' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.' )
lowercase__ = additional_special_tokens_extended
else:
lowercase__ = [mask_token_sent] if mask_token_sent is not None else []
additional_special_tokens += [f'<unk_{i}>' for i in range(2 , self.offset )]
super().__init__(
UpperCamelCase_ , tokenizer_file=UpperCamelCase_ , pad_token=UpperCamelCase_ , eos_token=UpperCamelCase_ , unk_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , mask_token_sent=UpperCamelCase_ , offset=UpperCamelCase_ , additional_special_tokens=UpperCamelCase_ , **UpperCamelCase_ , )
lowercase__ = vocab_file
lowercase__ = False if not self.vocab_file else True
def lowerCamelCase_ ( self: List[Any] , UpperCamelCase_: Any ) -> Dict:
"""simple docstring"""
lowercase__ = set(self.all_special_ids ) # call it once instead of inside list comp
all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special
if all_special_ids != set(range(len(self.additional_special_tokens ) + 3 ) ):
raise ValueError(
'''There should be 3 special tokens: mask_token, pad_token, and eos_token +'''
f' {len(self.additional_special_tokens )} additional_special_tokens, but got {all_special_ids}' )
return [1 if x in all_special_ids else 0 for x in seq]
def lowerCamelCase_ ( self: Any , UpperCamelCase_: List , UpperCamelCase_: Optional[List] = None , UpperCamelCase_: bool = False ) -> List[int]:
"""simple docstring"""
if already_has_special_tokens:
return self._special_token_mask(UpperCamelCase_ )
elif token_ids_a is None:
return self._special_token_mask(UpperCamelCase_ ) + [1]
else:
return self._special_token_mask(token_ids_a + token_ids_a ) + [1]
def lowerCamelCase_ ( self: List[str] , UpperCamelCase_: Union[str, Any] , UpperCamelCase_: str=None ) -> List[int]:
"""simple docstring"""
if token_ids_a is None:
return token_ids_a + [self.eos_token_id]
# We don't expect to process pairs, but leave the pair logic for API consistency
return token_ids_a + token_ids_a + [self.eos_token_id]
def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase_: str , UpperCamelCase_: Optional[str] = None ) -> Tuple[str]:
"""simple docstring"""
if not self.can_save_slow_tokenizer:
raise ValueError(
'''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow '''
'''tokenizer.''' )
if not os.path.isdir(UpperCamelCase_ ):
logger.error(f'Vocabulary path ({save_directory}) should be a directory' )
return
lowercase__ = os.path.join(
UpperCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase_ ):
copyfile(self.vocab_file , UpperCamelCase_ )
return (out_vocab_file,)
| 43 |
"""simple docstring"""
import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List
import git
import torch
from torch.utils.data import Dataset
from transformers import BartTokenizer, RagTokenizer, TaTokenizer
def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {}
__SCREAMING_SNAKE_CASE : Optional[int] = padding_side
return tokenizer(
[line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , )
def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 )
if attention_mask is None:
return input_ids[:, keep_column_mask]
else:
return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])
class snake_case ( __UpperCAmelCase ):
def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ):
super().__init__()
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' )
__SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' )
__SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file )
__SCREAMING_SNAKE_CASE : List[str] = max_source_length
__SCREAMING_SNAKE_CASE : Dict = max_target_length
assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}'''
__SCREAMING_SNAKE_CASE : Dict = tokenizer
__SCREAMING_SNAKE_CASE : Union[str, Any] = prefix
if n_obs is not None:
__SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs]
__SCREAMING_SNAKE_CASE : List[str] = src_lang
__SCREAMING_SNAKE_CASE : str = tgt_lang
def __len__( self :int ):
return len(self.src_lens )
def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ):
__SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1
__SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' )
__SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' )
assert source_line, f'''empty source line for index {index}'''
assert tgt_line, f'''empty tgt line for index {index}'''
# Need to add eos token manually for T5
if isinstance(self.tokenizer , _lowerCamelCase ):
source_line += self.tokenizer.eos_token
tgt_line += self.tokenizer.eos_token
# Pad source and target to the right
__SCREAMING_SNAKE_CASE : Dict = (
self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer
)
__SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer
__SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' )
__SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' )
__SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze()
__SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze()
__SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze()
return {
"input_ids": source_ids,
"attention_mask": src_mask,
"decoder_input_ids": target_ids,
}
@staticmethod
def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ):
return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()]
def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ):
__SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] )
__SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] )
__SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] )
__SCREAMING_SNAKE_CASE : str = (
self.tokenizer.generator.pad_token_id
if isinstance(self.tokenizer , _lowerCamelCase )
else self.tokenizer.pad_token_id
)
__SCREAMING_SNAKE_CASE : Union[str, Any] = (
self.tokenizer.question_encoder.pad_token_id
if isinstance(self.tokenizer , _lowerCamelCase )
else self.tokenizer.pad_token_id
)
__SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Dict = {
'''input_ids''': source_ids,
'''attention_mask''': source_mask,
'''decoder_input_ids''': y,
}
return batch
_lowerCamelCase = getLogger(__name__)
def lowerCAmelCase_ ( lowercase_ : List[List] ):
'''simple docstring'''
return list(itertools.chain.from_iterable(lowercase_ ) )
def lowerCAmelCase_ ( lowercase_ : str ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = get_git_info()
save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) )
def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ):
'''simple docstring'''
with open(lowercase_ , '''w''' ) as f:
json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ )
def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ):
'''simple docstring'''
with open(lowercase_ ) as f:
return json.load(lowercase_ )
def lowerCAmelCase_ ( ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ )
__SCREAMING_SNAKE_CASE : List[str] = {
'''repo_id''': str(lowercase_ ),
'''repo_sha''': str(repo.head.object.hexsha ),
'''repo_branch''': str(repo.active_branch ),
'''hostname''': str(socket.gethostname() ),
}
return repo_infos
def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ):
'''simple docstring'''
return list(map(lowercase_ , lowercase_ ) )
def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ):
'''simple docstring'''
with open(lowercase_ , '''wb''' ) as f:
return pickle.dump(lowercase_ , lowercase_ )
def lowerCAmelCase_ ( lowercase_ : Any ):
'''simple docstring'''
def remove_articles(lowercase_ : Dict ):
return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ )
def white_space_fix(lowercase_ : Optional[int] ):
return " ".join(text.split() )
def remove_punc(lowercase_ : Any ):
__SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation )
return "".join(ch for ch in text if ch not in exclude )
def lower(lowercase_ : int ):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) )
def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split()
__SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split()
__SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ )
__SCREAMING_SNAKE_CASE : Tuple = sum(common.values() )
if num_same == 0:
return 0
__SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ )
__SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ )
__SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall)
return fa
def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ):
'''simple docstring'''
return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ )
def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ):
'''simple docstring'''
assert len(lowercase_ ) == len(lowercase_ )
__SCREAMING_SNAKE_CASE : Union[str, Any] = 0
for hypo, pred in zip(lowercase_ , lowercase_ ):
em += exact_match_score(lowercase_ , lowercase_ )
if len(lowercase_ ) > 0:
em /= len(lowercase_ )
return {"em": em}
def lowerCAmelCase_ ( lowercase_ : str ):
'''simple docstring'''
return model_prefix.startswith('''rag''' )
def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params}
# T5 models don't have `dropout` param, they have `dropout_rate` instead
__SCREAMING_SNAKE_CASE : Any = '''dropout_rate'''
for p in extra_params:
if getattr(lowercase_ , lowercase_ , lowercase_ ):
if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ):
logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) )
delattr(lowercase_ , lowercase_ )
continue
__SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p]
setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) )
delattr(lowercase_ , lowercase_ )
return hparams, config
| 674 | 0 |
'''simple docstring'''
import json
import os
import unittest
from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import (
VOCAB_FILES_NAMES,
GPTSanJapaneseTokenizer,
)
from transformers.testing_utils import require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class UpperCAmelCase__ ( A , unittest.TestCase ):
lowerCAmelCase_ = GPTSanJapaneseTokenizer
lowerCAmelCase_ = False
lowerCAmelCase_ = {'do_clean_text': False, 'add_prefix_space': False}
def lowerCamelCase_ ( self : Union[str, Any] ):
super().setUp()
# fmt: off
_lowerCamelCase : Dict = ["こん", "こんに", "にちは", "ばんは", "世界,㔺界", "、", "。", "<BR>", "<SP>", "<TAB>", "<URL>", "<EMAIL>", "<TEL>", "<DATE>", "<PRICE>", "<BLOCK>", "<KIGOU>", "<U2000U2BFF>", "<|emoji1|>", "<unk>", "<|bagoftoken|>", "<|endoftext|>"]
# fmt: on
_lowerCamelCase : Union[str, Any] = {"emoji": {"\ud83d\ude00": "<|emoji1|>"}, "emoji_inv": {"<|emoji1|>": "\ud83d\ude00"}} # 😀
_lowerCamelCase : int = {"unk_token": "<unk>"}
_lowerCamelCase : int = os.path.join(self.tmpdirname,VOCAB_FILES_NAMES["vocab_file"] )
_lowerCamelCase : int = os.path.join(self.tmpdirname,VOCAB_FILES_NAMES["emoji_file"] )
with open(self.vocab_file,"w",encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) )
with open(self.emoji_file,"w" ) as emoji_writer:
emoji_writer.write(json.dumps(__A ) )
def lowerCamelCase_ ( self : List[Any],**__A : Optional[int] ):
kwargs.update(self.special_tokens_map )
return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname,**__A )
def lowerCamelCase_ ( self : List[str],__A : int ):
_lowerCamelCase : List[Any] = "こんにちは、世界。 \nこんばんは、㔺界。😀"
_lowerCamelCase : Optional[int] = "こんにちは、世界。 \nこんばんは、世界。😀"
return input_text, output_text
def lowerCamelCase_ ( self : Dict,__A : Optional[int] ):
_lowerCamelCase , _lowerCamelCase : int = self.get_input_output_texts(__A )
_lowerCamelCase : Optional[Any] = tokenizer.encode(__A,add_special_tokens=__A )
_lowerCamelCase : int = tokenizer.decode(__A,clean_up_tokenization_spaces=__A )
return text, ids
def lowerCamelCase_ ( self : int ):
pass # TODO add if relevant
def lowerCamelCase_ ( self : Tuple ):
pass # TODO add if relevant
def lowerCamelCase_ ( self : Dict ):
pass # TODO add if relevant
def lowerCamelCase_ ( self : List[str] ):
_lowerCamelCase : Optional[Any] = self.get_tokenizer()
# Testing tokenization
_lowerCamelCase : Union[str, Any] = "こんにちは、世界。 こんばんは、㔺界。"
_lowerCamelCase : List[Any] = ["こん", "にちは", "、", "世界", "。", "<SP>", "こん", "ばんは", "、", "㔺界", "。"]
_lowerCamelCase : str = tokenizer.tokenize(__A )
self.assertListEqual(__A,__A )
# Testing conversion to ids without special tokens
_lowerCamelCase : Dict = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6]
_lowerCamelCase : int = tokenizer.convert_tokens_to_ids(__A )
self.assertListEqual(__A,__A )
# Testing conversion to ids with special tokens
_lowerCamelCase : Optional[Any] = tokens + [tokenizer.unk_token]
_lowerCamelCase : int = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 1_9]
_lowerCamelCase : List[Any] = tokenizer.convert_tokens_to_ids(__A )
self.assertListEqual(__A,__A )
def lowerCamelCase_ ( self : Optional[int] ):
_lowerCamelCase : List[Any] = self.get_tokenizer()
# Testing tokenization
_lowerCamelCase : Optional[Any] = "こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。"
_lowerCamelCase : Tuple = "こんにちは、、、、世界。こんばんは、、、、世界。"
_lowerCamelCase : Any = tokenizer.encode(__A )
_lowerCamelCase : int = tokenizer.decode(__A )
self.assertEqual(__A,__A )
@slow
def lowerCamelCase_ ( self : Any ):
_lowerCamelCase : str = self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese" )
# Testing tokenization
_lowerCamelCase : Optional[Any] = "こんにちは、世界。"
_lowerCamelCase : List[str] = "こんばんは、㔺界。😀"
_lowerCamelCase : str = "こんにちは、世界。こんばんは、世界。😀"
_lowerCamelCase : Tuple = tokenizer.encode(prefix_text + input_text )
_lowerCamelCase : List[Any] = tokenizer.encode("",prefix_text=prefix_text + input_text )
_lowerCamelCase : Optional[Any] = tokenizer.encode(__A,prefix_text=__A )
_lowerCamelCase : Optional[Any] = tokenizer.decode(__A )
_lowerCamelCase : List[str] = tokenizer.decode(__A )
_lowerCamelCase : Dict = tokenizer.decode(__A )
self.assertEqual(__A,__A )
self.assertEqual(__A,__A )
self.assertEqual(__A,__A )
@slow
def lowerCamelCase_ ( self : Tuple ):
_lowerCamelCase : List[str] = self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese" )
# Testing tokenization
_lowerCamelCase : Optional[int] = "こんにちは、世界。"
_lowerCamelCase : Optional[Any] = "こんばんは、㔺界。😀"
_lowerCamelCase : Any = len(tokenizer.encode(__A ) ) - 2
_lowerCamelCase : Dict = len(tokenizer.encode(__A ) ) - 2
_lowerCamelCase : int = [1] + [0] * (len_prefix + len_text + 1)
_lowerCamelCase : Optional[Any] = [1] * (len_prefix + len_text + 1) + [0]
_lowerCamelCase : List[str] = [1] + [1] * (len_prefix) + [0] * (len_text + 1)
_lowerCamelCase : Optional[int] = tokenizer(prefix_text + input_text ).token_type_ids
_lowerCamelCase : List[Any] = tokenizer("",prefix_text=prefix_text + input_text ).token_type_ids
_lowerCamelCase : str = tokenizer(__A,prefix_text=__A ).token_type_ids
self.assertListEqual(__A,__A )
self.assertListEqual(__A,__A )
self.assertListEqual(__A,__A )
@slow
def lowerCamelCase_ ( self : Dict ):
_lowerCamelCase : List[str] = self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese" )
_lowerCamelCase : Any = tokenizer.encode("あンいワ" )
_lowerCamelCase : List[Any] = tokenizer.encode("",prefix_text="あンいワ" )
_lowerCamelCase : str = tokenizer.encode("いワ",prefix_text="あン" )
self.assertEqual(tokenizer.decode(__A ),tokenizer.decode(__A ) )
self.assertEqual(tokenizer.decode(__A ),tokenizer.decode(__A ) )
self.assertNotEqual(__A,__A )
self.assertNotEqual(__A,__A )
self.assertEqual(x_token_a[1],x_token_a[-1] ) # SEG token
self.assertEqual(x_token_a[1],x_token_a[3] ) # SEG token
@slow
def lowerCamelCase_ ( self : Dict ):
_lowerCamelCase : Optional[int] = self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese" )
_lowerCamelCase : str = [["武田信玄", "は、"], ["織田信長", "の配下の、"]]
_lowerCamelCase : List[Any] = tokenizer(__A,padding=__A )
_lowerCamelCase : str = tokenizer.batch_encode_plus(__A,padding=__A )
# fmt: off
_lowerCamelCase : Dict = [[3_5_9_9_3, 8_6_4_0, 2_5_9_4_8, 3_5_9_9_8, 3_0_6_4_7, 3_5_6_7_5, 3_5_9_9_9, 3_5_9_9_9], [3_5_9_9_3, 1_0_3_8_2, 9_8_6_8, 3_5_9_9_8, 3_0_6_4_6, 9_4_5_9, 3_0_6_4_6, 3_5_6_7_5]]
_lowerCamelCase : int = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]]
_lowerCamelCase : Tuple = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]]
# fmt: on
self.assertListEqual(x_token.input_ids,__A )
self.assertListEqual(x_token.token_type_ids,__A )
self.assertListEqual(x_token.attention_mask,__A )
self.assertListEqual(x_token_a.input_ids,__A )
self.assertListEqual(x_token_a.token_type_ids,__A )
self.assertListEqual(x_token_a.attention_mask,__A )
def lowerCamelCase_ ( self : Any ):
# Intentionally convert some words to accommodate character fluctuations unique to Japanese
pass
def lowerCamelCase_ ( self : Any ):
# tokenizer has no padding token
pass | 44 |
"""simple docstring"""
from collections.abc import Callable
import numpy as np
def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) )
__SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) )
__SCREAMING_SNAKE_CASE : List[Any] = ya
__SCREAMING_SNAKE_CASE : Dict = xa
for k in range(lowercase_ ):
__SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] )
__SCREAMING_SNAKE_CASE : int = y[k] + (
(step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ ))
)
x += step_size
return y
if __name__ == "__main__":
import doctest
doctest.testmod()
| 674 | 0 |
from typing import List, Optional, Tuple, Union
import torch
from ...utils import logging, randn_tensor
from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline
UpperCamelCase = logging.get_logger(__name__) # pylint: disable=invalid-name
class lowerCAmelCase_ ( lowercase ):
"""simple docstring"""
def __init__( self :int , lowerCamelCase__ :int , lowerCamelCase__ :Optional[int] ):
super().__init__()
self.register_modules(unet=lowerCamelCase__ , scheduler=lowerCamelCase__ )
@torch.no_grad()
def __call__( self :Optional[int] , lowerCamelCase__ :int = 1 , lowerCamelCase__ :int = 1_00 , lowerCamelCase__ :Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCamelCase__ :Optional[float] = None , lowerCamelCase__ :bool = True , ):
if audio_length_in_s is None:
UpperCamelCase__ :List[Any] = self.unet.config.sample_size / self.unet.config.sample_rate
UpperCamelCase__ :Tuple = audio_length_in_s * self.unet.config.sample_rate
UpperCamelCase__ :str = 2 ** len(self.unet.up_blocks )
if sample_size < 3 * down_scale_factor:
raise ValueError(
f"""{audio_length_in_s} is too small. Make sure it's bigger or equal to"""
f""" {3 * down_scale_factor / self.unet.config.sample_rate}.""" )
UpperCamelCase__ :Tuple = int(lowerCamelCase__ )
if sample_size % down_scale_factor != 0:
UpperCamelCase__ :Union[str, Any] = (
(audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1
) * down_scale_factor
logger.info(
f"""{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled"""
f""" by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising"""
""" process.""" )
UpperCamelCase__ :Dict = int(lowerCamelCase__ )
UpperCamelCase__ :Any = next(iter(self.unet.parameters() ) ).dtype
UpperCamelCase__ :Union[str, Any] = (batch_size, self.unet.config.in_channels, sample_size)
if isinstance(lowerCamelCase__ , lowerCamelCase__ ) and len(lowerCamelCase__ ) != batch_size:
raise ValueError(
f"""You have passed a list of generators of length {len(lowerCamelCase__ )}, but requested an effective batch"""
f""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" )
UpperCamelCase__ :Union[str, Any] = randn_tensor(lowerCamelCase__ , generator=lowerCamelCase__ , device=self.device , dtype=lowerCamelCase__ )
# set step values
self.scheduler.set_timesteps(lowerCamelCase__ , device=audio.device )
UpperCamelCase__ :List[Any] = self.scheduler.timesteps.to(lowerCamelCase__ )
for t in self.progress_bar(self.scheduler.timesteps ):
# 1. predict noise model_output
UpperCamelCase__ :Tuple = self.unet(lowerCamelCase__ , lowerCamelCase__ ).sample
# 2. compute previous image: x_t -> t_t-1
UpperCamelCase__ :str = self.scheduler.step(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ).prev_sample
UpperCamelCase__ :Any = audio.clamp(-1 , 1 ).float().cpu().numpy()
UpperCamelCase__ :Optional[int] = audio[:, :, :original_sample_size]
if not return_dict:
return (audio,)
return AudioPipelineOutput(audios=lowerCamelCase__ ) | 45 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...file_utils import _LazyModule, is_torch_available
from ...utils import OptionalDependencyNotAvailable
_lowerCamelCase = {
'''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''],
'''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase = [
'''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''GPTNeoXJapaneseForCausalLM''',
'''GPTNeoXJapaneseLayer''',
'''GPTNeoXJapaneseModel''',
'''GPTNeoXJapanesePreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig
from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_gpt_neox_japanese import (
GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST,
GPTNeoXJapaneseForCausalLM,
GPTNeoXJapaneseLayer,
GPTNeoXJapaneseModel,
GPTNeoXJapanesePreTrainedModel,
)
else:
import sys
_lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 674 | 0 |
"""simple docstring"""
def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase ) -> float:
'''simple docstring'''
return price * (1 + tax_rate)
if __name__ == "__main__":
print(f'''{price_plus_tax(100, 0.25) = }''')
print(f'''{price_plus_tax(125.50, 0.05) = }''') | 46 |
"""simple docstring"""
from __future__ import annotations
from typing import Any
class snake_case :
def __init__( self :Optional[Any] , _lowerCamelCase :int ):
__SCREAMING_SNAKE_CASE : int = num_of_nodes
__SCREAMING_SNAKE_CASE : list[list[int]] = []
__SCREAMING_SNAKE_CASE : dict[int, int] = {}
def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ):
self.m_edges.append([u_node, v_node, weight] )
def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ):
if self.m_component[u_node] == u_node:
return u_node
return self.find_component(self.m_component[u_node] )
def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ):
if self.m_component[u_node] != u_node:
for k in self.m_component:
__SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ):
if component_size[u_node] <= component_size[v_node]:
__SCREAMING_SNAKE_CASE : List[Any] = v_node
component_size[v_node] += component_size[u_node]
self.set_component(_lowerCamelCase )
elif component_size[u_node] >= component_size[v_node]:
__SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase )
component_size[u_node] += component_size[v_node]
self.set_component(_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
__SCREAMING_SNAKE_CASE : Optional[int] = []
__SCREAMING_SNAKE_CASE : str = 0
__SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes
# A list of components (initialized to all of the nodes)
for node in range(self.m_num_of_nodes ):
self.m_component.update({node: node} )
component_size.append(1 )
__SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes
while num_of_components > 1:
for edge in self.m_edges:
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge
__SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u]
__SCREAMING_SNAKE_CASE : int = self.m_component[v]
if u_component != v_component:
for component in (u_component, v_component):
if (
minimum_weight_edge[component] == -1
or minimum_weight_edge[component][2] > w
):
__SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w]
for edge in minimum_weight_edge:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge
__SCREAMING_SNAKE_CASE : Tuple = self.m_component[u]
__SCREAMING_SNAKE_CASE : int = self.m_component[v]
if u_component != v_component:
mst_weight += w
self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' )
num_of_components -= 1
__SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes
print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' )
def lowerCAmelCase_ ( ):
'''simple docstring'''
if __name__ == "__main__":
import doctest
doctest.testmod()
| 674 | 0 |
import os
from shutil import copyfile
from typing import List, Optional, Tuple
from tokenizers import processors
from ...tokenization_utils import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging
if is_sentencepiece_available():
from .tokenization_nllb import NllbTokenizer
else:
SCREAMING_SNAKE_CASE__ = None
SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE__ = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''}
SCREAMING_SNAKE_CASE__ = {
'''vocab_file''': {
'''facebook/nllb-200-distilled-600M''': (
'''https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model'''
),
},
'''tokenizer_file''': {
'''facebook/nllb-200-distilled-600M''': (
'''https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json'''
),
},
}
SCREAMING_SNAKE_CASE__ = {
'''facebook/nllb-large-en-ro''': 1024,
'''facebook/nllb-200-distilled-600M''': 1024,
}
# fmt: off
SCREAMING_SNAKE_CASE__ = ['''ace_Arab''', '''ace_Latn''', '''acm_Arab''', '''acq_Arab''', '''aeb_Arab''', '''afr_Latn''', '''ajp_Arab''', '''aka_Latn''', '''amh_Ethi''', '''apc_Arab''', '''arb_Arab''', '''ars_Arab''', '''ary_Arab''', '''arz_Arab''', '''asm_Beng''', '''ast_Latn''', '''awa_Deva''', '''ayr_Latn''', '''azb_Arab''', '''azj_Latn''', '''bak_Cyrl''', '''bam_Latn''', '''ban_Latn''', '''bel_Cyrl''', '''bem_Latn''', '''ben_Beng''', '''bho_Deva''', '''bjn_Arab''', '''bjn_Latn''', '''bod_Tibt''', '''bos_Latn''', '''bug_Latn''', '''bul_Cyrl''', '''cat_Latn''', '''ceb_Latn''', '''ces_Latn''', '''cjk_Latn''', '''ckb_Arab''', '''crh_Latn''', '''cym_Latn''', '''dan_Latn''', '''deu_Latn''', '''dik_Latn''', '''dyu_Latn''', '''dzo_Tibt''', '''ell_Grek''', '''eng_Latn''', '''epo_Latn''', '''est_Latn''', '''eus_Latn''', '''ewe_Latn''', '''fao_Latn''', '''pes_Arab''', '''fij_Latn''', '''fin_Latn''', '''fon_Latn''', '''fra_Latn''', '''fur_Latn''', '''fuv_Latn''', '''gla_Latn''', '''gle_Latn''', '''glg_Latn''', '''grn_Latn''', '''guj_Gujr''', '''hat_Latn''', '''hau_Latn''', '''heb_Hebr''', '''hin_Deva''', '''hne_Deva''', '''hrv_Latn''', '''hun_Latn''', '''hye_Armn''', '''ibo_Latn''', '''ilo_Latn''', '''ind_Latn''', '''isl_Latn''', '''ita_Latn''', '''jav_Latn''', '''jpn_Jpan''', '''kab_Latn''', '''kac_Latn''', '''kam_Latn''', '''kan_Knda''', '''kas_Arab''', '''kas_Deva''', '''kat_Geor''', '''knc_Arab''', '''knc_Latn''', '''kaz_Cyrl''', '''kbp_Latn''', '''kea_Latn''', '''khm_Khmr''', '''kik_Latn''', '''kin_Latn''', '''kir_Cyrl''', '''kmb_Latn''', '''kon_Latn''', '''kor_Hang''', '''kmr_Latn''', '''lao_Laoo''', '''lvs_Latn''', '''lij_Latn''', '''lim_Latn''', '''lin_Latn''', '''lit_Latn''', '''lmo_Latn''', '''ltg_Latn''', '''ltz_Latn''', '''lua_Latn''', '''lug_Latn''', '''luo_Latn''', '''lus_Latn''', '''mag_Deva''', '''mai_Deva''', '''mal_Mlym''', '''mar_Deva''', '''min_Latn''', '''mkd_Cyrl''', '''plt_Latn''', '''mlt_Latn''', '''mni_Beng''', '''khk_Cyrl''', '''mos_Latn''', '''mri_Latn''', '''zsm_Latn''', '''mya_Mymr''', '''nld_Latn''', '''nno_Latn''', '''nob_Latn''', '''npi_Deva''', '''nso_Latn''', '''nus_Latn''', '''nya_Latn''', '''oci_Latn''', '''gaz_Latn''', '''ory_Orya''', '''pag_Latn''', '''pan_Guru''', '''pap_Latn''', '''pol_Latn''', '''por_Latn''', '''prs_Arab''', '''pbt_Arab''', '''quy_Latn''', '''ron_Latn''', '''run_Latn''', '''rus_Cyrl''', '''sag_Latn''', '''san_Deva''', '''sat_Beng''', '''scn_Latn''', '''shn_Mymr''', '''sin_Sinh''', '''slk_Latn''', '''slv_Latn''', '''smo_Latn''', '''sna_Latn''', '''snd_Arab''', '''som_Latn''', '''sot_Latn''', '''spa_Latn''', '''als_Latn''', '''srd_Latn''', '''srp_Cyrl''', '''ssw_Latn''', '''sun_Latn''', '''swe_Latn''', '''swh_Latn''', '''szl_Latn''', '''tam_Taml''', '''tat_Cyrl''', '''tel_Telu''', '''tgk_Cyrl''', '''tgl_Latn''', '''tha_Thai''', '''tir_Ethi''', '''taq_Latn''', '''taq_Tfng''', '''tpi_Latn''', '''tsn_Latn''', '''tso_Latn''', '''tuk_Latn''', '''tum_Latn''', '''tur_Latn''', '''twi_Latn''', '''tzm_Tfng''', '''uig_Arab''', '''ukr_Cyrl''', '''umb_Latn''', '''urd_Arab''', '''uzn_Latn''', '''vec_Latn''', '''vie_Latn''', '''war_Latn''', '''wol_Latn''', '''xho_Latn''', '''ydd_Hebr''', '''yor_Latn''', '''yue_Hant''', '''zho_Hans''', '''zho_Hant''', '''zul_Latn''']
class _UpperCamelCase( __lowerCamelCase ):
__SCREAMING_SNAKE_CASE : Tuple = VOCAB_FILES_NAMES
__SCREAMING_SNAKE_CASE : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__SCREAMING_SNAKE_CASE : List[Any] = PRETRAINED_VOCAB_FILES_MAP
__SCREAMING_SNAKE_CASE : Optional[int] = ['''input_ids''', '''attention_mask''']
__SCREAMING_SNAKE_CASE : Union[str, Any] = NllbTokenizer
__SCREAMING_SNAKE_CASE : List[int] = []
__SCREAMING_SNAKE_CASE : List[int] = []
def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Any="<s>" , SCREAMING_SNAKE_CASE__ : Dict="</s>" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="</s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="<s>" , SCREAMING_SNAKE_CASE__ : List[Any]="<unk>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="<pad>" , SCREAMING_SNAKE_CASE__ : Optional[int]="<mask>" , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ):
'''simple docstring'''
__a : Tuple = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else mask_token
__a : Union[str, Any] = legacy_behaviour
super().__init__(
vocab_file=SCREAMING_SNAKE_CASE__ , tokenizer_file=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ , additional_special_tokens=SCREAMING_SNAKE_CASE__ , legacy_behaviour=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
__a : Any = vocab_file
__a : List[str] = False if not self.vocab_file else True
__a : Union[str, Any] = FAIRSEQ_LANGUAGE_CODES.copy()
if additional_special_tokens is not None:
# Only add those special tokens if they are not already there.
_additional_special_tokens.extend(
[t for t in additional_special_tokens if t not in _additional_special_tokens] )
self.add_special_tokens({'additional_special_tokens': _additional_special_tokens} )
__a : List[Any] = {
lang_code: self.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) for lang_code in FAIRSEQ_LANGUAGE_CODES
}
__a : Any = src_lang if src_lang is not None else 'eng_Latn'
__a : Union[str, Any] = self.convert_tokens_to_ids(self._src_lang )
__a : List[Any] = tgt_lang
self.set_src_lang_special_tokens(self._src_lang )
@property
def __lowerCAmelCase ( self : Tuple ):
'''simple docstring'''
return self._src_lang
@src_lang.setter
def __lowerCAmelCase ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str ):
'''simple docstring'''
__a : Union[str, Any] = new_src_lang
self.set_src_lang_special_tokens(self._src_lang )
def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ):
'''simple docstring'''
if token_ids_a is None:
return self.prefix_tokens + token_ids_a + self.suffix_tokens
# We don't expect to process pairs, but leave the pair logic for API consistency
return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens
def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ):
'''simple docstring'''
__a : Dict = [self.sep_token_id]
__a : List[Any] = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
def __lowerCAmelCase ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] , SCREAMING_SNAKE_CASE__ : Optional[str] , **SCREAMING_SNAKE_CASE__ : Any ):
'''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' )
__a : List[Any] = src_lang
__a : Tuple = self(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
__a : int = self.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ )
__a : Optional[int] = tgt_lang_id
return inputs
def __lowerCAmelCase ( self : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str = "eng_Latn" , SCREAMING_SNAKE_CASE__ : Optional[List[str]] = None , SCREAMING_SNAKE_CASE__ : str = "fra_Latn" , **SCREAMING_SNAKE_CASE__ : Optional[int] , ):
'''simple docstring'''
__a : Optional[Any] = src_lang
__a : Optional[int] = tgt_lang
return super().prepare_seqaseq_batch(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
def __lowerCAmelCase ( self : List[Any] ):
'''simple docstring'''
return self.set_src_lang_special_tokens(self.src_lang )
def __lowerCAmelCase ( self : Dict ):
'''simple docstring'''
return self.set_tgt_lang_special_tokens(self.tgt_lang )
def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int ):
'''simple docstring'''
__a : Union[str, Any] = self.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ )
if self.legacy_behaviour:
__a : List[Any] = []
__a : Optional[int] = [self.eos_token_id, self.cur_lang_code]
else:
__a : Dict = [self.cur_lang_code]
__a : Optional[int] = [self.eos_token_id]
__a : str = self.convert_ids_to_tokens(self.prefix_tokens )
__a : int = self.convert_ids_to_tokens(self.suffix_tokens )
__a : str = processors.TemplateProcessing(
single=prefix_tokens_str + ['$A'] + suffix_tokens_str , pair=prefix_tokens_str + ['$A', '$B'] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , )
def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : str ):
'''simple docstring'''
__a : Union[str, Any] = self.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ )
if self.legacy_behaviour:
__a : Optional[Any] = []
__a : int = [self.eos_token_id, self.cur_lang_code]
else:
__a : Optional[int] = [self.cur_lang_code]
__a : List[str] = [self.eos_token_id]
__a : Union[str, Any] = self.convert_ids_to_tokens(self.prefix_tokens )
__a : Dict = self.convert_ids_to_tokens(self.suffix_tokens )
__a : Dict = processors.TemplateProcessing(
single=prefix_tokens_str + ['$A'] + suffix_tokens_str , pair=prefix_tokens_str + ['$A', '$B'] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , )
def __lowerCAmelCase ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ):
'''simple docstring'''
if not self.can_save_slow_tokenizer:
raise ValueError(
'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow '
'tokenizer.' )
if not os.path.isdir(SCREAMING_SNAKE_CASE__ ):
logger.error(f'''Vocabulary path ({save_directory}) should be a directory.''' )
return
__a : Tuple = os.path.join(
SCREAMING_SNAKE_CASE__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ):
copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ )
return (out_vocab_file,)
| 47 |
"""simple docstring"""
import argparse
import pickle
import numpy as np
import torch
from torch import nn
from transformers import ReformerConfig, ReformerModelWithLMHead
from transformers.utils import logging
logging.set_verbosity_info()
def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ):
'''simple docstring'''
assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match'''
__SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ )
if bias is not None:
assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match'''
__SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ )
def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] )
__SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] )
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] )
set_param(
torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , )
def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] )
__SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] )
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] )
__SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] )
set_param(
torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , )
def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = weights[0][0][0]
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] )
__SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] )
set_param(
torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , )
# lsh weights + output
__SCREAMING_SNAKE_CASE : Tuple = weights[0][1]
if len(lowercase_ ) < 4:
set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ )
else:
set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ )
# intermediate weighs
__SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2]
# Chunked Feed Forward
if len(lowercase_ ) == 4:
__SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2]
# layernorm 2
__SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] )
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] )
set_param(
torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , )
# intermediate dense
__SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] )
set_param(
torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , )
# intermediate out
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] )
__SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] )
set_param(
torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , )
def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Dict = torch_model.reformer
# word embeds
__SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] )
set_param(
torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , )
if isinstance(weights[3] , lowercase_ ):
__SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings
for emb_idx in range(len(position_embeddings.weights ) ):
__SCREAMING_SNAKE_CASE : Dict = np.asarray(weights[3][emb_idx][0] )
assert (
position_embeddings.weights[emb_idx].shape == emb_weights.shape
), F'''{position_embeddings[emb_idx]} emb does not match'''
__SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) )
__SCREAMING_SNAKE_CASE : List[Any] = weights[5]
assert len(torch_model_reformer.encoder.layers ) * 4 == len(
lowercase_ ), "HF and trax model do not have the same number of layers"
for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)]
set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ )
# output layer norm
__SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] )
set_param(
torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , )
# output embeddings
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] )
__SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] )
set_param(
torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , )
def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ )
print(F'''Building PyTorch model from configuration: {config}''' )
__SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ )
with open(lowercase_ , '''rb''' ) as f:
__SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights''']
set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size )
# Save pytorch-model
print(F'''Save PyTorch model to {pytorch_dump_path}''' )
torch.save(model.state_dict() , lowercase_ )
if __name__ == "__main__":
_lowerCamelCase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--trax_model_pkl_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.'''
)
parser.add_argument(
'''--config_file''',
default=None,
type=str,
required=True,
help=(
'''The config json file corresponding to the pre-trained Reformer model. \n'''
'''This specifies the model architecture.'''
),
)
parser.add_argument(
'''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
)
_lowerCamelCase = parser.parse_args()
convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
| 674 | 0 |
'''simple docstring'''
import argparse
import copy
def A ( UpperCamelCase_ : str ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase__ = {}
with open(UpperCamelCase_ ) as f:
for line in f:
if line.split()[0] not in dict_of_neighbours:
lowerCAmelCase__ = []
_list.append([line.split()[1], line.split()[2]] )
lowerCAmelCase__ = _list
else:
dict_of_neighbours[line.split()[0]].append(
[line.split()[1], line.split()[2]] )
if line.split()[1] not in dict_of_neighbours:
lowerCAmelCase__ = []
_list.append([line.split()[0], line.split()[2]] )
lowerCAmelCase__ = _list
else:
dict_of_neighbours[line.split()[1]].append(
[line.split()[0], line.split()[2]] )
return dict_of_neighbours
def A ( UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : str ) -> List[str]:
'''simple docstring'''
with open(UpperCamelCase_ ) as f:
lowerCAmelCase__ = f.read(1 )
lowerCAmelCase__ = start_node
lowerCAmelCase__ = []
lowerCAmelCase__ = start_node
lowerCAmelCase__ = 0
while visiting not in first_solution:
lowerCAmelCase__ = 1_00_00
for k in dict_of_neighbours[visiting]:
if int(k[1] ) < int(UpperCamelCase_ ) and k[0] not in first_solution:
lowerCAmelCase__ = k[1]
lowerCAmelCase__ = k[0]
first_solution.append(UpperCamelCase_ )
lowerCAmelCase__ = distance_of_first_solution + int(UpperCamelCase_ )
lowerCAmelCase__ = best_node
first_solution.append(UpperCamelCase_ )
lowerCAmelCase__ = 0
for k in dict_of_neighbours[first_solution[-2]]:
if k[0] == start_node:
break
position += 1
lowerCAmelCase__ = (
distance_of_first_solution
+ int(dict_of_neighbours[first_solution[-2]][position][1] )
- 1_00_00
)
return first_solution, distance_of_first_solution
def A ( UpperCamelCase_ : str , UpperCamelCase_ : Dict ) -> Dict:
'''simple docstring'''
lowerCAmelCase__ = []
for n in solution[1:-1]:
lowerCAmelCase__ = solution.index(UpperCamelCase_ )
for kn in solution[1:-1]:
lowerCAmelCase__ = solution.index(UpperCamelCase_ )
if n == kn:
continue
lowerCAmelCase__ = copy.deepcopy(UpperCamelCase_ )
lowerCAmelCase__ = kn
lowerCAmelCase__ = n
lowerCAmelCase__ = 0
for k in _tmp[:-1]:
lowerCAmelCase__ = _tmp[_tmp.index(UpperCamelCase_ ) + 1]
for i in dict_of_neighbours[k]:
if i[0] == next_node:
lowerCAmelCase__ = distance + int(i[1] )
_tmp.append(UpperCamelCase_ )
if _tmp not in neighborhood_of_solution:
neighborhood_of_solution.append(_tmp )
lowerCAmelCase__ = len(neighborhood_of_solution[0] ) - 1
neighborhood_of_solution.sort(key=lambda UpperCamelCase_ : x[index_of_last_item_in_the_list] )
return neighborhood_of_solution
def A ( UpperCamelCase_ : Dict , UpperCamelCase_ : Any , UpperCamelCase_ : str , UpperCamelCase_ : Dict , UpperCamelCase_ : Tuple ) -> Dict:
'''simple docstring'''
lowerCAmelCase__ = 1
lowerCAmelCase__ = first_solution
lowerCAmelCase__ = []
lowerCAmelCase__ = distance_of_first_solution
lowerCAmelCase__ = solution
while count <= iters:
lowerCAmelCase__ = find_neighborhood(UpperCamelCase_ , UpperCamelCase_ )
lowerCAmelCase__ = 0
lowerCAmelCase__ = neighborhood[index_of_best_solution]
lowerCAmelCase__ = len(UpperCamelCase_ ) - 1
lowerCAmelCase__ = False
while not found:
lowerCAmelCase__ = 0
while i < len(UpperCamelCase_ ):
if best_solution[i] != solution[i]:
lowerCAmelCase__ = best_solution[i]
lowerCAmelCase__ = solution[i]
break
lowerCAmelCase__ = i + 1
if [first_exchange_node, second_exchange_node] not in tabu_list and [
second_exchange_node,
first_exchange_node,
] not in tabu_list:
tabu_list.append([first_exchange_node, second_exchange_node] )
lowerCAmelCase__ = True
lowerCAmelCase__ = best_solution[:-1]
lowerCAmelCase__ = neighborhood[index_of_best_solution][best_cost_index]
if cost < best_cost:
lowerCAmelCase__ = cost
lowerCAmelCase__ = solution
else:
lowerCAmelCase__ = index_of_best_solution + 1
lowerCAmelCase__ = neighborhood[index_of_best_solution]
if len(UpperCamelCase_ ) >= size:
tabu_list.pop(0 )
lowerCAmelCase__ = count + 1
return best_solution_ever, best_cost
def A ( UpperCamelCase_ : Optional[int]=None ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase__ = generate_neighbours(args.File )
lowerCAmelCase__ ,lowerCAmelCase__ = generate_first_solution(
args.File , UpperCamelCase_ )
lowerCAmelCase__ ,lowerCAmelCase__ = tabu_search(
UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , args.Iterations , args.Size , )
print(F"""Best solution: {best_sol}, with total distance: {best_cost}.""" )
if __name__ == "__main__":
UpperCAmelCase__ : Optional[Any] = argparse.ArgumentParser(description="Tabu Search")
parser.add_argument(
"-f",
"--File",
type=str,
help="Path to the file containing the data",
required=True,
)
parser.add_argument(
"-i",
"--Iterations",
type=int,
help="How many iterations the algorithm should perform",
required=True,
)
parser.add_argument(
"-s", "--Size", type=int, help="Size of the tabu list", required=True
)
# Pass the arguments to main method
main(parser.parse_args())
| 48 |
"""simple docstring"""
from typing import Callable, Optional, Union
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_lowerCamelCase = logging.get_logger(__name__)
_lowerCamelCase = {
'''microsoft/xprophetnet-large-wiki100-cased''': (
'''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json'''
),
}
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = '''xlm-prophetnet'''
lowerCamelCase__ = ['''past_key_values''']
lowerCamelCase__ = {
'''num_attention_heads''': '''num_encoder_attention_heads''',
}
def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size
__SCREAMING_SNAKE_CASE : Optional[int] = hidden_size
__SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim
__SCREAMING_SNAKE_CASE : str = num_encoder_layers
__SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads
__SCREAMING_SNAKE_CASE : str = decoder_ffn_dim
__SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers
__SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads
__SCREAMING_SNAKE_CASE : Dict = max_position_embeddings
__SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter)
__SCREAMING_SNAKE_CASE : Any = activation_function
# parameters for xlmprophetnet
__SCREAMING_SNAKE_CASE : List[Any] = ngram
__SCREAMING_SNAKE_CASE : int = num_buckets
__SCREAMING_SNAKE_CASE : List[str] = relative_max_distance
__SCREAMING_SNAKE_CASE : str = disable_ngram_loss
__SCREAMING_SNAKE_CASE : Optional[int] = eps
# 3 Types of Dropout
__SCREAMING_SNAKE_CASE : int = attention_dropout
__SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout
__SCREAMING_SNAKE_CASE : Dict = dropout
__SCREAMING_SNAKE_CASE : Any = use_cache
super().__init__(
pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , )
@property
def SCREAMING_SNAKE_CASE_ ( self :int ):
return self.num_encoder_layers + self.num_decoder_layers
@num_hidden_layers.setter
def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ):
raise NotImplementedError(
'''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and'''
''' `num_decoder_layers`.''' )
| 674 | 0 |
"""simple docstring"""
import os
from typing import Dict, List, Tuple, TypeVar, Union
_lowercase : int = TypeVar('T')
_lowercase : str = Union[List[T], Tuple[T, ...]]
_lowercase : Optional[Any] = Union[T, List[T], Dict[str, T]]
_lowercase : List[Any] = Union[str, bytes, os.PathLike]
| 49 |
"""simple docstring"""
import ast
import os
import re
import shutil
import tempfile
import unittest
from unittest import mock
import torch
from accelerate.test_utils.examples import compare_against_test
from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow
from accelerate.utils import write_basic_config
# DataLoaders built from `test_samples/MRPC` for quick testing
# Should mock `{script_name}.get_dataloaders` via:
# @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders)
_lowerCamelCase = [
'''cross_validation.py''',
'''gradient_accumulation.py''',
'''local_sgd.py''',
'''multi_process_metrics.py''',
'''memory.py''',
'''automatic_gradient_accumulation.py''',
'''fsdp_with_peak_mem_tracking.py''',
'''deepspeed_with_config_support.py''',
'''megatron_lm_gpt_pretraining.py''',
]
class snake_case ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ):
__SCREAMING_SNAKE_CASE : List[str] = None
__SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) )
__SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' )
for item in os.listdir(_lowerCamelCase ):
if item not in EXCLUDE_EXAMPLES:
__SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase )
if os.path.isfile(_lowerCamelCase ) and ".py" in item_path:
with self.subTest(
tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ):
__SCREAMING_SNAKE_CASE : Tuple = compare_against_test(
os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase )
if special_strings is not None:
for string in special_strings:
__SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' )
self.assertEqual(_lowerCamelCase , '''''' )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase )
self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) )
__SCREAMING_SNAKE_CASE : Optional[int] = [
''' ''' * 1_6 + '''{\n\n''',
''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''',
''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''',
''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''',
''' ''' * 2_0 + '''"epoch": epoch,\n\n''',
''' ''' * 1_6 + '''},\n\n''',
''' ''' * 1_6 + '''step=epoch,\n''',
''' ''' * 1_2,
''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''',
]
self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
@mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} )
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = False
@classmethod
def SCREAMING_SNAKE_CASE_ ( cls :Dict ):
super().setUpClass()
__SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp()
__SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' )
write_basic_config(save_location=cls.configPath )
__SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath]
@classmethod
def SCREAMING_SNAKE_CASE_ ( cls :Dict ):
super().tearDownClass()
shutil.rmtree(cls._tmpdir )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
__SCREAMING_SNAKE_CASE : str = f'''
examples/by_feature/checkpointing.py
--checkpointing_steps epoch
--output_dir {self.tmpdir}
'''.split()
run_command(self._launch_args + testargs )
self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
__SCREAMING_SNAKE_CASE : Optional[Any] = f'''
examples/by_feature/checkpointing.py
--checkpointing_steps 1
--output_dir {self.tmpdir}
'''.split()
__SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs )
self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
__SCREAMING_SNAKE_CASE : Optional[int] = f'''
examples/by_feature/checkpointing.py
--resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )}
'''.split()
__SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase )
self.assertNotIn('''epoch 0:''' , _lowerCamelCase )
self.assertIn('''epoch 1:''' , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Optional[int] = f'''
examples/by_feature/checkpointing.py
--resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )}
'''.split()
__SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase )
if torch.cuda.is_available():
__SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count()
else:
__SCREAMING_SNAKE_CASE : Optional[int] = 1
if num_processes > 1:
self.assertNotIn('''epoch 0:''' , _lowerCamelCase )
self.assertIn('''epoch 1:''' , _lowerCamelCase )
else:
self.assertIn('''epoch 0:''' , _lowerCamelCase )
self.assertIn('''epoch 1:''' , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE : Optional[Any] = '''
examples/by_feature/cross_validation.py
--num_folds 2
'''.split()
with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1]
__SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase )
self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 )
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py''']
run_command(self._launch_args + testargs )
@require_trackers
@mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
with tempfile.TemporaryDirectory() as tmpdir:
__SCREAMING_SNAKE_CASE : int = f'''
examples/by_feature/tracking.py
--with_tracking
--project_dir {tmpdir}
'''.split()
run_command(self._launch_args + testargs )
self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py''']
run_command(self._launch_args + testargs )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
__SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py''']
run_command(self._launch_args + testargs )
| 674 | 0 |
'''simple docstring'''
from typing import List, Optional, Union
import numpy as np
from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ....feature_extraction_sequence_utils import SequenceFeatureExtractor
from ....feature_extraction_utils import BatchFeature
from ....file_utils import PaddingStrategy, TensorType
from ....utils import logging
UpperCamelCase : Optional[Any] = logging.get_logger(__name__)
class UpperCamelCase__ (a ):
'''simple docstring'''
_UpperCamelCase = ['input_features', 'attention_mask']
def __init__( self ,_lowerCAmelCase=80 ,_lowerCAmelCase=1_60_00 ,_lowerCAmelCase=0.0 ,_lowerCAmelCase=10 ,_lowerCAmelCase=25 ,_lowerCAmelCase="hamming_window" ,_lowerCAmelCase=3_2768.0 ,_lowerCAmelCase=0.97 ,_lowerCAmelCase=1.0 ,_lowerCAmelCase=True ,_lowerCAmelCase=True ,_lowerCAmelCase=False ,**_lowerCAmelCase ,):
super().__init__(feature_size=_lowerCAmelCase ,sampling_rate=_lowerCAmelCase ,padding_value=_lowerCAmelCase ,**_lowerCAmelCase )
lowerCamelCase__ = feature_size
lowerCamelCase__ = sampling_rate
lowerCamelCase__ = padding_value
lowerCamelCase__ = hop_length
lowerCamelCase__ = win_length
lowerCamelCase__ = frame_signal_scale
lowerCamelCase__ = preemphasis_coeff
lowerCamelCase__ = mel_floor
lowerCamelCase__ = normalize_means
lowerCamelCase__ = normalize_vars
lowerCamelCase__ = win_function
lowerCamelCase__ = return_attention_mask
lowerCamelCase__ = win_length * sampling_rate // 10_00
lowerCamelCase__ = hop_length * sampling_rate // 10_00
lowerCamelCase__ = optimal_fft_length(self.sample_size )
lowerCamelCase__ = (self.n_fft // 2) + 1
def UpperCamelCase_ ( self ,_lowerCAmelCase ):
if self.win_function == "hamming_window":
lowerCamelCase__ = window_function(window_length=self.sample_size ,name=self.win_function ,periodic=_lowerCAmelCase )
else:
lowerCamelCase__ = window_function(window_length=self.sample_size ,name=self.win_function )
lowerCamelCase__ = 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__ = spectrogram(
one_waveform * self.frame_signal_scale ,window=_lowerCAmelCase ,frame_length=self.sample_size ,hop_length=self.sample_stride ,fft_length=self.n_fft ,center=_lowerCAmelCase ,preemphasis=self.preemphasis_coeff ,mel_filters=_lowerCAmelCase ,mel_floor=self.mel_floor ,log_mel="""log""" ,)
return msfc_features.T
def UpperCamelCase_ ( self ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ):
# make sure we normalize float32 arrays
if self.normalize_means:
lowerCamelCase__ = x[:input_length].mean(axis=0 )
lowerCamelCase__ = np.subtract(_lowerCAmelCase ,_lowerCAmelCase )
if self.normalize_vars:
lowerCamelCase__ = x[:input_length].std(axis=0 )
lowerCamelCase__ = np.divide(_lowerCAmelCase ,_lowerCAmelCase )
if input_length < x.shape[0]:
lowerCamelCase__ = padding_value
# make sure array is in float32
lowerCamelCase__ = x.astype(np.floataa )
return x
def UpperCamelCase_ ( self ,_lowerCAmelCase ,_lowerCAmelCase = None ):
lowerCamelCase__ = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features]
return [self._normalize_one(_lowerCAmelCase ,_lowerCAmelCase ,self.padding_value ) for x, n in zip(_lowerCAmelCase ,_lowerCAmelCase )]
def __call__( self ,_lowerCAmelCase ,_lowerCAmelCase = False ,_lowerCAmelCase = None ,_lowerCAmelCase = False ,_lowerCAmelCase = None ,_lowerCAmelCase = None ,_lowerCAmelCase = None ,_lowerCAmelCase = None ,**_lowerCAmelCase ,):
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__ = isinstance(_lowerCAmelCase ,np.ndarray ) and len(raw_speech.shape ) > 1
if is_batched_numpy and len(raw_speech.shape ) > 2:
raise ValueError(F'''Only mono-channel audio is supported for input to {self}''' )
lowerCamelCase__ = is_batched_numpy or (
isinstance(_lowerCAmelCase ,(list, tuple) ) and (isinstance(raw_speech[0] ,(np.ndarray, tuple, list) ))
)
if is_batched:
lowerCamelCase__ = [np.asarray(_lowerCAmelCase ,dtype=np.floataa ) for speech in raw_speech]
elif not is_batched and not isinstance(_lowerCAmelCase ,np.ndarray ):
lowerCamelCase__ = np.asarray(_lowerCAmelCase ,dtype=np.floataa )
elif isinstance(_lowerCAmelCase ,np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ):
lowerCamelCase__ = raw_speech.astype(np.floataa )
# always return batch
if not is_batched:
lowerCamelCase__ = [raw_speech]
# extract fbank features
lowerCamelCase__ = [self._extract_mfsc_features(_lowerCAmelCase ) for one_waveform in raw_speech]
# convert into correct format for padding
lowerCamelCase__ = BatchFeature({"""input_features""": features} )
lowerCamelCase__ = self.pad(
_lowerCAmelCase ,padding=_lowerCAmelCase ,max_length=_lowerCAmelCase ,truncation=_lowerCAmelCase ,pad_to_multiple_of=_lowerCAmelCase ,return_attention_mask=_lowerCAmelCase ,**_lowerCAmelCase ,)
# make sure list is in array format
lowerCamelCase__ = padded_inputs.get("""input_features""" )
if isinstance(input_features[0] ,_lowerCAmelCase ):
lowerCamelCase__ = [np.asarray(_lowerCAmelCase ,dtype=np.floataa ) for feature in input_features]
lowerCamelCase__ = padded_inputs.get("""attention_mask""" )
if attention_mask is not None:
lowerCamelCase__ = [np.asarray(_lowerCAmelCase ,dtype=np.intaa ) for array in attention_mask]
if self.normalize_means or self.normalize_vars:
lowerCamelCase__ = (
np.array(_lowerCAmelCase ,dtype=np.intaa )
if self._get_padding_strategies(_lowerCAmelCase ,max_length=_lowerCAmelCase ) is not PaddingStrategy.DO_NOT_PAD
and padding
else None
)
lowerCamelCase__ = self.normalize(
padded_inputs["""input_features"""] ,attention_mask=_lowerCAmelCase )
if return_tensors is not None:
lowerCamelCase__ = padded_inputs.convert_to_tensors(_lowerCAmelCase )
return padded_inputs
| 50 |
"""simple docstring"""
import argparse
import logging
import os
import time
import timeit
import datasets
import numpy as np
import pycuda.autoinit # noqa: F401
import pycuda.driver as cuda
import tensorrt as trt
import torch
from absl import logging as absl_logging
from accelerate import Accelerator
from datasets import load_dataset, load_metric
from torch.utils.data import DataLoader
from utils_qa import postprocess_qa_predictions
import transformers
from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed
from transformers.trainer_pt_utils import nested_concat, nested_truncate
_lowerCamelCase = trt.Logger(trt.Logger.WARNING)
_lowerCamelCase = absl_logging.get_absl_logger()
absl_logger.setLevel(logging.WARNING)
_lowerCamelCase = logging.getLogger(__name__)
_lowerCamelCase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--onnx_model_path''',
default=None,
type=str,
required=True,
help='''Path to ONNX model: ''',
)
parser.add_argument(
'''--output_dir''',
default=None,
type=str,
required=True,
help='''The output directory where the model checkpoints and predictions will be written.''',
)
# Other parameters
parser.add_argument(
'''--tokenizer_name''',
default='''''',
type=str,
required=True,
help='''Pretrained tokenizer name or path if not the same as model_name''',
)
parser.add_argument(
'''--version_2_with_negative''',
action='''store_true''',
help='''If true, the SQuAD examples contain some that do not have an answer.''',
)
parser.add_argument(
'''--null_score_diff_threshold''',
type=float,
default=0.0,
help='''If null_score - best_non_null is greater than the threshold predict null.''',
)
parser.add_argument(
'''--max_seq_length''',
default=3_84,
type=int,
help=(
'''The maximum total input sequence length after WordPiece tokenization. Sequences '''
'''longer than this will be truncated, and sequences shorter than this will be padded.'''
),
)
parser.add_argument(
'''--doc_stride''',
default=1_28,
type=int,
help='''When splitting up a long document into chunks, how much stride to take between chunks.''',
)
parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''')
parser.add_argument(
'''--n_best_size''',
default=20,
type=int,
help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''',
)
parser.add_argument(
'''--max_answer_length''',
default=30,
type=int,
help=(
'''The maximum length of an answer that can be generated. This is needed because the start '''
'''and end predictions are not conditioned on one another.'''
),
)
parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''')
parser.add_argument(
'''--dataset_name''',
type=str,
default=None,
required=True,
help='''The name of the dataset to use (via the datasets library).''',
)
parser.add_argument(
'''--dataset_config_name''',
type=str,
default=None,
help='''The configuration name of the dataset to use (via the datasets library).''',
)
parser.add_argument(
'''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.'''
)
parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''')
parser.add_argument(
'''--fp16''',
action='''store_true''',
help='''Whether to use 16-bit (mixed) precision instead of 32-bit''',
)
parser.add_argument(
'''--int8''',
action='''store_true''',
help='''Whether to use INT8''',
)
_lowerCamelCase = parser.parse_args()
if args.tokenizer_name:
_lowerCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True)
else:
raise ValueError(
'''You are instantiating a new tokenizer from scratch. This is not supported by this script.'''
'''You can do it from another script, save it, and load it from here, using --tokenizer_name.'''
)
logger.info('''Training/evaluation parameters %s''', args)
_lowerCamelCase = args.per_device_eval_batch_size
_lowerCamelCase = (args.eval_batch_size, args.max_seq_length)
# TRT Engine properties
_lowerCamelCase = True
_lowerCamelCase = '''temp_engine/bert-fp32.engine'''
if args.fpaa:
_lowerCamelCase = '''temp_engine/bert-fp16.engine'''
if args.inta:
_lowerCamelCase = '''temp_engine/bert-int8.engine'''
# import ONNX file
if not os.path.exists('''temp_engine'''):
os.makedirs('''temp_engine''')
_lowerCamelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser(
network, TRT_LOGGER
) as parser:
with open(args.onnx_model_path, '''rb''') as model:
if not parser.parse(model.read()):
for error in range(parser.num_errors):
print(parser.get_error(error))
# Query input names and shapes from parsed TensorRT network
_lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)]
_lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"]
with builder.create_builder_config() as config:
_lowerCamelCase = 1 << 50
if STRICT_TYPES:
config.set_flag(trt.BuilderFlag.STRICT_TYPES)
if args.fpaa:
config.set_flag(trt.BuilderFlag.FPaa)
if args.inta:
config.set_flag(trt.BuilderFlag.INTa)
_lowerCamelCase = builder.create_optimization_profile()
config.add_optimization_profile(profile)
for i in range(len(input_names)):
profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE)
_lowerCamelCase = builder.build_engine(network, config)
# serialize_engine and store in file (can be directly loaded and deserialized):
with open(engine_name, '''wb''') as f:
f.write(engine.serialize())
def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa )
# Copy inputs
cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase_ )
cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase_ )
cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase_ )
# start time
__SCREAMING_SNAKE_CASE : Tuple = time.time()
# Run inference
context.execute_async(
bindings=[int(lowercase_ ) for d_inp in d_inputs] + [int(lowercase_ ), int(lowercase_ )] , stream_handle=stream.handle )
# Transfer predictions back from GPU
cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ )
cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ )
# Synchronize the stream and take time
stream.synchronize()
# end time
__SCREAMING_SNAKE_CASE : List[str] = time.time()
__SCREAMING_SNAKE_CASE : int = end_time - start_time
__SCREAMING_SNAKE_CASE : int = (h_outputa, h_outputa)
# print(outputs)
return outputs, infer_time
# Initialize the accelerator. We will let the accelerator handle device placement for us in this example.
_lowerCamelCase = Accelerator()
# Make one log on every process with the configuration for debugging.
logging.basicConfig(
format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''',
datefmt='''%m/%d/%Y %H:%M:%S''',
level=logging.INFO,
)
# Setup logging, we only want one process per machine to log things on the screen.
# accelerator.is_local_main_process is only True for one process per machine.
logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR)
if accelerator.is_local_main_process:
datasets.utils.logging.set_verbosity_warning()
transformers.utils.logging.set_verbosity_info()
else:
datasets.utils.logging.set_verbosity_error()
transformers.utils.logging.set_verbosity_error()
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
# (the dataset will be downloaded automatically from the datasets Hub).
#
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
# 'text' is found. You can easily tweak this behavior (see below).
if args.dataset_name is not None:
# Downloading and loading a dataset from the hub.
_lowerCamelCase = load_dataset(args.dataset_name, args.dataset_config_name)
else:
raise ValueError('''Evaluation requires a dataset name''')
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
# Preprocessing the datasets.
# Preprocessing is slighlty different for training and evaluation.
_lowerCamelCase = raw_datasets['''validation'''].column_names
_lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0]
_lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1]
_lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2]
# Padding side determines if we do (question|context) or (context|question).
_lowerCamelCase = tokenizer.padding_side == '''right'''
if args.max_seq_length > tokenizer.model_max_length:
logger.warning(
f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the'
f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.'
)
_lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length)
def lowerCAmelCase_ ( lowercase_ : Tuple ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = [q.lstrip() for q in examples[question_column_name]]
# Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results
# in one example possible giving several features when a context is long, each of those features having a
# context that overlaps a bit the context of the previous feature.
__SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer(
examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=lowercase_ , stride=args.doc_stride , return_overflowing_tokens=lowercase_ , return_offsets_mapping=lowercase_ , padding='''max_length''' , )
# Since one example might give us several features if it has a long context, we need a map from a feature to
# its corresponding example. This key gives us just that.
__SCREAMING_SNAKE_CASE : Optional[int] = tokenized_examples.pop('''overflow_to_sample_mapping''' )
# For evaluation, we will need to convert our predictions to substrings of the context, so we keep the
# corresponding example_id and we will store the offset mappings.
__SCREAMING_SNAKE_CASE : Any = []
for i in range(len(tokenized_examples['''input_ids'''] ) ):
# Grab the sequence corresponding to that example (to know what is the context and what is the question).
__SCREAMING_SNAKE_CASE : int = tokenized_examples.sequence_ids(lowercase_ )
__SCREAMING_SNAKE_CASE : str = 1 if pad_on_right else 0
# One example can give several spans, this is the index of the example containing this span of text.
__SCREAMING_SNAKE_CASE : str = sample_mapping[i]
tokenized_examples["example_id"].append(examples['''id'''][sample_index] )
# Set to None the offset_mapping that are not part of the context so it's easy to determine if a token
# position is part of the context or not.
__SCREAMING_SNAKE_CASE : List[str] = [
(o if sequence_ids[k] == context_index else None)
for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] )
]
return tokenized_examples
_lowerCamelCase = raw_datasets['''validation''']
# Validation Feature Creation
_lowerCamelCase = eval_examples.map(
prepare_validation_features,
batched=True,
num_proc=args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not args.overwrite_cache,
desc='''Running tokenizer on validation dataset''',
)
_lowerCamelCase = default_data_collator
_lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping'''])
_lowerCamelCase = DataLoader(
eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size
)
def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Tuple = postprocess_qa_predictions(
examples=lowercase_ , features=lowercase_ , predictions=lowercase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase_ , )
# Format the result to the format the metric expects.
if args.version_2_with_negative:
__SCREAMING_SNAKE_CASE : Union[str, Any] = [
{'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items()
]
else:
__SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()]
__SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples]
return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ )
_lowerCamelCase = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''')
# Evaluation!
logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path)
with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine(
f.read()
) as engine, engine.create_execution_context() as context:
# setup for TRT inferrence
for i in range(len(input_names)):
context.set_binding_shape(i, INPUT_SHAPE)
assert context.all_binding_shapes_specified
def lowerCAmelCase_ ( lowercase_ : Any ):
'''simple docstring'''
return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize
# Allocate device memory for inputs and outputs.
_lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)]
# Allocate output buffer
_lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa)
_lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa)
_lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes)
_lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes)
# Create a stream in which to copy inputs/outputs and run inference.
_lowerCamelCase = cuda.Stream()
# Evaluation
logger.info('''***** Running Evaluation *****''')
logger.info(f' Num examples = {len(eval_dataset)}')
logger.info(f' Batch size = {args.per_device_eval_batch_size}')
_lowerCamelCase = 0.0
_lowerCamelCase = 0
_lowerCamelCase = timeit.default_timer()
_lowerCamelCase = None
for step, batch in enumerate(eval_dataloader):
_lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream)
total_time += infer_time
niter += 1
_lowerCamelCase , _lowerCamelCase = outputs
_lowerCamelCase = torch.tensor(start_logits)
_lowerCamelCase = torch.tensor(end_logits)
# necessary to pad predictions and labels for being gathered
_lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00)
_lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00)
_lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy())
_lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00)
if all_preds is not None:
_lowerCamelCase = nested_truncate(all_preds, len(eval_dataset))
_lowerCamelCase = timeit.default_timer() - start_time
logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset))
# Inference time from TRT
logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 10_00 / niter))
logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00))
logger.info('''Total Number of Inference = %d''', niter)
_lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds)
_lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids)
logger.info(f'Evaluation metrics: {eval_metric}')
| 674 | 0 |
'''simple docstring'''
from packaging import version
from .import_utils import is_accelerate_available
if is_accelerate_available():
import accelerate
def __snake_case ( SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> Any:
"""simple docstring"""
if not is_accelerate_available():
return method
UpperCAmelCase = version.parse(accelerate.__version__ ).base_version
if version.parse(SCREAMING_SNAKE_CASE_ ) < version.parse('''0.17.0''' ):
return method
def wrapper(self : Tuple , *SCREAMING_SNAKE_CASE_ : List[Any] , **SCREAMING_SNAKE_CASE_ : Any ):
if hasattr(self , '''_hf_hook''' ) and hasattr(self._hf_hook , '''pre_forward''' ):
self._hf_hook.pre_forward(self )
return method(self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
return wrapper
| 51 |
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import is_tf_available, is_torch_available
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow
if is_tf_available():
from transformers import (
AutoConfig,
BertConfig,
GPTaConfig,
TaConfig,
TFAutoModel,
TFAutoModelForCausalLM,
TFAutoModelForMaskedLM,
TFAutoModelForPreTraining,
TFAutoModelForQuestionAnswering,
TFAutoModelForSeqaSeqLM,
TFAutoModelForSequenceClassification,
TFAutoModelWithLMHead,
TFBertForMaskedLM,
TFBertForPreTraining,
TFBertForQuestionAnswering,
TFBertForSequenceClassification,
TFBertModel,
TFGPTaLMHeadModel,
TFRobertaForMaskedLM,
TFTaForConditionalGeneration,
)
from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST
from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST
from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST
if is_torch_available():
from transformers import (
AutoModel,
AutoModelForCausalLM,
AutoModelForMaskedLM,
AutoModelForPreTraining,
AutoModelForQuestionAnswering,
AutoModelForSeqaSeqLM,
AutoModelForSequenceClassification,
AutoModelWithLMHead,
BertForMaskedLM,
BertForPreTraining,
BertForQuestionAnswering,
BertForSequenceClassification,
BertModel,
GPTaLMHeadModel,
RobertaForMaskedLM,
TaForConditionalGeneration,
)
@is_pt_tf_cross_test
class snake_case ( unittest.TestCase ):
@slow
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
__SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
__SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Any ):
for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :int ):
for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
__SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
__SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
| 674 | 0 |
"""simple docstring"""
# NOTE: This file is deprecated and will be removed in a future version.
# It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works
from ...utils import deprecate
from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401
from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401
deprecate(
'''stable diffusion controlnet''',
'''0.22.0''',
'''Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.''',
standard_warn=False,
stacklevel=3,
) | 52 |
"""simple docstring"""
import os
import re
import warnings
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
if TYPE_CHECKING:
from ...tokenization_utils_base import TextInput
from ...utils import logging
_lowerCamelCase = logging.get_logger(__name__)
_lowerCamelCase = {'''vocab_file''': '''spiece.model'''}
_lowerCamelCase = {
'''vocab_file''': {
'''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''',
'''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''',
'''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''',
'''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''',
'''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''',
}
}
# TODO(PVP) - this should be removed in Transformers v5
_lowerCamelCase = {
'''t5-small''': 5_12,
'''t5-base''': 5_12,
'''t5-large''': 5_12,
'''t5-3b''': 5_12,
'''t5-11b''': 5_12,
}
_lowerCamelCase = '''▁'''
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = VOCAB_FILES_NAMES
lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP
lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowerCamelCase__ = ['''input_ids''', '''attention_mask''']
def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ):
# Add extra_ids to the special token list
if extra_ids > 0 and additional_special_tokens is None:
__SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )]
elif extra_ids > 0 and additional_special_tokens is not None:
# Check that we have the right number of extra_id special tokens
__SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) )
if extra_tokens != extra_ids:
raise ValueError(
f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are'''
''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids'''
''' tokens''' )
if legacy:
logger.warning_once(
f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to'''
''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' )
__SCREAMING_SNAKE_CASE : Optional[Any] = legacy
__SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , )
__SCREAMING_SNAKE_CASE : Tuple = vocab_file
__SCREAMING_SNAKE_CASE : List[str] = extra_ids
__SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(_lowerCamelCase )
@staticmethod
def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ):
if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes:
__SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path]
if init_max_model_length is not None and init_max_model_length != max_model_length:
return init_max_model_length
elif init_max_model_length is None:
warnings.warn(
'''This tokenizer was incorrectly instantiated with a model max length of'''
f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this'''
''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with'''
''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on'''
f''' {pretrained_model_name_or_path} automatically truncating your input to'''
f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences'''
f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with'''
''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please'''
''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , )
return max_model_length
@property
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
return self.sp_model.get_piece_size() + self._extra_ids
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ):
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase )
# normal case: some special tokens
if token_ids_a is None:
return ([0] * len(_lowerCamelCase )) + [1]
return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1]
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
return list(
set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()]
def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ):
if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id:
warnings.warn(
f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated'''
''' eos tokens being added.''' )
return token_ids
else:
return token_ids + [self.eos_token_id]
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ):
__SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id]
if token_ids_a is None:
return len(token_ids_a + eos ) * [0]
return len(token_ids_a + eos + token_ids_a + eos ) * [0]
def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ):
__SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase )
if token_ids_a is None:
return token_ids_a
else:
__SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase )
return token_ids_a + token_ids_a
def __getstate__( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Any = self.__dict__.copy()
__SCREAMING_SNAKE_CASE : List[str] = None
return state
def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ):
__SCREAMING_SNAKE_CASE : Tuple = d
# for backward compatibility
if not hasattr(self , '''sp_model_kwargs''' ):
__SCREAMING_SNAKE_CASE : Optional[int] = {}
__SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ):
# Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at
# the beginning of the text
if not self.legacy:
__SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' )
return super().tokenize(_lowerCamelCase , **_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ):
if not self.legacy:
__SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase )
if is_first:
__SCREAMING_SNAKE_CASE : str = text[1:]
__SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase )
if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ):
__SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:]
return tokens
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ):
if token.startswith('''<extra_id_''' ):
__SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) )
return self.vocab_size - num - 1
return self.sp_model.piece_to_id(_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ):
if index < self.sp_model.get_piece_size():
__SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase )
else:
__SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>'''
return token
def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ):
__SCREAMING_SNAKE_CASE : str = []
__SCREAMING_SNAKE_CASE : Dict = ''''''
__SCREAMING_SNAKE_CASE : Dict = False
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
if not prev_is_special:
out_string += " "
out_string += self.sp_model.decode(_lowerCamelCase ) + token
__SCREAMING_SNAKE_CASE : List[str] = True
__SCREAMING_SNAKE_CASE : str = []
else:
current_sub_tokens.append(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = False
out_string += self.sp_model.decode(_lowerCamelCase )
return out_string.strip()
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ):
if not os.path.isdir(_lowerCamelCase ):
logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' )
return
__SCREAMING_SNAKE_CASE : List[str] = os.path.join(
_lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , _lowerCamelCase )
elif not os.path.isfile(self.vocab_file ):
with open(_lowerCamelCase , '''wb''' ) as fi:
__SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto()
fi.write(_lowerCamelCase )
return (out_vocab_file,)
| 674 | 0 |
import os
import pytest
import yaml
from datasets.features.features import Features, Value
from datasets.info import DatasetInfo, DatasetInfosDict
@pytest.mark.parametrize(
'files', [
['full:README.md', 'dataset_infos.json'],
['empty:README.md', 'dataset_infos.json'],
['dataset_infos.json'],
['full:README.md'],
], )
def a_ ( lowerCAmelCase_ : Union[str, Any], lowerCAmelCase_ : Optional[int] ):
__lowerCAmelCase = tmp_path_factory.mktemp('dset_infos_dir' )
if "full:README.md" in files:
with open(dataset_infos_dir / 'README.md', 'w' ) as f:
f.write('---\ndataset_info:\n dataset_size: 42\n---' )
if "empty:README.md" in files:
with open(dataset_infos_dir / 'README.md', 'w' ) as f:
f.write('' )
# we want to support dataset_infos.json for backward compatibility
if "dataset_infos.json" in files:
with open(dataset_infos_dir / 'dataset_infos.json', 'w' ) as f:
f.write('{"default": {"dataset_size": 42}}' )
__lowerCAmelCase = DatasetInfosDict.from_directory(lowerCAmelCase_ )
assert dataset_infos
assert dataset_infos["default"].dataset_size == 42
@pytest.mark.parametrize(
'dataset_info', [
DatasetInfo(),
DatasetInfo(
description='foo', features=Features({'a': Value('int32' )} ), builder_name='builder', config_name='config', version='1.0.0', splits=[{'name': 'train'}], download_size=42, ),
], )
def a_ ( lowerCAmelCase_ : Union[str, Any], lowerCAmelCase_ : DatasetInfo ):
__lowerCAmelCase = str(lowerCAmelCase_ )
dataset_info.write_to_directory(lowerCAmelCase_ )
__lowerCAmelCase = DatasetInfo.from_directory(lowerCAmelCase_ )
assert dataset_info == reloaded
assert os.path.exists(os.path.join(lowerCAmelCase_, 'dataset_info.json' ) )
def a_ ( ):
__lowerCAmelCase = DatasetInfo(
description='foo', citation='bar', homepage='https://foo.bar', license='CC0', features=Features({'a': Value('int32' )} ), post_processed={}, supervised_keys=(), task_templates=[], builder_name='builder', config_name='config', version='1.0.0', splits=[{'name': 'train', 'num_examples': 42}], download_checksums={}, download_size=1337, post_processing_size=442, dataset_size=1234, size_in_bytes=1337 + 442 + 1234, )
__lowerCAmelCase = dataset_info._to_yaml_dict()
assert sorted(lowerCAmelCase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML )
for key in DatasetInfo._INCLUDED_INFO_IN_YAML:
assert key in dataset_info_yaml_dict
assert isinstance(dataset_info_yaml_dict[key], (list, dict, int, str) )
__lowerCAmelCase = yaml.safe_dump(lowerCAmelCase_ )
__lowerCAmelCase = yaml.safe_load(lowerCAmelCase_ )
assert dataset_info_yaml_dict == reloaded
def a_ ( ):
__lowerCAmelCase = DatasetInfo()
__lowerCAmelCase = dataset_info._to_yaml_dict()
assert dataset_info_yaml_dict == {}
@pytest.mark.parametrize(
'dataset_infos_dict', [
DatasetInfosDict(),
DatasetInfosDict({'default': DatasetInfo()} ),
DatasetInfosDict({'my_config_name': DatasetInfo()} ),
DatasetInfosDict(
{
'default': DatasetInfo(
description='foo', features=Features({'a': Value('int32' )} ), builder_name='builder', config_name='config', version='1.0.0', splits=[{'name': 'train'}], download_size=42, )
} ),
DatasetInfosDict(
{
'v1': DatasetInfo(dataset_size=42 ),
'v2': DatasetInfo(dataset_size=1337 ),
} ),
], )
def a_ ( lowerCAmelCase_ : int, lowerCAmelCase_ : DatasetInfosDict ):
__lowerCAmelCase = str(lowerCAmelCase_ )
dataset_infos_dict.write_to_directory(lowerCAmelCase_ )
__lowerCAmelCase = DatasetInfosDict.from_directory(lowerCAmelCase_ )
# the config_name of the dataset_infos_dict take over the attribute
for config_name, dataset_info in dataset_infos_dict.items():
__lowerCAmelCase = config_name
# the yaml representation doesn't include fields like description or citation
# so we just test that we can recover what we can from the yaml
__lowerCAmelCase = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() )
assert dataset_infos_dict == reloaded
if dataset_infos_dict:
assert os.path.exists(os.path.join(lowerCAmelCase_, 'README.md' ) )
| 53 |
"""simple docstring"""
import os
import pytest
import yaml
from datasets.features.features import Features, Value
from datasets.info import DatasetInfo, DatasetInfosDict
@pytest.mark.parametrize(
'''files''' , [
['''full:README.md''', '''dataset_infos.json'''],
['''empty:README.md''', '''dataset_infos.json'''],
['''dataset_infos.json'''],
['''full:README.md'''],
] , )
def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' )
if "full:README.md" in files:
with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f:
f.write('''---\ndataset_info:\n dataset_size: 42\n---''' )
if "empty:README.md" in files:
with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f:
f.write('''''' )
# we want to support dataset_infos.json for backward compatibility
if "dataset_infos.json" in files:
with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f:
f.write('''{"default": {"dataset_size": 42}}''' )
__SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ )
assert dataset_infos
assert dataset_infos["default"].dataset_size == 42
@pytest.mark.parametrize(
'''dataset_info''' , [
DatasetInfo(),
DatasetInfo(
description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ),
] , )
def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ )
dataset_info.write_to_directory(lowercase_ )
__SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ )
assert dataset_info == reloaded
assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) )
def lowerCAmelCase_ ( ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Tuple = DatasetInfo(
description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , )
__SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict()
assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML )
for key in DatasetInfo._INCLUDED_INFO_IN_YAML:
assert key in dataset_info_yaml_dict
assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) )
__SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ )
__SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ )
assert dataset_info_yaml_dict == reloaded
def lowerCAmelCase_ ( ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo()
__SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict()
assert dataset_info_yaml_dict == {}
@pytest.mark.parametrize(
'''dataset_infos_dict''' , [
DatasetInfosDict(),
DatasetInfosDict({'''default''': DatasetInfo()} ),
DatasetInfosDict({'''my_config_name''': DatasetInfo()} ),
DatasetInfosDict(
{
'''default''': DatasetInfo(
description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , )
} ),
DatasetInfosDict(
{
'''v1''': DatasetInfo(dataset_size=42 ),
'''v2''': DatasetInfo(dataset_size=1337 ),
} ),
] , )
def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ )
dataset_infos_dict.write_to_directory(lowercase_ )
__SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ )
# the config_name of the dataset_infos_dict take over the attribute
for config_name, dataset_info in dataset_infos_dict.items():
__SCREAMING_SNAKE_CASE : Optional[int] = config_name
# the yaml representation doesn't include fields like description or citation
# so we just test that we can recover what we can from the yaml
__SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() )
assert dataset_infos_dict == reloaded
if dataset_infos_dict:
assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
| 674 | 0 |
from typing import Optional, Union
import torch
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_mobilenet_va import MobileNetVaConfig
__lowercase : Tuple =logging.get_logger(__name__)
# General docstring
__lowercase : Dict ="""MobileNetV1Config"""
# Base docstring
__lowercase : Union[str, Any] ="""google/mobilenet_v1_1.0_224"""
__lowercase : str =[1, 1024, 7, 7]
# Image classification docstring
__lowercase : str ="""google/mobilenet_v1_1.0_224"""
__lowercase : List[Any] ="""tabby, tabby cat"""
__lowercase : Dict =[
"""google/mobilenet_v1_1.0_224""",
"""google/mobilenet_v1_0.75_192""",
# See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
]
def a__ ( lowercase__ , lowercase__ , lowercase__=None ):
'''simple docstring'''
UpperCAmelCase_ ={}
if isinstance(lowercase__ , lowercase__ ):
UpperCAmelCase_ =model.mobilenet_va
else:
UpperCAmelCase_ =model
UpperCAmelCase_ ="MobilenetV1/Conv2d_0/"
UpperCAmelCase_ =backbone.conv_stem.convolution.weight
UpperCAmelCase_ =backbone.conv_stem.normalization.bias
UpperCAmelCase_ =backbone.conv_stem.normalization.weight
UpperCAmelCase_ =backbone.conv_stem.normalization.running_mean
UpperCAmelCase_ =backbone.conv_stem.normalization.running_var
for i in range(1_3 ):
UpperCAmelCase_ =i + 1
UpperCAmelCase_ =i * 2
UpperCAmelCase_ =backbone.layer[pt_index]
UpperCAmelCase_ =F'MobilenetV1/Conv2d_{tf_index}_depthwise/'
UpperCAmelCase_ =pointer.convolution.weight
UpperCAmelCase_ =pointer.normalization.bias
UpperCAmelCase_ =pointer.normalization.weight
UpperCAmelCase_ =pointer.normalization.running_mean
UpperCAmelCase_ =pointer.normalization.running_var
UpperCAmelCase_ =backbone.layer[pt_index + 1]
UpperCAmelCase_ =F'MobilenetV1/Conv2d_{tf_index}_pointwise/'
UpperCAmelCase_ =pointer.convolution.weight
UpperCAmelCase_ =pointer.normalization.bias
UpperCAmelCase_ =pointer.normalization.weight
UpperCAmelCase_ =pointer.normalization.running_mean
UpperCAmelCase_ =pointer.normalization.running_var
if isinstance(lowercase__ , lowercase__ ):
UpperCAmelCase_ ="MobilenetV1/Logits/Conv2d_1c_1x1/"
UpperCAmelCase_ =model.classifier.weight
UpperCAmelCase_ =model.classifier.bias
return tf_to_pt_map
def a__ ( lowercase__ , lowercase__ , lowercase__ ):
'''simple docstring'''
try:
import numpy as np
import tensorflow as tf
except ImportError:
logger.error(
"Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see "
"https://www.tensorflow.org/install/ for installation instructions." )
raise
# Load weights from TF model
UpperCAmelCase_ =tf.train.list_variables(lowercase__ )
UpperCAmelCase_ ={}
for name, shape in init_vars:
logger.info(F'Loading TF weight {name} with shape {shape}' )
UpperCAmelCase_ =tf.train.load_variable(lowercase__ , lowercase__ )
UpperCAmelCase_ =array
# Build TF to PyTorch weights loading map
UpperCAmelCase_ =_build_tf_to_pytorch_map(lowercase__ , lowercase__ , lowercase__ )
for name, pointer in tf_to_pt_map.items():
logger.info(F'Importing {name}' )
if name not in tf_weights:
logger.info(F'{name} not in tf pre-trained weights, skipping' )
continue
UpperCAmelCase_ =tf_weights[name]
if "depthwise_weights" in name:
logger.info("Transposing depthwise" )
UpperCAmelCase_ =np.transpose(lowercase__ , (2, 3, 0, 1) )
elif "weights" in name:
logger.info("Transposing" )
if len(pointer.shape ) == 2: # copying into linear layer
UpperCAmelCase_ =array.squeeze().transpose()
else:
UpperCAmelCase_ =np.transpose(lowercase__ , (3, 2, 0, 1) )
if pointer.shape != array.shape:
raise ValueError(F'Pointer shape {pointer.shape} and array shape {array.shape} mismatched' )
logger.info(F'Initialize PyTorch weight {name} {array.shape}' )
UpperCAmelCase_ =torch.from_numpy(lowercase__ )
tf_weights.pop(lowercase__ , lowercase__ )
tf_weights.pop(name + "/RMSProp" , lowercase__ )
tf_weights.pop(name + "/RMSProp_1" , lowercase__ )
tf_weights.pop(name + "/ExponentialMovingAverage" , lowercase__ )
logger.info(F'Weights not copied to PyTorch model: {", ".join(tf_weights.keys() )}' )
return model
def a__ ( lowercase__ , lowercase__ ):
'''simple docstring'''
UpperCAmelCase_ , UpperCAmelCase_ =features.shape[-2:]
UpperCAmelCase_ , UpperCAmelCase_ =conv_layer.stride
UpperCAmelCase_ , UpperCAmelCase_ =conv_layer.kernel_size
if in_height % stride_height == 0:
UpperCAmelCase_ =max(kernel_height - stride_height , 0 )
else:
UpperCAmelCase_ =max(kernel_height - (in_height % stride_height) , 0 )
if in_width % stride_width == 0:
UpperCAmelCase_ =max(kernel_width - stride_width , 0 )
else:
UpperCAmelCase_ =max(kernel_width - (in_width % stride_width) , 0 )
UpperCAmelCase_ =pad_along_width // 2
UpperCAmelCase_ =pad_along_width - pad_left
UpperCAmelCase_ =pad_along_height // 2
UpperCAmelCase_ =pad_along_height - pad_top
UpperCAmelCase_ =(pad_left, pad_right, pad_top, pad_bottom)
return nn.functional.pad(lowercase__ , lowercase__ , "constant" , 0.0 )
class A ( nn.Module ):
def __init__( self: Optional[Any] , _lowerCAmelCase: MobileNetVaConfig , _lowerCAmelCase: int , _lowerCAmelCase: int , _lowerCAmelCase: int , _lowerCAmelCase: Optional[int] = 1 , _lowerCAmelCase: Optional[int] = 1 , _lowerCAmelCase: bool = False , _lowerCAmelCase: Optional[bool] = True , _lowerCAmelCase: Optional[bool or str] = True , ) -> None:
'''simple docstring'''
super().__init__()
UpperCAmelCase_ =config
if in_channels % groups != 0:
raise ValueError(F'Input channels ({in_channels}) are not divisible by {groups} groups.' )
if out_channels % groups != 0:
raise ValueError(F'Output channels ({out_channels}) are not divisible by {groups} groups.' )
UpperCAmelCase_ =0 if config.tf_padding else int((kernel_size - 1) / 2 )
UpperCAmelCase_ =nn.Convad(
in_channels=_lowerCAmelCase , out_channels=_lowerCAmelCase , kernel_size=_lowerCAmelCase , stride=_lowerCAmelCase , padding=_lowerCAmelCase , groups=_lowerCAmelCase , bias=_lowerCAmelCase , padding_mode="zeros" , )
if use_normalization:
UpperCAmelCase_ =nn.BatchNormad(
num_features=_lowerCAmelCase , eps=config.layer_norm_eps , momentum=0.99_97 , affine=_lowerCAmelCase , track_running_stats=_lowerCAmelCase , )
else:
UpperCAmelCase_ =None
if use_activation:
if isinstance(_lowerCAmelCase , _lowerCAmelCase ):
UpperCAmelCase_ =ACTaFN[use_activation]
elif isinstance(config.hidden_act , _lowerCAmelCase ):
UpperCAmelCase_ =ACTaFN[config.hidden_act]
else:
UpperCAmelCase_ =config.hidden_act
else:
UpperCAmelCase_ =None
def lowerCAmelCase__ ( self: Union[str, Any] , _lowerCAmelCase: torch.Tensor ) -> torch.Tensor:
'''simple docstring'''
if self.config.tf_padding:
UpperCAmelCase_ =apply_tf_padding(_lowerCAmelCase , self.convolution )
UpperCAmelCase_ =self.convolution(_lowerCAmelCase )
if self.normalization is not None:
UpperCAmelCase_ =self.normalization(_lowerCAmelCase )
if self.activation is not None:
UpperCAmelCase_ =self.activation(_lowerCAmelCase )
return features
class A ( __lowercase ):
_snake_case =MobileNetVaConfig
_snake_case =load_tf_weights_in_mobilenet_va
_snake_case ='''mobilenet_v1'''
_snake_case ='''pixel_values'''
_snake_case =False
def lowerCAmelCase__ ( self: Optional[int] , _lowerCAmelCase: Union[nn.Linear, nn.Convad] ) -> None:
'''simple docstring'''
if isinstance(_lowerCAmelCase , (nn.Linear, nn.Convad) ):
module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range )
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(_lowerCAmelCase , nn.BatchNormad ):
module.bias.data.zero_()
module.weight.data.fill_(1.0 )
__lowercase : Union[str, Any] =R"""
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
behavior.
Parameters:
config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""
__lowercase : List[Any] =R"""
Args:
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
[`MobileNetV1ImageProcessor.__call__`] for details.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
@add_start_docstrings(
'''The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.''' , __lowercase , )
class A ( __lowercase ):
def __init__( self: str , _lowerCAmelCase: MobileNetVaConfig , _lowerCAmelCase: bool = True ) -> Any:
'''simple docstring'''
super().__init__(_lowerCAmelCase )
UpperCAmelCase_ =config
UpperCAmelCase_ =32
UpperCAmelCase_ =max(int(depth * config.depth_multiplier ) , config.min_depth )
UpperCAmelCase_ =MobileNetVaConvLayer(
_lowerCAmelCase , in_channels=config.num_channels , out_channels=_lowerCAmelCase , kernel_size=3 , stride=2 , )
UpperCAmelCase_ =[1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]
UpperCAmelCase_ =nn.ModuleList()
for i in range(13 ):
UpperCAmelCase_ =out_channels
if strides[i] == 2 or i == 0:
depth *= 2
UpperCAmelCase_ =max(int(depth * config.depth_multiplier ) , config.min_depth )
self.layer.append(
MobileNetVaConvLayer(
_lowerCAmelCase , in_channels=_lowerCAmelCase , out_channels=_lowerCAmelCase , kernel_size=3 , stride=strides[i] , groups=_lowerCAmelCase , ) )
self.layer.append(
MobileNetVaConvLayer(
_lowerCAmelCase , in_channels=_lowerCAmelCase , out_channels=_lowerCAmelCase , kernel_size=1 , ) )
UpperCAmelCase_ =nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None
# Initialize weights and apply final processing
self.post_init()
def lowerCAmelCase__ ( self: Union[str, Any] , _lowerCAmelCase: str ) -> List[str]:
'''simple docstring'''
raise NotImplementedError
@add_start_docstrings_to_model_forward(_lowerCAmelCase )
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC , output_type=_lowerCAmelCase , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , )
def lowerCAmelCase__ ( self: Optional[int] , _lowerCAmelCase: Optional[torch.Tensor] = None , _lowerCAmelCase: Optional[bool] = None , _lowerCAmelCase: Optional[bool] = None , ) -> Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:
'''simple docstring'''
UpperCAmelCase_ =(
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
UpperCAmelCase_ =return_dict if return_dict is not None else self.config.use_return_dict
if pixel_values is None:
raise ValueError("You have to specify pixel_values" )
UpperCAmelCase_ =self.conv_stem(_lowerCAmelCase )
UpperCAmelCase_ =() if output_hidden_states else None
for i, layer_module in enumerate(self.layer ):
UpperCAmelCase_ =layer_module(_lowerCAmelCase )
if output_hidden_states:
UpperCAmelCase_ =all_hidden_states + (hidden_states,)
UpperCAmelCase_ =hidden_states
if self.pooler is not None:
UpperCAmelCase_ =torch.flatten(self.pooler(_lowerCAmelCase ) , start_dim=1 )
else:
UpperCAmelCase_ =None
if not return_dict:
return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None )
return BaseModelOutputWithPoolingAndNoAttention(
last_hidden_state=_lowerCAmelCase , pooler_output=_lowerCAmelCase , hidden_states=_lowerCAmelCase , )
@add_start_docstrings(
'''
MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
ImageNet.
''' , __lowercase , )
class A ( __lowercase ):
def __init__( self: Dict , _lowerCAmelCase: MobileNetVaConfig ) -> None:
'''simple docstring'''
super().__init__(_lowerCAmelCase )
UpperCAmelCase_ =config.num_labels
UpperCAmelCase_ =MobileNetVaModel(_lowerCAmelCase )
UpperCAmelCase_ =self.mobilenet_va.layer[-1].convolution.out_channels
# Classifier head
UpperCAmelCase_ =nn.Dropout(config.classifier_dropout_prob , inplace=_lowerCAmelCase )
UpperCAmelCase_ =nn.Linear(_lowerCAmelCase , config.num_labels ) if config.num_labels > 0 else nn.Identity()
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(_lowerCAmelCase )
@add_code_sample_docstrings(
checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_lowerCAmelCase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , )
def lowerCAmelCase__ ( self: Any , _lowerCAmelCase: Optional[torch.Tensor] = None , _lowerCAmelCase: Optional[bool] = None , _lowerCAmelCase: Optional[torch.Tensor] = None , _lowerCAmelCase: Optional[bool] = None , ) -> Union[tuple, ImageClassifierOutputWithNoAttention]:
'''simple docstring'''
UpperCAmelCase_ =return_dict if return_dict is not None else self.config.use_return_dict
UpperCAmelCase_ =self.mobilenet_va(_lowerCAmelCase , output_hidden_states=_lowerCAmelCase , return_dict=_lowerCAmelCase )
UpperCAmelCase_ =outputs.pooler_output if return_dict else outputs[1]
UpperCAmelCase_ =self.classifier(self.dropout(_lowerCAmelCase ) )
UpperCAmelCase_ =None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
UpperCAmelCase_ ="regression"
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
UpperCAmelCase_ ="single_label_classification"
else:
UpperCAmelCase_ ="multi_label_classification"
if self.config.problem_type == "regression":
UpperCAmelCase_ =MSELoss()
if self.num_labels == 1:
UpperCAmelCase_ =loss_fct(logits.squeeze() , labels.squeeze() )
else:
UpperCAmelCase_ =loss_fct(_lowerCAmelCase , _lowerCAmelCase )
elif self.config.problem_type == "single_label_classification":
UpperCAmelCase_ =CrossEntropyLoss()
UpperCAmelCase_ =loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) )
elif self.config.problem_type == "multi_label_classification":
UpperCAmelCase_ =BCEWithLogitsLoss()
UpperCAmelCase_ =loss_fct(_lowerCAmelCase , _lowerCAmelCase )
if not return_dict:
UpperCAmelCase_ =(logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return ImageClassifierOutputWithNoAttention(
loss=_lowerCAmelCase , logits=_lowerCAmelCase , hidden_states=outputs.hidden_states , )
| 54 |
"""simple docstring"""
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 snake_case ( __UpperCAmelCase , __UpperCAmelCase ):
@register_to_config
def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ):
super().__init__()
__SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) )
__SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) )
def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ):
__SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) )
__SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) )
return self
def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ):
__SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std
return embeds
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ):
__SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean
return embeds
| 674 | 0 |
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 UpperCAmelCase ( a_ , a_ , a_ ) -> Any:
"""simple docstring"""
def get_masked_lm_array(a_ ):
__A = F'''masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE'''
__A = tf.train.load_variable(a_ , a_ )
if "kernel" in name:
__A = array.transpose()
return torch.from_numpy(a_ )
def get_encoder_array(a_ ):
__A = F'''encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE'''
__A = tf.train.load_variable(a_ , a_ )
if "kernel" in name:
__A = array.transpose()
return torch.from_numpy(a_ )
def get_encoder_layer_array(a_ , a_ ):
__A = F'''encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE'''
__A = tf.train.load_variable(a_ , a_ )
if "kernel" in name:
__A = array.transpose()
return torch.from_numpy(a_ )
def get_encoder_attention_layer_array(a_ , a_ , a_ ):
__A = F'''encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE'''
__A = tf.train.load_variable(a_ , a_ )
__A = array.reshape(a_ )
if "kernel" in name:
__A = array.transpose()
return torch.from_numpy(a_ )
print(F'''Loading model based on config from {config_path}...''' )
__A = BertConfig.from_json_file(a_ )
__A = BertForMaskedLM(a_ )
# Layers
for layer_index in range(0 , config.num_hidden_layers ):
__A = model.bert.encoder.layer[layer_index]
# Self-attention
__A = layer.attention.self
__A = get_encoder_attention_layer_array(
a_ , "_query_dense/kernel" , self_attn.query.weight.data.shape )
__A = get_encoder_attention_layer_array(
a_ , "_query_dense/bias" , self_attn.query.bias.data.shape )
__A = get_encoder_attention_layer_array(
a_ , "_key_dense/kernel" , self_attn.key.weight.data.shape )
__A = get_encoder_attention_layer_array(
a_ , "_key_dense/bias" , self_attn.key.bias.data.shape )
__A = get_encoder_attention_layer_array(
a_ , "_value_dense/kernel" , self_attn.value.weight.data.shape )
__A = get_encoder_attention_layer_array(
a_ , "_value_dense/bias" , self_attn.value.bias.data.shape )
# Self-attention Output
__A = layer.attention.output
__A = get_encoder_attention_layer_array(
a_ , "_output_dense/kernel" , self_output.dense.weight.data.shape )
__A = get_encoder_attention_layer_array(
a_ , "_output_dense/bias" , self_output.dense.bias.data.shape )
__A = get_encoder_layer_array(a_ , "_attention_layer_norm/gamma" )
__A = get_encoder_layer_array(a_ , "_attention_layer_norm/beta" )
# Intermediate
__A = layer.intermediate
__A = get_encoder_layer_array(a_ , "_intermediate_dense/kernel" )
__A = get_encoder_layer_array(a_ , "_intermediate_dense/bias" )
# Output
__A = layer.output
__A = get_encoder_layer_array(a_ , "_output_dense/kernel" )
__A = get_encoder_layer_array(a_ , "_output_dense/bias" )
__A = get_encoder_layer_array(a_ , "_output_layer_norm/gamma" )
__A = get_encoder_layer_array(a_ , "_output_layer_norm/beta" )
# Embeddings
__A = get_encoder_array("_position_embedding_layer/embeddings" )
__A = get_encoder_array("_type_embedding_layer/embeddings" )
__A = get_encoder_array("_embedding_norm_layer/gamma" )
__A = get_encoder_array("_embedding_norm_layer/beta" )
# LM Head
__A = model.cls.predictions.transform
__A = get_masked_lm_array("dense/kernel" )
__A = get_masked_lm_array("dense/bias" )
__A = get_masked_lm_array("layer_norm/gamma" )
__A = get_masked_lm_array("layer_norm/beta" )
__A = get_masked_lm_array("embedding_table" )
# Pooling
__A = BertPooler(config=a_ )
__A = get_encoder_array("_pooler_layer/kernel" )
__A = get_encoder_array("_pooler_layer/bias" )
# Export final model
model.save_pretrained(a_ )
# Integration test - should load without any errors ;)
__A = BertForMaskedLM.from_pretrained(a_ )
print(new_model.eval() )
print("Model conversion was done sucessfully!" )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE :int = 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.',
)
SCREAMING_SNAKE_CASE :Tuple = parser.parse_args()
convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
| 55 |
"""simple docstring"""
import argparse
import torch
from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert
from transformers.utils import logging
logging.set_verbosity_info()
def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ )
print(F'''Building PyTorch model from configuration: {config}''' )
__SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ )
# Load weights from tf checkpoint
load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ )
# Save pytorch-model
print(F'''Save PyTorch model to {pytorch_dump_path}''' )
torch.save(model.state_dict() , lowercase_ )
if __name__ == "__main__":
_lowerCamelCase = 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(
'''--bert_config_file''',
default=None,
type=str,
required=True,
help=(
'''The config json file corresponding to the pre-trained BERT model. \n'''
'''This specifies the model architecture.'''
),
)
parser.add_argument(
'''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
)
_lowerCamelCase = parser.parse_args()
convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
| 674 | 0 |
'''simple docstring'''
import numpy as np
# Importing the Keras libraries and packages
import tensorflow as tf
from tensorflow.keras import layers, models
if __name__ == "__main__":
# Initialising the CNN
# (Sequential- Building the model layer by layer)
_a : Dict = models.Sequential()
# Step 1 - Convolution
# Here 64,64 is the length & breadth of dataset images and 3 is for the RGB channel
# (3,3) is the kernel size (filter matrix)
classifier.add(
layers.ConvaD(32, (3, 3), input_shape=(64, 64, 3), activation="relu")
)
# Step 2 - Pooling
classifier.add(layers.MaxPoolingaD(pool_size=(2, 2)))
# Adding a second convolutional layer
classifier.add(layers.ConvaD(32, (3, 3), activation="relu"))
classifier.add(layers.MaxPoolingaD(pool_size=(2, 2)))
# Step 3 - Flattening
classifier.add(layers.Flatten())
# Step 4 - Full connection
classifier.add(layers.Dense(units=128, activation="relu"))
classifier.add(layers.Dense(units=1, activation="sigmoid"))
# Compiling the CNN
classifier.compile(
optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"]
)
# Part 2 - Fitting the CNN to the images
# Load Trained model weights
# from keras.models import load_model
# regressor=load_model('cnn.h5')
_a : List[str] = tf.keras.preprocessing.image.ImageDataGenerator(
rescale=1.0 / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True
)
_a : str = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1.0 / 255)
_a : Optional[int] = train_datagen.flow_from_directory(
"dataset/training_set", target_size=(64, 64), batch_size=32, class_mode="binary"
)
_a : Union[str, Any] = test_datagen.flow_from_directory(
"dataset/test_set", target_size=(64, 64), batch_size=32, class_mode="binary"
)
classifier.fit_generator(
training_set, steps_per_epoch=5, epochs=30, validation_data=test_set
)
classifier.save("cnn.h5")
# Part 3 - Making new predictions
_a : str = tf.keras.preprocessing.image.load_img(
"dataset/single_prediction/image.png", target_size=(64, 64)
)
_a : Optional[Any] = tf.keras.preprocessing.image.img_to_array(test_image)
_a : int = np.expand_dims(test_image, axis=0)
_a : Optional[Any] = classifier.predict(test_image)
# training_set.class_indices
if result[0][0] == 0:
_a : int = "Normal"
if result[0][0] == 1:
_a : List[Any] = "Abnormality detected"
| 56 |
"""simple docstring"""
# 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 numpy as np
import torch
from ..models.clipseg import CLIPSegForImageSegmentation
from ..utils import is_vision_available, requires_backends
from .base import PipelineTool
if is_vision_available():
from PIL import Image
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = (
'''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.'''
'''It takes two arguments named `image` which should be the original image, and `label` which should be a text '''
'''describing the elements what should be identified in the segmentation mask. The tool returns the mask.'''
)
lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined'''
lowerCamelCase__ = '''image_segmenter'''
lowerCamelCase__ = CLIPSegForImageSegmentation
lowerCamelCase__ = ['''image''', '''text''']
lowerCamelCase__ = ['''image''']
def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ):
requires_backends(self , ['''vision'''] )
super().__init__(*_lowerCamelCase , **_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ):
return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ):
with torch.no_grad():
__SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits
return logits
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ):
__SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy()
__SCREAMING_SNAKE_CASE : str = 0
__SCREAMING_SNAKE_CASE : str = 1
return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
| 674 | 0 |
import warnings
from ...utils import logging
from .image_processing_clip import CLIPImageProcessor
A_ : int = logging.get_logger(__name__)
class _lowerCAmelCase( UpperCAmelCase_ ):
"""simple docstring"""
def __init__( self , *_lowerCamelCase , **_lowerCamelCase ):
warnings.warn(
'The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please'
' use CLIPImageProcessor instead.' , _lowerCamelCase , )
super().__init__(*_lowerCamelCase , **_lowerCamelCase ) | 57 |
"""simple docstring"""
import json
import os
import shutil
import tempfile
import unittest
import numpy as np
from transformers import BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer
from transformers.testing_utils import require_tokenizers, require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available
if is_vision_available():
from PIL import Image
from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor
@require_tokenizers
@require_vision
class snake_case ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp()
# fmt: off
__SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''']
# fmt: on
__SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer:
vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) )
__SCREAMING_SNAKE_CASE : Optional[int] = {
'''do_resize''': True,
'''size''': {'''height''': 1_8, '''width''': 1_8},
'''do_normalize''': True,
'''image_mean''': [0.5, 0.5, 0.5],
'''image_std''': [0.5, 0.5, 0.5],
}
__SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase )
with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp:
json.dump(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ):
return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ):
return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
shutil.rmtree(self.tmpdirname )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )]
__SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def SCREAMING_SNAKE_CASE_ ( self :int ):
__SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor()
__SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
processor.save_pretrained(self.tmpdirname )
__SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() )
self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) )
self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() )
self.assertIsInstance(processor.image_processor , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
__SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor(
tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
__SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' )
__SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 )
__SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(
self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :int ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor()
__SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs()
__SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' )
__SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''np''' )
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
__SCREAMING_SNAKE_CASE : Any = self.get_image_processor()
__SCREAMING_SNAKE_CASE : Any = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer'''
__SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE : str = self.get_image_processor()
__SCREAMING_SNAKE_CASE : int = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = '''lower newer'''
__SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs()
__SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase )
self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] )
# test if it raises when no input is passed
with self.assertRaises(_lowerCamelCase ):
processor()
def SCREAMING_SNAKE_CASE_ ( self :Any ):
__SCREAMING_SNAKE_CASE : Dict = self.get_image_processor()
__SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
__SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase )
self.assertListEqual(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
__SCREAMING_SNAKE_CASE : str = self.get_image_processor()
__SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = '''lower newer'''
__SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs()
__SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase )
self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
| 674 | 0 |
"""simple docstring"""
import copy
import os
from typing import Union
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCAmelCase : List[Any] = logging.get_logger(__name__)
__lowerCAmelCase : Union[str, Any] = {
'''BridgeTower/bridgetower-base''': '''https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json''',
'''BridgeTower/bridgetower-base-itm-mlm''': (
'''https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json'''
),
}
class _lowerCAmelCase ( SCREAMING_SNAKE_CASE__ ):
"""simple docstring"""
_lowerCamelCase = '''bridgetower_vision_model'''
def __init__( self , _lowercase=7_6_8 , _lowercase=1_2 , _lowercase=3 , _lowercase=1_6 , _lowercase=2_8_8 , _lowercase=1 , _lowercase=1E-05 , _lowercase=False , _lowercase=True , _lowercase=False , **_lowercase , ) -> List[Any]:
'''simple docstring'''
super().__init__(**_lowercase )
snake_case_ : Any = hidden_size
snake_case_ : Tuple = num_hidden_layers
snake_case_ : Union[str, Any] = num_channels
snake_case_ : List[Any] = patch_size
snake_case_ : int = image_size
snake_case_ : Tuple = initializer_factor
snake_case_ : List[str] = layer_norm_eps
snake_case_ : Optional[int] = stop_gradient
snake_case_ : Optional[Any] = share_layernorm
snake_case_ : Tuple = remove_last_layer
@classmethod
def UpperCAmelCase__ ( cls , _lowercase , **_lowercase ) -> "PretrainedConfig":
'''simple docstring'''
snake_case_ , snake_case_ : Any = cls.get_config_dict(_lowercase , **_lowercase )
if config_dict.get("""model_type""" ) == "bridgetower":
snake_case_ : Any = config_dict["""text_config"""]
if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type:
logger.warning(
f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' )
return cls.from_dict(_lowercase , **_lowercase )
class _lowerCAmelCase ( SCREAMING_SNAKE_CASE__ ):
"""simple docstring"""
_lowerCamelCase = '''bridgetower_text_model'''
def __init__( self , _lowercase=5_0_2_6_5 , _lowercase=7_6_8 , _lowercase=1_2 , _lowercase=1_2 , _lowercase=1 , _lowercase=3_0_7_2 , _lowercase="gelu" , _lowercase=0.1 , _lowercase=0.1 , _lowercase=5_1_4 , _lowercase=1 , _lowercase=1E-05 , _lowercase=1 , _lowercase=0 , _lowercase=2 , _lowercase="absolute" , _lowercase=True , **_lowercase , ) -> str:
'''simple docstring'''
super().__init__(**_lowercase )
snake_case_ : Any = vocab_size
snake_case_ : Dict = hidden_size
snake_case_ : int = num_hidden_layers
snake_case_ : Dict = num_attention_heads
snake_case_ : Any = hidden_act
snake_case_ : Dict = initializer_factor
snake_case_ : List[Any] = intermediate_size
snake_case_ : Dict = hidden_dropout_prob
snake_case_ : Optional[int] = attention_probs_dropout_prob
snake_case_ : str = max_position_embeddings
snake_case_ : List[str] = type_vocab_size
snake_case_ : Tuple = layer_norm_eps
snake_case_ : int = position_embedding_type
snake_case_ : Optional[int] = use_cache
snake_case_ : List[str] = pad_token_id
snake_case_ : int = bos_token_id
snake_case_ : Dict = eos_token_id
@classmethod
def UpperCAmelCase__ ( cls , _lowercase , **_lowercase ) -> "PretrainedConfig":
'''simple docstring'''
snake_case_ , snake_case_ : int = cls.get_config_dict(_lowercase , **_lowercase )
if config_dict.get("""model_type""" ) == "bridgetower":
snake_case_ : Union[str, Any] = config_dict["""text_config"""]
if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type:
logger.warning(
f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' )
return cls.from_dict(_lowercase , **_lowercase )
class _lowerCAmelCase ( SCREAMING_SNAKE_CASE__ ):
"""simple docstring"""
_lowerCamelCase = '''bridgetower'''
def __init__( self , _lowercase=True , _lowercase="gelu" , _lowercase=7_6_8 , _lowercase=1 , _lowercase=1E-05 , _lowercase=False , _lowercase="add" , _lowercase=1_2 , _lowercase=6 , _lowercase=False , _lowercase=False , _lowercase=None , _lowercase=None , **_lowercase , ) -> Dict:
'''simple docstring'''
snake_case_ : Dict = kwargs.pop("""text_config_dict""" , _lowercase )
snake_case_ : List[str] = kwargs.pop("""vision_config_dict""" , _lowercase )
super().__init__(**_lowercase )
snake_case_ : str = share_cross_modal_transformer_layers
snake_case_ : int = hidden_act
snake_case_ : Tuple = hidden_size
snake_case_ : List[Any] = initializer_factor
snake_case_ : Dict = layer_norm_eps
snake_case_ : str = share_link_tower_layers
snake_case_ : int = link_tower_type
snake_case_ : str = num_attention_heads
snake_case_ : int = num_hidden_layers
snake_case_ : Tuple = tie_word_embeddings
snake_case_ : Tuple = init_layernorm_from_vision_encoder
if text_config is None:
snake_case_ : Optional[Any] = {}
logger.info("""`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values.""" )
if vision_config is None:
snake_case_ : Optional[int] = {}
logger.info("""`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.""" )
snake_case_ : str = BridgeTowerTextConfig(**_lowercase )
snake_case_ : Any = BridgeTowerVisionConfig(**_lowercase )
@classmethod
def UpperCAmelCase__ ( cls , _lowercase , _lowercase , **_lowercase ) -> Dict:
'''simple docstring'''
return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **_lowercase )
def UpperCAmelCase__ ( self ) -> Union[str, Any]:
'''simple docstring'''
snake_case_ : Optional[Any] = copy.deepcopy(self.__dict__ )
snake_case_ : int = self.text_config.to_dict()
snake_case_ : str = self.vision_config.to_dict()
snake_case_ : Tuple = self.__class__.model_type
return output
| 58 |
"""simple docstring"""
import inspect
import unittest
import numpy as np
from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel
if is_vision_available():
from transformers import MaskFormerImageProcessor
if is_vision_available():
from PIL import Image
class snake_case :
def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ):
__SCREAMING_SNAKE_CASE : List[str] = parent
__SCREAMING_SNAKE_CASE : Tuple = batch_size
__SCREAMING_SNAKE_CASE : Optional[Any] = is_training
__SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss
__SCREAMING_SNAKE_CASE : List[str] = num_queries
__SCREAMING_SNAKE_CASE : Optional[int] = num_channels
__SCREAMING_SNAKE_CASE : List[Any] = min_size
__SCREAMING_SNAKE_CASE : int = max_size
__SCREAMING_SNAKE_CASE : Any = num_labels
__SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size
def SCREAMING_SNAKE_CASE_ ( self :Any ):
__SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to(
_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = (
torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5
).float()
__SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long()
__SCREAMING_SNAKE_CASE : str = self.get_config()
return config, pixel_values, pixel_mask, mask_labels, class_labels
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
return MaskFormerConfig.from_backbone_and_decoder_configs(
backbone_config=SwinConfig(
depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig(
decoder_ffn_dim=1_2_8 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , )
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs()
__SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
return config, inputs_dict
def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states
__SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states
__SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states
self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers )
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ):
with torch.no_grad():
__SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
__SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase )
# the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
# encoder and pixel decoder
self.parent.assertEqual(
output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , )
# let's ensure the other two hidden state exists
self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(output.encoder_last_hidden_state is not None )
if output_hidden_states:
self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ):
__SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
def comm_check_on_output(_lowerCamelCase :Optional[Any] ):
# let's still check that all the required stuff is there
self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.encoder_last_hidden_state is not None )
# okay, now we need to check the logits shape
# due to the encoder compression, masks have a //4 spatial size
self.parent.assertEqual(
result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , )
# + 1 for null class
self.parent.assertEqual(
result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) )
with torch.no_grad():
__SCREAMING_SNAKE_CASE : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase )
comm_check_on_output(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Dict = model(
pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase )
comm_check_on_output(_lowerCamelCase )
self.parent.assertTrue(result.loss is not None )
self.parent.assertEqual(result.loss.shape , torch.Size([1] ) )
@require_torch
class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ):
lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
lowerCamelCase__ = (
{'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation}
if is_torch_available()
else {}
)
lowerCamelCase__ = False
lowerCamelCase__ = False
lowerCamelCase__ = False
lowerCamelCase__ = False
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
__SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self )
__SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
self.config_tester.run_common_tests()
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
__SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase )
@unittest.skip(reason='''MaskFormer does not use inputs_embeds''' )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
pass
@unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' )
def SCREAMING_SNAKE_CASE_ ( self :int ):
pass
@unittest.skip(reason='''MaskFormer is not a generative model''' )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
pass
@unittest.skip(reason='''MaskFormer does not use token embeddings''' )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
pass
@require_torch_multi_gpu
@unittest.skip(
reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
pass
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
pass
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__SCREAMING_SNAKE_CASE : Tuple = model_class(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()]
__SCREAMING_SNAKE_CASE : Optional[Any] = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
for model_name in ["facebook/maskformer-swin-small-coco"]:
__SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2
__SCREAMING_SNAKE_CASE : Dict = {
'''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ),
'''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ),
'''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(),
}
__SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase )
self.assertTrue(outputs.loss is not None )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__SCREAMING_SNAKE_CASE : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase )
self.assertTrue(outputs.attentions is not None )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
if not self.model_tester.is_training:
return
# only MaskFormerForInstanceSegmentation has the loss
__SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1]
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs()
__SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase )
model.to(_lowerCamelCase )
model.train()
__SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss
loss.backward()
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# only MaskFormerForInstanceSegmentation has the loss
__SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1]
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs()
__SCREAMING_SNAKE_CASE : Tuple = True
__SCREAMING_SNAKE_CASE : List[str] = True
__SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase )
model.to(_lowerCamelCase )
model.train()
__SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = outputs.encoder_hidden_states[0]
encoder_hidden_states.retain_grad()
__SCREAMING_SNAKE_CASE : str = outputs.pixel_decoder_hidden_states[0]
pixel_decoder_hidden_states.retain_grad()
# we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
__SCREAMING_SNAKE_CASE : Optional[int] = outputs.transformer_decoder_hidden_states[0]
transformer_decoder_hidden_states.retain_grad()
__SCREAMING_SNAKE_CASE : int = outputs.attentions[0]
attentions.retain_grad()
outputs.loss.backward(retain_graph=_lowerCamelCase )
self.assertIsNotNone(encoder_hidden_states.grad )
self.assertIsNotNone(pixel_decoder_hidden_states.grad )
self.assertIsNotNone(transformer_decoder_hidden_states.grad )
self.assertIsNotNone(attentions.grad )
_lowerCamelCase = 1e-4
def lowerCAmelCase_ ( ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_vision
@slow
class snake_case ( unittest.TestCase ):
@cached_property
def SCREAMING_SNAKE_CASE_ ( self :str ):
return (
MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' )
if is_vision_available()
else None
)
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = self.default_image_processor
__SCREAMING_SNAKE_CASE : Tuple = prepare_img()
__SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 )
# check size
self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) )
with torch.no_grad():
__SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor(
[[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase )
self.assertTrue(
torch.allclose(
outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
__SCREAMING_SNAKE_CASE : Any = torch.tensor(
[[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase )
self.assertTrue(
torch.allclose(
outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
__SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(
[[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase )
self.assertTrue(
torch.allclose(
outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
__SCREAMING_SNAKE_CASE : Tuple = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
.to(_lowerCamelCase )
.eval()
)
__SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor
__SCREAMING_SNAKE_CASE : Tuple = prepare_img()
__SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 )
# check size
self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) )
with torch.no_grad():
__SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase )
# masks_queries_logits
__SCREAMING_SNAKE_CASE : Any = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
__SCREAMING_SNAKE_CASE : List[Any] = [
[-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3],
[-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5],
[-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2],
]
__SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
# class_queries_logits
__SCREAMING_SNAKE_CASE : List[Any] = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
__SCREAMING_SNAKE_CASE : List[str] = torch.tensor(
[
[1.65_12e00, -5.25_72e00, -3.35_19e00],
[3.61_69e-02, -5.90_25e00, -2.93_13e00],
[1.07_66e-04, -7.76_30e00, -5.12_63e00],
] ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
def SCREAMING_SNAKE_CASE_ ( self :Any ):
__SCREAMING_SNAKE_CASE : Tuple = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' )
.to(_lowerCamelCase )
.eval()
)
__SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor
__SCREAMING_SNAKE_CASE : str = prepare_img()
__SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 )
# check size
self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) )
with torch.no_grad():
__SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase )
# masks_queries_logits
__SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
__SCREAMING_SNAKE_CASE : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]]
__SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
# class_queries_logits
__SCREAMING_SNAKE_CASE : int = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
__SCREAMING_SNAKE_CASE : List[str] = torch.tensor(
[[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
def SCREAMING_SNAKE_CASE_ ( self :int ):
__SCREAMING_SNAKE_CASE : int = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
.to(_lowerCamelCase )
.eval()
)
__SCREAMING_SNAKE_CASE : Any = self.default_image_processor
__SCREAMING_SNAKE_CASE : int = image_processor(
[np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , )
__SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']]
__SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']]
with torch.no_grad():
__SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase )
self.assertTrue(outputs.loss is not None )
| 674 | 0 |
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 |
"""simple docstring"""
import contextlib
import importlib
import io
import unittest
import transformers
# Try to import everything from transformers to ensure every object can be loaded.
from transformers import * # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available
if is_torch_available():
from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification
if is_tf_available():
from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification
if is_flax_available():
from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification
_lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co
_lowerCamelCase = '''main'''
# Default branch name
_lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'''
# One particular commit (not the top of `main`)
_lowerCamelCase = '''aaaaaaa'''
# This commit does not exist, so we should 404.
_lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684'''
# Sha-1 of config.json on the top of `main`, for checking purposes
_lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'''
@contextlib.contextmanager
def lowerCAmelCase_ ( ):
'''simple docstring'''
print('''Welcome!''' )
yield
print('''Bye!''' )
@contextlib.contextmanager
def lowerCAmelCase_ ( ):
'''simple docstring'''
print('''Bonjour!''' )
yield
print('''Au revoir!''' )
class snake_case ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
# If the spec is missing, importlib would not be able to import the module dynamically.
assert transformers.__spec__ is not None
assert importlib.util.find_spec('''transformers''' ) is not None
class snake_case ( unittest.TestCase ):
@unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO )
def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ):
with ContextManagers([] ):
print('''Transformers are awesome!''' )
# The print statement adds a new line at the end of the output
self.assertEqual(mock_stdout.getvalue() , '''Transformers are awesome!\n''' )
@unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO )
def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ):
with ContextManagers([context_en()] ):
print('''Transformers are awesome!''' )
# The output should be wrapped with an English welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , '''Welcome!\nTransformers are awesome!\nBye!\n''' )
@unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO )
def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ):
with ContextManagers([context_fr(), context_en()] ):
print('''Transformers are awesome!''' )
# The output should be wrapped with an English and French welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , '''Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n''' )
@require_torch
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] )
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] )
self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] )
class snake_case ( __UpperCAmelCase ):
pass
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] )
@require_tf
def SCREAMING_SNAKE_CASE_ ( self :int ):
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] )
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] )
self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] )
class snake_case ( __UpperCAmelCase ):
pass
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] )
@require_flax
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
# Flax models don't have labels
self.assertEqual(find_labels(_lowerCamelCase ) , [] )
self.assertEqual(find_labels(_lowerCamelCase ) , [] )
self.assertEqual(find_labels(_lowerCamelCase ) , [] )
class snake_case ( __UpperCAmelCase ):
pass
self.assertEqual(find_labels(_lowerCamelCase ) , [] )
| 674 | 0 |
from pathlib import Path
from typing import List
from transformers import is_torch_available, is_vision_available
from transformers.testing_utils import get_tests_dir, is_tool_test
from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
lowerCAmelCase_ = ['''text''', '''image''', '''audio''']
def lowerCamelCase_ ( _UpperCamelCase ) -> Tuple:
"""simple docstring"""
snake_case_ : Tuple = []
for input_type in input_types:
if input_type == "text":
inputs.append('''Text input''' )
elif input_type == "image":
inputs.append(
Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO''' ) ) / '''000000039769.png''' ).resize((512, 512) ) )
elif input_type == "audio":
inputs.append(torch.ones(3_000 ) )
elif isinstance(_UpperCamelCase , _UpperCamelCase ):
inputs.append(create_inputs(_UpperCamelCase ) )
else:
raise ValueError(f'''Invalid type requested: {input_type}''' )
return inputs
def lowerCamelCase_ ( _UpperCamelCase ) -> Tuple:
"""simple docstring"""
snake_case_ : Dict = []
for output in outputs:
if isinstance(_UpperCamelCase , (str, AgentText) ):
output_types.append('''text''' )
elif isinstance(_UpperCamelCase , (Image.Image, AgentImage) ):
output_types.append('''image''' )
elif isinstance(_UpperCamelCase , (torch.Tensor, AgentAudio) ):
output_types.append('''audio''' )
else:
raise ValueError(f'''Invalid output: {output}''' )
return output_types
@is_tool_test
class __lowerCAmelCase :
def lowerCamelCase (self ) -> Dict:
'''simple docstring'''
self.assertTrue(hasattr(self.tool , '''inputs''' ) )
self.assertTrue(hasattr(self.tool , '''outputs''' ) )
snake_case_ : Any = self.tool.inputs
for _input in inputs:
if isinstance(_input , __magic_name__ ):
for __input in _input:
self.assertTrue(__input in authorized_types )
else:
self.assertTrue(_input in authorized_types )
snake_case_ : Dict = self.tool.outputs
for _output in outputs:
self.assertTrue(_output in authorized_types )
def lowerCamelCase (self ) -> Optional[int]:
'''simple docstring'''
snake_case_ : Union[str, Any] = create_inputs(self.tool.inputs )
snake_case_ : Tuple = self.tool(*__magic_name__ )
# There is a single output
if len(self.tool.outputs ) == 1:
snake_case_ : Optional[Any] = [outputs]
self.assertListEqual(output_types(__magic_name__ ) , self.tool.outputs )
def lowerCamelCase (self ) -> str:
'''simple docstring'''
self.assertTrue(hasattr(self.tool , '''description''' ) )
self.assertTrue(hasattr(self.tool , '''default_checkpoint''' ) )
self.assertTrue(self.tool.description.startswith('''This is a tool that''' ) )
def lowerCamelCase (self ) -> Tuple:
'''simple docstring'''
snake_case_ : Any = create_inputs(self.tool.inputs )
snake_case_ : int = self.tool(*__magic_name__ )
if not isinstance(__magic_name__ , __magic_name__ ):
snake_case_ : Tuple = [outputs]
self.assertEqual(len(__magic_name__ ) , len(self.tool.outputs ) )
for output, output_type in zip(__magic_name__ , self.tool.outputs ):
snake_case_ : Any = AGENT_TYPE_MAPPING[output_type]
self.assertTrue(isinstance(__magic_name__ , __magic_name__ ) )
def lowerCamelCase (self ) -> Tuple:
'''simple docstring'''
snake_case_ : List[str] = create_inputs(self.tool.inputs )
snake_case_ : Optional[int] = []
for _input, input_type in zip(__magic_name__ , self.tool.inputs ):
if isinstance(__magic_name__ , __magic_name__ ):
_inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] )
else:
_inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) )
# Should not raise an error
snake_case_ : List[str] = self.tool(*__magic_name__ )
if not isinstance(__magic_name__ , __magic_name__ ):
snake_case_ : Dict = [outputs]
self.assertEqual(len(__magic_name__ ) , len(self.tool.outputs ) )
| 60 |
"""simple docstring"""
import json
import pathlib
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import YolosImageProcessor
class snake_case ( unittest.TestCase ):
def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ):
# by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
__SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3}
__SCREAMING_SNAKE_CASE : List[str] = parent
__SCREAMING_SNAKE_CASE : Dict = batch_size
__SCREAMING_SNAKE_CASE : str = num_channels
__SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution
__SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution
__SCREAMING_SNAKE_CASE : Tuple = do_resize
__SCREAMING_SNAKE_CASE : Union[str, Any] = size
__SCREAMING_SNAKE_CASE : int = do_normalize
__SCREAMING_SNAKE_CASE : List[Any] = image_mean
__SCREAMING_SNAKE_CASE : Tuple = image_std
__SCREAMING_SNAKE_CASE : Dict = do_rescale
__SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor
__SCREAMING_SNAKE_CASE : List[Any] = do_pad
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
return {
"do_resize": self.do_resize,
"size": self.size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_rescale": self.do_rescale,
"rescale_factor": self.rescale_factor,
"do_pad": self.do_pad,
}
def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ):
if not batched:
__SCREAMING_SNAKE_CASE : str = image_inputs[0]
if isinstance(_lowerCamelCase , Image.Image ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size
else:
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2]
if w < h:
__SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w )
__SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge''']
elif w > h:
__SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge''']
__SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h )
else:
__SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge''']
__SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge''']
else:
__SCREAMING_SNAKE_CASE : Optional[Any] = []
for image in image_inputs:
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] )
expected_values.append((expected_height, expected_width) )
__SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0]
__SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1]
return expected_height, expected_width
@require_torch
@require_vision
class snake_case ( __UpperCAmelCase , unittest.TestCase ):
lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
__SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self )
@property
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
return self.image_processor_tester.prepare_image_processor_dict()
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
__SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) )
self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) )
self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) )
self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) )
self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} )
self.assertEqual(image_processor.do_pad , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict(
self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase )
self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} )
self.assertEqual(image_processor.do_pad , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
pass
def SCREAMING_SNAKE_CASE_ ( self :int ):
# Initialize image_processing
__SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
__SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , Image.Image )
# Test not batched input
__SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# Initialize image_processing
__SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
__SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , np.ndarray )
# Test not batched input
__SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def SCREAMING_SNAKE_CASE_ ( self :Any ):
# Initialize image_processing
__SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
__SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , torch.Tensor )
# Test not batched input
__SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
# Initialize image_processings
__SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict )
__SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase )
# create random PyTorch tensors
__SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , torch.Tensor )
# Test whether the method "pad" and calling the image processor return the same tensors
__SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' )
__SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' )
self.assertTrue(
torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) )
@slow
def SCREAMING_SNAKE_CASE_ ( self :int ):
# prepare image and target
__SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f:
__SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() )
__SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target}
# encode them
__SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' )
__SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' )
# verify pixel values
__SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] )
self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] )
self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) )
# verify area
__SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) )
# verify boxes
__SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] )
self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) )
# verify image_id
__SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) )
# verify is_crowd
__SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) )
# verify class_labels
__SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) )
# verify orig_size
__SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) )
# verify size
__SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# prepare image, target and masks_path
__SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f:
__SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() )
__SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target}
__SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' )
# encode them
__SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' )
__SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' )
# verify pixel values
__SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] )
self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] )
self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) )
# verify area
__SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) )
# verify boxes
__SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] )
self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) )
# verify image_id
__SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) )
# verify is_crowd
__SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) )
# verify class_labels
__SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) )
# verify masks
__SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3
self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase )
# verify orig_size
__SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) )
# verify size
__SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
| 674 | 0 |
from decimal import Decimal, getcontext
from math import ceil, factorial
def _A ( lowerCAmelCase_ : int ):
"""simple docstring"""
if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ):
raise TypeError("Undefined for non-integers" )
elif precision < 1:
raise ValueError("Undefined for non-natural numbers" )
lowerCAmelCase__ = precision
lowerCAmelCase__ = ceil(precision / 14 )
lowerCAmelCase__ = 42_6880 * Decimal(1_0005 ).sqrt()
lowerCAmelCase__ = 1
lowerCAmelCase__ = 1359_1409
lowerCAmelCase__ = Decimal(lowerCAmelCase_ )
for k in range(1 , lowerCAmelCase_ ):
lowerCAmelCase__ = factorial(6 * k ) // (factorial(3 * k ) * factorial(lowerCAmelCase_ ) ** 3)
linear_term += 5_4514_0134
exponential_term *= -26_2537_4126_4076_8000
partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term
return str(constant_term / partial_sum )[:-1]
if __name__ == "__main__":
UpperCamelCase = 50
print(F"""The first {n} digits of pi is: {pi(n)}""")
| 61 |
"""simple docstring"""
from __future__ import annotations
def lowerCAmelCase_ ( lowercase_ : int ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ )
return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' )
def lowerCAmelCase_ ( ):
'''simple docstring'''
for base_num in range(9999 , 4999 , -1 ):
__SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num
if is_9_pandigital(lowercase_ ):
return candidate
for base_num in range(333 , 99 , -1 ):
__SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num
if is_9_pandigital(lowercase_ ):
return candidate
return None
if __name__ == "__main__":
print(f'{solution() = }')
| 674 | 0 |
from __future__ import annotations
import sys
from collections import deque
from typing import Generic, TypeVar
snake_case = TypeVar("""T""")
class SCREAMING_SNAKE_CASE ( Generic[T] ):
'''simple docstring'''
UpperCamelCase_ : deque[T] # Cache store of keys
UpperCamelCase_ : set[T] # References of the keys in cache
UpperCamelCase_ : int = 1_0 # Maximum capacity of cache
def __init__( self : int , UpperCAmelCase_ : int ):
SCREAMING_SNAKE_CASE : List[Any] = deque()
SCREAMING_SNAKE_CASE : Tuple = set()
if not n:
SCREAMING_SNAKE_CASE : Dict = sys.maxsize
elif n < 0:
raise ValueError("n should be an integer greater than 0." )
else:
SCREAMING_SNAKE_CASE : str = n
def _A ( self : Tuple , UpperCAmelCase_ : T ):
if x not in self.key_reference:
if len(self.dq_store ) == LRUCache._MAX_CAPACITY:
SCREAMING_SNAKE_CASE : Union[str, Any] = self.dq_store.pop()
self.key_reference.remove(UpperCAmelCase_ )
else:
self.dq_store.remove(UpperCAmelCase_ )
self.dq_store.appendleft(UpperCAmelCase_ )
self.key_reference.add(UpperCAmelCase_ )
def _A ( self : Any ):
for k in self.dq_store:
print(UpperCAmelCase_ )
def __repr__( self : str ):
return f'''LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}'''
if __name__ == "__main__":
import doctest
doctest.testmod()
snake_case = LRUCache(4)
lru_cache.refer("""A""")
lru_cache.refer(2)
lru_cache.refer(3)
lru_cache.refer("""A""")
lru_cache.refer(4)
lru_cache.refer(5)
lru_cache.display()
print(lru_cache)
assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
| 62 |
"""simple docstring"""
import json
import sys
import tempfile
import unittest
from pathlib import Path
import transformers
from transformers import (
CONFIG_MAPPING,
IMAGE_PROCESSOR_MAPPING,
AutoConfig,
AutoImageProcessor,
CLIPConfig,
CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER
sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils'''))
from test_module.custom_configuration import CustomConfig # noqa E402
from test_module.custom_image_processing import CustomImageProcessor # noqa E402
class snake_case ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE_ ( self :int ):
__SCREAMING_SNAKE_CASE : Tuple = 0
def SCREAMING_SNAKE_CASE_ ( self :Any ):
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :int ):
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json'''
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) )
__SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# Ensure we can load the image processor from the feature extractor config
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json'''
__SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json'''
json.dump(
{'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) )
__SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :int ):
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : str = CLIPConfig()
# Create a dummy config file with image_proceesor_type
__SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json'''
__SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) )
# remove image_processor_type to make sure config.json alone is enough to load image processor locally
__SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict()
config_dict.pop('''image_processor_type''' )
__SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase )
# save in new folder
model_config.save_pretrained(_lowerCamelCase )
config.save_pretrained(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase )
# make sure private variable is not incorrectly saved
__SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() )
self.assertTrue('''_processor_class''' not in dict_as_saved )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , )
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
with self.assertRaisesRegex(
_lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ):
__SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
with self.assertRaisesRegex(
_lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ):
__SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
with self.assertRaisesRegex(
_lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ):
__SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
# If remote code is not set, we will time out when asking whether to load the model.
with self.assertRaises(_lowerCamelCase ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' )
# If remote code is disabled, we can't load this config.
with self.assertRaises(_lowerCamelCase ):
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
# Test image processor can be reloaded.
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase )
self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
try:
AutoConfig.register('''custom''' , _lowerCamelCase )
AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase )
# Trying to register something existing in the Transformers library will raise an error
with self.assertRaises(_lowerCamelCase ):
AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase )
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json'''
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json'''
json.dump(
{'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) )
__SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase )
# Now that the config is registered, it can be used as any other config with the auto-API
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = True
try:
AutoConfig.register('''custom''' , _lowerCamelCase )
AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase )
# If remote code is not set, the default is to use local
__SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
self.assertTrue(image_processor.is_local )
# If remote code is disabled, we load the local one.
__SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
self.assertTrue(image_processor.is_local )
# If remote is enabled, we load from the Hub
__SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
self.assertTrue(not hasattr(_lowerCamelCase , '''is_local''' ) )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
| 674 | 0 |
import os
import sys
import tempfile
import torch
from .state import AcceleratorState
from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment
def lowerCamelCase__ ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : str=() , __lowerCamelCase : List[str]=None , __lowerCamelCase : List[str]="no" , __lowerCamelCase : Dict="29500" ):
__UpperCAmelCase : int = False
__UpperCAmelCase : List[Any] = False
if any(key.startswith("""KAGGLE""" ) for key in os.environ.keys() ):
__UpperCAmelCase : Any = True
elif "IPython" in sys.modules:
__UpperCAmelCase : Optional[Any] = """google.colab""" in str(sys.modules["""IPython"""].get_ipython() )
try:
__UpperCAmelCase : Dict = PrecisionType(mixed_precision.lower() )
except ValueError:
raise ValueError(
f"""Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}.""" )
if (in_colab or in_kaggle) and (os.environ.get("""TPU_NAME""" , __lowerCamelCase ) is not None):
# TPU launch
import torch_xla.distributed.xla_multiprocessing as xmp
if len(AcceleratorState._shared_state ) > 0:
raise ValueError(
"""To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside """
"""your training function. Restart your notebook and make sure no cells initializes an """
"""`Accelerator`.""" )
if num_processes is None:
__UpperCAmelCase : int = 8
__UpperCAmelCase : Optional[Any] = PrepareForLaunch(__lowerCamelCase , distributed_type="""TPU""" )
print(f"""Launching a training on {num_processes} TPU cores.""" )
xmp.spawn(__lowerCamelCase , args=__lowerCamelCase , nprocs=__lowerCamelCase , start_method="""fork""" )
elif in_colab:
# No need for a distributed launch otherwise as it's either CPU or one GPU.
if torch.cuda.is_available():
print("""Launching training on one GPU.""" )
else:
print("""Launching training on one CPU.""" )
function(*__lowerCamelCase )
else:
if num_processes is None:
raise ValueError(
"""You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call.""" )
if num_processes > 1:
# Multi-GPU launch
from torch.multiprocessing import start_processes
from torch.multiprocessing.spawn import ProcessRaisedException
if len(AcceleratorState._shared_state ) > 0:
raise ValueError(
"""To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized """
"""inside your training function. Restart your notebook and make sure no cells initializes an """
"""`Accelerator`.""" )
if torch.cuda.is_initialized():
raise ValueError(
"""To launch a multi-GPU training from your notebook, you need to avoid running any instruction """
"""using `torch.cuda` in any cell. Restart your notebook and make sure no cells use any CUDA """
"""function.""" )
# torch.distributed will expect a few environment variable to be here. We set the ones common to each
# process here (the other ones will be set be the launcher).
with patch_environment(
world_size=__lowerCamelCase , master_addr="""127.0.01""" , master_port=__lowerCamelCase , mixed_precision=__lowerCamelCase ):
__UpperCAmelCase : Dict = PrepareForLaunch(__lowerCamelCase , distributed_type="""MULTI_GPU""" )
print(f"""Launching training on {num_processes} GPUs.""" )
try:
start_processes(__lowerCamelCase , args=__lowerCamelCase , nprocs=__lowerCamelCase , start_method="""fork""" )
except ProcessRaisedException as e:
if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]:
raise RuntimeError(
"""CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. """
"""This likely stems from an outside import causing issues once the `notebook_launcher()` is called. """
"""Please review your imports and test them when running the `notebook_launcher()` to identify """
"""which one is problematic.""" ) from e
else:
# No need for a distributed launch otherwise as it's either CPU, GPU or MPS.
if is_mps_available():
__UpperCAmelCase : Union[str, Any] = """1"""
print("""Launching training on MPS.""" )
elif torch.cuda.is_available():
print("""Launching training on one GPU.""" )
else:
print("""Launching training on CPU.""" )
function(*__lowerCamelCase )
def lowerCamelCase__ ( __lowerCamelCase : str , __lowerCamelCase : List[Any]=() , __lowerCamelCase : Dict=2 ):
from torch.multiprocessing import start_processes
with tempfile.NamedTemporaryFile() as tmp_file:
# torch.distributed will expect a few environment variable to be here. We set the ones common to each
# process here (the other ones will be set be the launcher).
with patch_environment(
world_size=__lowerCamelCase , master_addr="""127.0.01""" , master_port="""29500""" , accelerate_mixed_precision="""no""" , accelerate_debug_rdv_file=tmp_file.name , accelerate_use_cpu="""yes""" , ):
__UpperCAmelCase : Tuple = PrepareForLaunch(__lowerCamelCase , debug=__lowerCamelCase )
start_processes(__lowerCamelCase , args=__lowerCamelCase , nprocs=__lowerCamelCase , start_method="""fork""" )
| 63 |
"""simple docstring"""
from __future__ import annotations
from typing import Any
class snake_case ( __UpperCAmelCase ):
pass
class snake_case :
def __init__( self :List[Any] , _lowerCamelCase :Any ):
__SCREAMING_SNAKE_CASE : Any = data
__SCREAMING_SNAKE_CASE : Node | None = None
def __iter__( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : List[str] = self
__SCREAMING_SNAKE_CASE : List[str] = []
while node:
if node in visited:
raise ContainsLoopError
visited.append(_lowerCamelCase )
yield node.data
__SCREAMING_SNAKE_CASE : List[str] = node.next_node
@property
def SCREAMING_SNAKE_CASE_ ( self :Any ):
try:
list(self )
return False
except ContainsLoopError:
return True
if __name__ == "__main__":
_lowerCamelCase = Node(1)
_lowerCamelCase = Node(2)
_lowerCamelCase = Node(3)
_lowerCamelCase = Node(4)
print(root_node.has_loop) # False
_lowerCamelCase = root_node.next_node
print(root_node.has_loop) # True
_lowerCamelCase = Node(5)
_lowerCamelCase = Node(6)
_lowerCamelCase = Node(5)
_lowerCamelCase = Node(6)
print(root_node.has_loop) # False
_lowerCamelCase = Node(1)
print(root_node.has_loop) # False
| 674 | 0 |
# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run
import doctest
import sys
import warnings
from os.path import abspath, dirname, join
import _pytest
from transformers.testing_utils import HfDoctestModule, HfDocTestParser
# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
lowercase_ : Optional[Any] = abspath(join(dirname(__file__), 'src'))
sys.path.insert(1, git_repo_path)
# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action='ignore', category=FutureWarning)
def A__ ( snake_case_ : Optional[Any] ):
config.addinivalue_line(
'''markers''' , '''is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested''' )
config.addinivalue_line(
'''markers''' , '''is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested''' )
config.addinivalue_line('''markers''' , '''is_pipeline_test: mark test to run only when pipelines are tested''' )
config.addinivalue_line('''markers''' , '''is_staging_test: mark test to run only in the staging environment''' )
config.addinivalue_line('''markers''' , '''accelerate_tests: mark test that require accelerate''' )
config.addinivalue_line('''markers''' , '''tool_tests: mark the tool tests that are run on their specific schedule''' )
def A__ ( snake_case_ : int ):
from transformers.testing_utils import pytest_addoption_shared
pytest_addoption_shared(snake_case_ )
def A__ ( snake_case_ : Dict ):
from transformers.testing_utils import pytest_terminal_summary_main
SCREAMING_SNAKE_CASE__: Dict= terminalreporter.config.getoption('''--make-reports''' )
if make_reports:
pytest_terminal_summary_main(snake_case_ , id=snake_case_ )
def A__ ( snake_case_ : int , snake_case_ : Dict ):
# If no tests are collected, pytest exists with code 5, which makes the CI fail.
if exitstatus == 5:
SCREAMING_SNAKE_CASE__: Optional[Any]= 0
# Doctest custom flag to ignore output.
lowercase_ : Optional[Any] = doctest.register_optionflag('IGNORE_RESULT')
lowercase_ : Dict = doctest.OutputChecker
class _lowerCamelCase ( UpperCamelCase_ ):
def UpperCamelCase_ ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) -> Optional[int]:
if IGNORE_RESULT & optionflags:
return True
return OutputChecker.check_output(self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )
lowercase_ : Any = CustomOutputChecker
lowercase_ : List[str] = HfDoctestModule
lowercase_ : int = HfDocTestParser
| 64 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_lowerCamelCase = logging.get_logger(__name__)
_lowerCamelCase = {
'''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''',
}
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = '''roc_bert'''
def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ):
__SCREAMING_SNAKE_CASE : List[str] = vocab_size
__SCREAMING_SNAKE_CASE : int = max_position_embeddings
__SCREAMING_SNAKE_CASE : List[str] = hidden_size
__SCREAMING_SNAKE_CASE : str = num_hidden_layers
__SCREAMING_SNAKE_CASE : int = num_attention_heads
__SCREAMING_SNAKE_CASE : Any = intermediate_size
__SCREAMING_SNAKE_CASE : Optional[int] = hidden_act
__SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob
__SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob
__SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range
__SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size
__SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps
__SCREAMING_SNAKE_CASE : Optional[int] = use_cache
__SCREAMING_SNAKE_CASE : str = enable_pronunciation
__SCREAMING_SNAKE_CASE : List[str] = enable_shape
__SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim
__SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size
__SCREAMING_SNAKE_CASE : str = shape_embed_dim
__SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size
__SCREAMING_SNAKE_CASE : Tuple = concat_input
__SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type
__SCREAMING_SNAKE_CASE : str = classifier_dropout
super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
| 674 | 0 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__UpperCAmelCase = {
'configuration_trajectory_transformer': [
'TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP',
'TrajectoryTransformerConfig',
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCAmelCase = [
'TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
'TrajectoryTransformerModel',
'TrajectoryTransformerPreTrainedModel',
'load_tf_weights_in_trajectory_transformer',
]
if TYPE_CHECKING:
from .configuration_trajectory_transformer import (
TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
TrajectoryTransformerConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_trajectory_transformer import (
TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TrajectoryTransformerModel,
TrajectoryTransformerPreTrainedModel,
load_tf_weights_in_trajectory_transformer,
)
else:
import sys
__UpperCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 65 |
"""simple docstring"""
import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List
import git
import torch
from torch.utils.data import Dataset
from transformers import BartTokenizer, RagTokenizer, TaTokenizer
def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {}
__SCREAMING_SNAKE_CASE : Optional[int] = padding_side
return tokenizer(
[line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , )
def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 )
if attention_mask is None:
return input_ids[:, keep_column_mask]
else:
return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])
class snake_case ( __UpperCAmelCase ):
def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ):
super().__init__()
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' )
__SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' )
__SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file )
__SCREAMING_SNAKE_CASE : List[str] = max_source_length
__SCREAMING_SNAKE_CASE : Dict = max_target_length
assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}'''
__SCREAMING_SNAKE_CASE : Dict = tokenizer
__SCREAMING_SNAKE_CASE : Union[str, Any] = prefix
if n_obs is not None:
__SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs]
__SCREAMING_SNAKE_CASE : List[str] = src_lang
__SCREAMING_SNAKE_CASE : str = tgt_lang
def __len__( self :int ):
return len(self.src_lens )
def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ):
__SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1
__SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' )
__SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' )
assert source_line, f'''empty source line for index {index}'''
assert tgt_line, f'''empty tgt line for index {index}'''
# Need to add eos token manually for T5
if isinstance(self.tokenizer , _lowerCamelCase ):
source_line += self.tokenizer.eos_token
tgt_line += self.tokenizer.eos_token
# Pad source and target to the right
__SCREAMING_SNAKE_CASE : Dict = (
self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer
)
__SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer
__SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' )
__SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' )
__SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze()
__SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze()
__SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze()
return {
"input_ids": source_ids,
"attention_mask": src_mask,
"decoder_input_ids": target_ids,
}
@staticmethod
def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ):
return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()]
def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ):
__SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] )
__SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] )
__SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] )
__SCREAMING_SNAKE_CASE : str = (
self.tokenizer.generator.pad_token_id
if isinstance(self.tokenizer , _lowerCamelCase )
else self.tokenizer.pad_token_id
)
__SCREAMING_SNAKE_CASE : Union[str, Any] = (
self.tokenizer.question_encoder.pad_token_id
if isinstance(self.tokenizer , _lowerCamelCase )
else self.tokenizer.pad_token_id
)
__SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Dict = {
'''input_ids''': source_ids,
'''attention_mask''': source_mask,
'''decoder_input_ids''': y,
}
return batch
_lowerCamelCase = getLogger(__name__)
def lowerCAmelCase_ ( lowercase_ : List[List] ):
'''simple docstring'''
return list(itertools.chain.from_iterable(lowercase_ ) )
def lowerCAmelCase_ ( lowercase_ : str ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = get_git_info()
save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) )
def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ):
'''simple docstring'''
with open(lowercase_ , '''w''' ) as f:
json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ )
def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ):
'''simple docstring'''
with open(lowercase_ ) as f:
return json.load(lowercase_ )
def lowerCAmelCase_ ( ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ )
__SCREAMING_SNAKE_CASE : List[str] = {
'''repo_id''': str(lowercase_ ),
'''repo_sha''': str(repo.head.object.hexsha ),
'''repo_branch''': str(repo.active_branch ),
'''hostname''': str(socket.gethostname() ),
}
return repo_infos
def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ):
'''simple docstring'''
return list(map(lowercase_ , lowercase_ ) )
def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ):
'''simple docstring'''
with open(lowercase_ , '''wb''' ) as f:
return pickle.dump(lowercase_ , lowercase_ )
def lowerCAmelCase_ ( lowercase_ : Any ):
'''simple docstring'''
def remove_articles(lowercase_ : Dict ):
return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ )
def white_space_fix(lowercase_ : Optional[int] ):
return " ".join(text.split() )
def remove_punc(lowercase_ : Any ):
__SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation )
return "".join(ch for ch in text if ch not in exclude )
def lower(lowercase_ : int ):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) )
def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split()
__SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split()
__SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ )
__SCREAMING_SNAKE_CASE : Tuple = sum(common.values() )
if num_same == 0:
return 0
__SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ )
__SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ )
__SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall)
return fa
def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ):
'''simple docstring'''
return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ )
def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ):
'''simple docstring'''
assert len(lowercase_ ) == len(lowercase_ )
__SCREAMING_SNAKE_CASE : Union[str, Any] = 0
for hypo, pred in zip(lowercase_ , lowercase_ ):
em += exact_match_score(lowercase_ , lowercase_ )
if len(lowercase_ ) > 0:
em /= len(lowercase_ )
return {"em": em}
def lowerCAmelCase_ ( lowercase_ : str ):
'''simple docstring'''
return model_prefix.startswith('''rag''' )
def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params}
# T5 models don't have `dropout` param, they have `dropout_rate` instead
__SCREAMING_SNAKE_CASE : Any = '''dropout_rate'''
for p in extra_params:
if getattr(lowercase_ , lowercase_ , lowercase_ ):
if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ):
logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) )
delattr(lowercase_ , lowercase_ )
continue
__SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p]
setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) )
delattr(lowercase_ , lowercase_ )
return hparams, config
| 674 | 0 |
import os
import shutil
from pathlib import Path
from typing import Optional, Union
import numpy as np
from huggingface_hub import hf_hub_download
from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging
if is_onnx_available():
import onnxruntime as ort
UpperCamelCase = logging.get_logger(__name__)
UpperCamelCase = {
"tensor(bool)": np.bool_,
"tensor(int8)": np.inta,
"tensor(uint8)": np.uinta,
"tensor(int16)": np.intaa,
"tensor(uint16)": np.uintaa,
"tensor(int32)": np.intaa,
"tensor(uint32)": np.uintaa,
"tensor(int64)": np.intaa,
"tensor(uint64)": np.uintaa,
"tensor(float16)": np.floataa,
"tensor(float)": np.floataa,
"tensor(double)": np.floataa,
}
class lowerCAmelCase_ :
def __init__( self , _lowerCAmelCase=None , **_lowerCAmelCase ):
logger.info('`diffusers.OnnxRuntimeModel` is experimental and might change in the future.' )
_lowercase : Optional[Any] = model
_lowercase : Optional[Any] = kwargs.get('model_save_dir' , _lowerCAmelCase )
_lowercase : Optional[Any] = kwargs.get('latest_model_name' , _lowerCAmelCase )
def __call__( self , **_lowerCAmelCase ):
_lowercase : int = {k: np.array(_lowerCAmelCase ) for k, v in kwargs.items()}
return self.model.run(_lowerCAmelCase , _lowerCAmelCase )
@staticmethod
def __a ( _lowerCAmelCase , _lowerCAmelCase=None , _lowerCAmelCase=None ):
if provider is None:
logger.info('No onnxruntime provider specified, using CPUExecutionProvider' )
_lowercase : Any = 'CPUExecutionProvider'
return ort.InferenceSession(_lowerCAmelCase , providers=[provider] , sess_options=_lowerCAmelCase )
def __a ( self , _lowerCAmelCase , _lowerCAmelCase = None , **_lowerCAmelCase ):
_lowercase : Any = file_name if file_name is not None else ONNX_WEIGHTS_NAME
_lowercase : Optional[int] = self.model_save_dir.joinpath(self.latest_model_name )
_lowercase : Union[str, Any] = Path(_lowerCAmelCase ).joinpath(_lowerCAmelCase )
try:
shutil.copyfile(_lowerCAmelCase , _lowerCAmelCase )
except shutil.SameFileError:
pass
# copy external weights (for models >2GB)
_lowercase : Dict = self.model_save_dir.joinpath(_lowerCAmelCase )
if src_path.exists():
_lowercase : str = Path(_lowerCAmelCase ).joinpath(_lowerCAmelCase )
try:
shutil.copyfile(_lowerCAmelCase , _lowerCAmelCase )
except shutil.SameFileError:
pass
def __a ( self , _lowerCAmelCase , **_lowerCAmelCase , ):
if os.path.isfile(_lowerCAmelCase ):
logger.error(F"""Provided path ({save_directory}) should be a directory, not a file""" )
return
os.makedirs(_lowerCAmelCase , exist_ok=_lowerCAmelCase )
# saving model weights/files
self._save_pretrained(_lowerCAmelCase , **_lowerCAmelCase )
@classmethod
def __a ( cls , _lowerCAmelCase , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = False , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None , **_lowerCAmelCase , ):
_lowercase : Optional[Any] = file_name if file_name is not None else ONNX_WEIGHTS_NAME
# load model from local directory
if os.path.isdir(_lowerCAmelCase ):
_lowercase : Optional[int] = OnnxRuntimeModel.load_model(
os.path.join(_lowerCAmelCase , _lowerCAmelCase ) , provider=_lowerCAmelCase , sess_options=_lowerCAmelCase )
_lowercase : Optional[int] = Path(_lowerCAmelCase )
# load model from hub
else:
# download model
_lowercase : Any = hf_hub_download(
repo_id=_lowerCAmelCase , filename=_lowerCAmelCase , use_auth_token=_lowerCAmelCase , revision=_lowerCAmelCase , cache_dir=_lowerCAmelCase , force_download=_lowerCAmelCase , )
_lowercase : Any = Path(_lowerCAmelCase ).parent
_lowercase : str = Path(_lowerCAmelCase ).name
_lowercase : Tuple = OnnxRuntimeModel.load_model(_lowerCAmelCase , provider=_lowerCAmelCase , sess_options=_lowerCAmelCase )
return cls(model=_lowerCAmelCase , **_lowerCAmelCase )
@classmethod
def __a ( cls , _lowerCAmelCase , _lowerCAmelCase = True , _lowerCAmelCase = None , _lowerCAmelCase = None , **_lowerCAmelCase , ):
_lowercase : List[str] = None
if len(str(_lowerCAmelCase ).split('@' ) ) == 2:
_lowercase , _lowercase : List[str] = model_id.split('@' )
return cls._from_pretrained(
model_id=_lowerCAmelCase , revision=_lowerCAmelCase , cache_dir=_lowerCAmelCase , force_download=_lowerCAmelCase , use_auth_token=_lowerCAmelCase , **_lowerCAmelCase , )
| 66 |
"""simple docstring"""
from collections.abc import Callable
import numpy as np
def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) )
__SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) )
__SCREAMING_SNAKE_CASE : List[Any] = ya
__SCREAMING_SNAKE_CASE : Dict = xa
for k in range(lowercase_ ):
__SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] )
__SCREAMING_SNAKE_CASE : int = y[k] + (
(step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ ))
)
x += step_size
return y
if __name__ == "__main__":
import doctest
doctest.testmod()
| 674 | 0 |
def SCREAMING_SNAKE_CASE__ ( snake_case__ :List[str] ) -> int:
_lowercase = len(snake_case__ )
while cur > 1:
# Find the maximum number in arr
_lowercase = arr.index(max(arr[0:cur] ) )
# Reverse from 0 to mi
_lowercase = arr[mi::-1] + arr[mi + 1 : len(snake_case__ )]
# Reverse whole list
_lowercase = arr[cur - 1 :: -1] + arr[cur : len(snake_case__ )]
cur -= 1
return arr
if __name__ == "__main__":
snake_case = input("""Enter numbers separated by a comma:\n""").strip()
snake_case = [int(item) for item in user_input.split(""",""")]
print(pancake_sort(unsorted)) | 67 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...file_utils import _LazyModule, is_torch_available
from ...utils import OptionalDependencyNotAvailable
_lowerCamelCase = {
'''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''],
'''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase = [
'''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''GPTNeoXJapaneseForCausalLM''',
'''GPTNeoXJapaneseLayer''',
'''GPTNeoXJapaneseModel''',
'''GPTNeoXJapanesePreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig
from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_gpt_neox_japanese import (
GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST,
GPTNeoXJapaneseForCausalLM,
GPTNeoXJapaneseLayer,
GPTNeoXJapaneseModel,
GPTNeoXJapanesePreTrainedModel,
)
else:
import sys
_lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 674 | 0 |
import os
from typing import List, Optional, Union
from ...tokenization_utils import PreTrainedTokenizer
from ...tokenization_utils_base import AddedToken
from ...utils import logging
__A = logging.get_logger(__name__)
__A = {"vocab_file": "vocab.txt"}
__A = {
"vocab_file": {
"facebook/esm2_t6_8M_UR50D": "https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt",
"facebook/esm2_t12_35M_UR50D": "https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt",
},
}
__A = {
"facebook/esm2_t6_8M_UR50D": 10_24,
"facebook/esm2_t12_35M_UR50D": 10_24,
}
def lowercase__ ( A_: List[Any] ) -> Dict:
"""simple docstring"""
with open(A_ , """r""" ) as f:
__UpperCAmelCase =f.read().splitlines()
return [l.strip() for l in lines]
class _A ( UpperCamelCase ):
"""simple docstring"""
lowerCamelCase : List[Any] = VOCAB_FILES_NAMES
lowerCamelCase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP
lowerCamelCase : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowerCamelCase : List[Any] = ['input_ids', 'attention_mask']
def __init__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[Any]="<unk>" , __SCREAMING_SNAKE_CASE : str="<cls>" , __SCREAMING_SNAKE_CASE : Tuple="<pad>" , __SCREAMING_SNAKE_CASE : List[str]="<mask>" , __SCREAMING_SNAKE_CASE : Dict="<eos>" , **__SCREAMING_SNAKE_CASE : List[str] , ) -> Dict:
super().__init__(**__SCREAMING_SNAKE_CASE )
__UpperCAmelCase =load_vocab_file(__SCREAMING_SNAKE_CASE )
__UpperCAmelCase =dict(enumerate(self.all_tokens ) )
__UpperCAmelCase ={tok: ind for ind, tok in enumerate(self.all_tokens )}
__UpperCAmelCase =unk_token
__UpperCAmelCase =cls_token
__UpperCAmelCase =pad_token
__UpperCAmelCase =mask_token
__UpperCAmelCase =eos_token
__UpperCAmelCase =self.all_tokens
self._create_trie(self.unique_no_split_tokens )
def _a ( self : Any , __SCREAMING_SNAKE_CASE : int ) -> str:
return self._id_to_token.get(__SCREAMING_SNAKE_CASE , self.unk_token )
def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str ) -> int:
return self._token_to_id.get(__SCREAMING_SNAKE_CASE , self._token_to_id.get(self.unk_token ) )
def _a ( self : Dict , __SCREAMING_SNAKE_CASE : List[Any] , **__SCREAMING_SNAKE_CASE : str ) -> Optional[int]:
return text.split()
def _a ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=False ) -> Tuple:
return len(self._id_to_token )
def _a ( self : Optional[int] ) -> Any:
return {token: i for i, token in enumerate(self.all_tokens )}
def _a ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : str ) -> int:
return self._token_to_id.get(__SCREAMING_SNAKE_CASE , self._token_to_id.get(self.unk_token ) )
def _a ( self : int , __SCREAMING_SNAKE_CASE : int ) -> str:
return self._id_to_token.get(__SCREAMING_SNAKE_CASE , self.unk_token )
def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : List[int] , __SCREAMING_SNAKE_CASE : Optional[List[int]] = None ) -> List[int]:
__UpperCAmelCase =[self.cls_token_id]
__UpperCAmelCase =[self.eos_token_id] # No sep token in ESM vocabulary
if token_ids_a is None:
if self.eos_token_id is None:
return cls + token_ids_a
else:
return cls + token_ids_a + sep
elif self.eos_token_id is None:
raise ValueError("""Cannot tokenize multiple sequences when EOS token is not set!""" )
return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token
def _a ( self : str , __SCREAMING_SNAKE_CASE : List , __SCREAMING_SNAKE_CASE : Optional[List] = None , __SCREAMING_SNAKE_CASE : bool = False ) -> List[int]:
if already_has_special_tokens:
if token_ids_a is not None:
raise ValueError(
"""You should not supply a second sequence if the provided sequence of """
"""ids is already formatted with special tokens for the model.""" )
return [1 if token in self.all_special_ids else 0 for token in token_ids_a]
__UpperCAmelCase =[1] + ([0] * len(__SCREAMING_SNAKE_CASE )) + [1]
if token_ids_a is not None:
mask += [0] * len(__SCREAMING_SNAKE_CASE ) + [1]
return mask
def _a ( self : Dict , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Tuple ) -> int:
__UpperCAmelCase =os.path.join(__SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + """vocab.txt""" )
with open(__SCREAMING_SNAKE_CASE , """w""" ) as f:
f.write("""\n""".join(self.all_tokens ) )
return (vocab_file,)
@property
def _a ( self : Optional[int] ) -> int:
return self.get_vocab_size(with_added_tokens=__SCREAMING_SNAKE_CASE )
def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Union[List[str], List[AddedToken]] , __SCREAMING_SNAKE_CASE : bool = False ) -> int:
return super()._add_tokens(__SCREAMING_SNAKE_CASE , special_tokens=__SCREAMING_SNAKE_CASE )
| 68 |
"""simple docstring"""
from __future__ import annotations
from typing import Any
class snake_case :
def __init__( self :Optional[Any] , _lowerCamelCase :int ):
__SCREAMING_SNAKE_CASE : int = num_of_nodes
__SCREAMING_SNAKE_CASE : list[list[int]] = []
__SCREAMING_SNAKE_CASE : dict[int, int] = {}
def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ):
self.m_edges.append([u_node, v_node, weight] )
def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ):
if self.m_component[u_node] == u_node:
return u_node
return self.find_component(self.m_component[u_node] )
def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ):
if self.m_component[u_node] != u_node:
for k in self.m_component:
__SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ):
if component_size[u_node] <= component_size[v_node]:
__SCREAMING_SNAKE_CASE : List[Any] = v_node
component_size[v_node] += component_size[u_node]
self.set_component(_lowerCamelCase )
elif component_size[u_node] >= component_size[v_node]:
__SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase )
component_size[u_node] += component_size[v_node]
self.set_component(_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
__SCREAMING_SNAKE_CASE : Optional[int] = []
__SCREAMING_SNAKE_CASE : str = 0
__SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes
# A list of components (initialized to all of the nodes)
for node in range(self.m_num_of_nodes ):
self.m_component.update({node: node} )
component_size.append(1 )
__SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes
while num_of_components > 1:
for edge in self.m_edges:
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge
__SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u]
__SCREAMING_SNAKE_CASE : int = self.m_component[v]
if u_component != v_component:
for component in (u_component, v_component):
if (
minimum_weight_edge[component] == -1
or minimum_weight_edge[component][2] > w
):
__SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w]
for edge in minimum_weight_edge:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge
__SCREAMING_SNAKE_CASE : Tuple = self.m_component[u]
__SCREAMING_SNAKE_CASE : int = self.m_component[v]
if u_component != v_component:
mst_weight += w
self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' )
num_of_components -= 1
__SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes
print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' )
def lowerCAmelCase_ ( ):
'''simple docstring'''
if __name__ == "__main__":
import doctest
doctest.testmod()
| 674 | 0 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
a : List[str] = {'''configuration_swin''': ['''SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SwinConfig''', '''SwinOnnxConfig''']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : List[str] = [
'''SWIN_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''SwinForImageClassification''',
'''SwinForMaskedImageModeling''',
'''SwinModel''',
'''SwinPreTrainedModel''',
'''SwinBackbone''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : Optional[Any] = [
'''TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TFSwinForImageClassification''',
'''TFSwinForMaskedImageModeling''',
'''TFSwinModel''',
'''TFSwinPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_swin import SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinConfig, SwinOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_swin import (
SWIN_PRETRAINED_MODEL_ARCHIVE_LIST,
SwinBackbone,
SwinForImageClassification,
SwinForMaskedImageModeling,
SwinModel,
SwinPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_swin import (
TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST,
TFSwinForImageClassification,
TFSwinForMaskedImageModeling,
TFSwinModel,
TFSwinPreTrainedModel,
)
else:
import sys
a : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 69 |
"""simple docstring"""
import argparse
import pickle
import numpy as np
import torch
from torch import nn
from transformers import ReformerConfig, ReformerModelWithLMHead
from transformers.utils import logging
logging.set_verbosity_info()
def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ):
'''simple docstring'''
assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match'''
__SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ )
if bias is not None:
assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match'''
__SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ )
def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] )
__SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] )
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] )
set_param(
torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , )
def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] )
__SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] )
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] )
__SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] )
set_param(
torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , )
def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = weights[0][0][0]
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] )
__SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] )
set_param(
torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , )
# lsh weights + output
__SCREAMING_SNAKE_CASE : Tuple = weights[0][1]
if len(lowercase_ ) < 4:
set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ )
else:
set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ )
# intermediate weighs
__SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2]
# Chunked Feed Forward
if len(lowercase_ ) == 4:
__SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2]
# layernorm 2
__SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] )
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] )
set_param(
torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , )
# intermediate dense
__SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] )
set_param(
torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , )
# intermediate out
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] )
__SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] )
set_param(
torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , )
def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Dict = torch_model.reformer
# word embeds
__SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] )
set_param(
torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , )
if isinstance(weights[3] , lowercase_ ):
__SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings
for emb_idx in range(len(position_embeddings.weights ) ):
__SCREAMING_SNAKE_CASE : Dict = np.asarray(weights[3][emb_idx][0] )
assert (
position_embeddings.weights[emb_idx].shape == emb_weights.shape
), F'''{position_embeddings[emb_idx]} emb does not match'''
__SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) )
__SCREAMING_SNAKE_CASE : List[Any] = weights[5]
assert len(torch_model_reformer.encoder.layers ) * 4 == len(
lowercase_ ), "HF and trax model do not have the same number of layers"
for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)]
set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ )
# output layer norm
__SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] )
set_param(
torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , )
# output embeddings
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] )
__SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] )
set_param(
torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , )
def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ )
print(F'''Building PyTorch model from configuration: {config}''' )
__SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ )
with open(lowercase_ , '''rb''' ) as f:
__SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights''']
set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size )
# Save pytorch-model
print(F'''Save PyTorch model to {pytorch_dump_path}''' )
torch.save(model.state_dict() , lowercase_ )
if __name__ == "__main__":
_lowerCamelCase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--trax_model_pkl_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.'''
)
parser.add_argument(
'''--config_file''',
default=None,
type=str,
required=True,
help=(
'''The config json file corresponding to the pre-trained Reformer model. \n'''
'''This specifies the model architecture.'''
),
)
parser.add_argument(
'''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
)
_lowerCamelCase = parser.parse_args()
convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
| 674 | 0 |
import unittest
from transformers import is_torch_available
from transformers.testing_utils import require_torch
if is_torch_available():
import torch
from transformers.activations import gelu_new, gelu_python, get_activation
@require_torch
class A( unittest.TestCase ):
'''simple docstring'''
def a__ ( self : Optional[int] ) -> Optional[Any]:
"""simple docstring"""
lowerCamelCase_ = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] )
lowerCamelCase_ = get_activation('gelu' )
self.assertTrue(torch.allclose(gelu_python(A_ ) , torch_builtin(A_ ) ) )
self.assertFalse(torch.allclose(gelu_python(A_ ) , gelu_new(A_ ) ) )
def a__ ( self : Union[str, Any] ) -> List[str]:
"""simple docstring"""
lowerCamelCase_ = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] )
lowerCamelCase_ = get_activation('gelu' )
lowerCamelCase_ = get_activation('gelu_10' )
lowerCamelCase_ = torch_builtin(A_ )
lowerCamelCase_ = geluaa(A_ )
lowerCamelCase_ = torch.where(y_gelu_aa < 10.0 , 1 , 0 )
self.assertTrue(torch.max(A_ ).item() == 10.0 )
self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) )
def a__ ( self : Optional[Any] ) -> List[Any]:
"""simple docstring"""
get_activation('gelu' )
get_activation('gelu_10' )
get_activation('gelu_fast' )
get_activation('gelu_new' )
get_activation('gelu_python' )
get_activation('gelu_pytorch_tanh' )
get_activation('linear' )
get_activation('mish' )
get_activation('quick_gelu' )
get_activation('relu' )
get_activation('sigmoid' )
get_activation('silu' )
get_activation('swish' )
get_activation('tanh' )
with self.assertRaises(A_ ):
get_activation('bogus' )
with self.assertRaises(A_ ):
get_activation(A_ )
def a__ ( self : Tuple ) -> List[str]:
"""simple docstring"""
lowerCamelCase_ = get_activation('gelu' )
lowerCamelCase_ = 1
lowerCamelCase_ = get_activation('gelu' )
self.assertEqual(acta.a , 1 )
with self.assertRaises(A_ ):
lowerCamelCase_ = acta.a
| 70 |
"""simple docstring"""
from typing import Callable, Optional, Union
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_lowerCamelCase = logging.get_logger(__name__)
_lowerCamelCase = {
'''microsoft/xprophetnet-large-wiki100-cased''': (
'''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json'''
),
}
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = '''xlm-prophetnet'''
lowerCamelCase__ = ['''past_key_values''']
lowerCamelCase__ = {
'''num_attention_heads''': '''num_encoder_attention_heads''',
}
def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size
__SCREAMING_SNAKE_CASE : Optional[int] = hidden_size
__SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim
__SCREAMING_SNAKE_CASE : str = num_encoder_layers
__SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads
__SCREAMING_SNAKE_CASE : str = decoder_ffn_dim
__SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers
__SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads
__SCREAMING_SNAKE_CASE : Dict = max_position_embeddings
__SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter)
__SCREAMING_SNAKE_CASE : Any = activation_function
# parameters for xlmprophetnet
__SCREAMING_SNAKE_CASE : List[Any] = ngram
__SCREAMING_SNAKE_CASE : int = num_buckets
__SCREAMING_SNAKE_CASE : List[str] = relative_max_distance
__SCREAMING_SNAKE_CASE : str = disable_ngram_loss
__SCREAMING_SNAKE_CASE : Optional[int] = eps
# 3 Types of Dropout
__SCREAMING_SNAKE_CASE : int = attention_dropout
__SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout
__SCREAMING_SNAKE_CASE : Dict = dropout
__SCREAMING_SNAKE_CASE : Any = use_cache
super().__init__(
pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , )
@property
def SCREAMING_SNAKE_CASE_ ( self :int ):
return self.num_encoder_layers + self.num_decoder_layers
@num_hidden_layers.setter
def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ):
raise NotImplementedError(
'''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and'''
''' `num_decoder_layers`.''' )
| 674 | 0 |
'''simple docstring'''
def a__ ( _SCREAMING_SNAKE_CASE : int = 4_00_00_00 ) -> int:
"""simple docstring"""
UpperCAmelCase_ : Optional[Any] = [0, 1]
UpperCAmelCase_ : Optional[Any] = 0
while fib[i] <= n:
fib.append(fib[i] + fib[i + 1] )
if fib[i + 2] > n:
break
i += 1
UpperCAmelCase_ : Dict = 0
for j in range(len(_SCREAMING_SNAKE_CASE ) - 1 ):
if fib[j] % 2 == 0:
total += fib[j]
return total
if __name__ == "__main__":
print(f"""{solution() = }""")
| 71 |
"""simple docstring"""
import ast
import os
import re
import shutil
import tempfile
import unittest
from unittest import mock
import torch
from accelerate.test_utils.examples import compare_against_test
from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow
from accelerate.utils import write_basic_config
# DataLoaders built from `test_samples/MRPC` for quick testing
# Should mock `{script_name}.get_dataloaders` via:
# @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders)
_lowerCamelCase = [
'''cross_validation.py''',
'''gradient_accumulation.py''',
'''local_sgd.py''',
'''multi_process_metrics.py''',
'''memory.py''',
'''automatic_gradient_accumulation.py''',
'''fsdp_with_peak_mem_tracking.py''',
'''deepspeed_with_config_support.py''',
'''megatron_lm_gpt_pretraining.py''',
]
class snake_case ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ):
__SCREAMING_SNAKE_CASE : List[str] = None
__SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) )
__SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' )
for item in os.listdir(_lowerCamelCase ):
if item not in EXCLUDE_EXAMPLES:
__SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase )
if os.path.isfile(_lowerCamelCase ) and ".py" in item_path:
with self.subTest(
tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ):
__SCREAMING_SNAKE_CASE : Tuple = compare_against_test(
os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase )
if special_strings is not None:
for string in special_strings:
__SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' )
self.assertEqual(_lowerCamelCase , '''''' )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase )
self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) )
__SCREAMING_SNAKE_CASE : Optional[int] = [
''' ''' * 1_6 + '''{\n\n''',
''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''',
''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''',
''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''',
''' ''' * 2_0 + '''"epoch": epoch,\n\n''',
''' ''' * 1_6 + '''},\n\n''',
''' ''' * 1_6 + '''step=epoch,\n''',
''' ''' * 1_2,
''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''',
]
self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
@mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} )
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = False
@classmethod
def SCREAMING_SNAKE_CASE_ ( cls :Dict ):
super().setUpClass()
__SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp()
__SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' )
write_basic_config(save_location=cls.configPath )
__SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath]
@classmethod
def SCREAMING_SNAKE_CASE_ ( cls :Dict ):
super().tearDownClass()
shutil.rmtree(cls._tmpdir )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
__SCREAMING_SNAKE_CASE : str = f'''
examples/by_feature/checkpointing.py
--checkpointing_steps epoch
--output_dir {self.tmpdir}
'''.split()
run_command(self._launch_args + testargs )
self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
__SCREAMING_SNAKE_CASE : Optional[Any] = f'''
examples/by_feature/checkpointing.py
--checkpointing_steps 1
--output_dir {self.tmpdir}
'''.split()
__SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs )
self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
__SCREAMING_SNAKE_CASE : Optional[int] = f'''
examples/by_feature/checkpointing.py
--resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )}
'''.split()
__SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase )
self.assertNotIn('''epoch 0:''' , _lowerCamelCase )
self.assertIn('''epoch 1:''' , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Optional[int] = f'''
examples/by_feature/checkpointing.py
--resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )}
'''.split()
__SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase )
if torch.cuda.is_available():
__SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count()
else:
__SCREAMING_SNAKE_CASE : Optional[int] = 1
if num_processes > 1:
self.assertNotIn('''epoch 0:''' , _lowerCamelCase )
self.assertIn('''epoch 1:''' , _lowerCamelCase )
else:
self.assertIn('''epoch 0:''' , _lowerCamelCase )
self.assertIn('''epoch 1:''' , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE : Optional[Any] = '''
examples/by_feature/cross_validation.py
--num_folds 2
'''.split()
with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1]
__SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase )
self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 )
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py''']
run_command(self._launch_args + testargs )
@require_trackers
@mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
with tempfile.TemporaryDirectory() as tmpdir:
__SCREAMING_SNAKE_CASE : int = f'''
examples/by_feature/tracking.py
--with_tracking
--project_dir {tmpdir}
'''.split()
run_command(self._launch_args + testargs )
self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py''']
run_command(self._launch_args + testargs )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
__SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py''']
run_command(self._launch_args + testargs )
| 674 | 0 |
'''simple docstring'''
import unicodedata
from dataclasses import dataclass
from typing import Optional, Union
import numpy as np
from transformers.data.data_collator import DataCollatorMixin
from transformers.file_utils import PaddingStrategy
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
def UpperCamelCase ( lowercase_ : List[str] , lowercase_ : Union[str, Any] , lowercase_ : Dict , lowercase_ : Tuple ) -> List[Any]:
'''simple docstring'''
if isinstance(lowercase_ , lowercase_ ):
lowercase =np.full((len(lowercase_ ), sequence_length, 2) , lowercase_ )
else:
lowercase =np.full((len(lowercase_ ), sequence_length) , lowercase_ )
for i, tensor in enumerate(lowercase_ ):
if padding_side == "right":
if isinstance(lowercase_ , lowercase_ ):
lowercase =tensor[:sequence_length]
else:
lowercase =tensor[:sequence_length]
else:
if isinstance(lowercase_ , lowercase_ ):
lowercase =tensor[:sequence_length]
else:
lowercase =tensor[:sequence_length]
return out_tensor.tolist()
def UpperCamelCase ( lowercase_ : Optional[Any] ) -> str:
'''simple docstring'''
lowercase =ord(lowercase_ )
if (cp >= 3_3 and cp <= 4_7) or (cp >= 5_8 and cp <= 6_4) or (cp >= 9_1 and cp <= 9_6) or (cp >= 1_2_3 and cp <= 1_2_6):
return True
lowercase =unicodedata.category(lowercase_ )
if cat.startswith('''P''' ):
return True
return False
@dataclass
class __magic_name__ ( __SCREAMING_SNAKE_CASE ):
UpperCamelCase__ = 42
UpperCamelCase__ = True
UpperCamelCase__ = None
UpperCamelCase__ = None
UpperCamelCase__ = -1_00
UpperCamelCase__ = "pt"
def _A( self , snake_case_ ):
import torch
lowercase ='''label''' if '''label''' in features[0].keys() else '''labels'''
lowercase =[feature[label_name] for feature in features] if label_name in features[0].keys() else None
lowercase =self.tokenizer.pad(
snake_case_ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' if labels is None else None , )
if labels is None:
return batch
lowercase =torch.tensor(batch['''entity_ids'''] ).shape[1]
lowercase =self.tokenizer.padding_side
if padding_side == "right":
lowercase =[
list(snake_case_ ) + [self.label_pad_token_id] * (sequence_length - len(snake_case_ )) for label in labels
]
else:
lowercase =[
[self.label_pad_token_id] * (sequence_length - len(snake_case_ )) + list(snake_case_ ) for label in labels
]
lowercase =[feature['''ner_tags'''] for feature in features]
lowercase =padding_tensor(snake_case_ , -1 , snake_case_ , snake_case_ )
lowercase =[feature['''original_entity_spans'''] for feature in features]
lowercase =padding_tensor(snake_case_ , (-1, -1) , snake_case_ , snake_case_ )
lowercase ={k: torch.tensor(snake_case_ , dtype=torch.intaa ) for k, v in batch.items()}
return batch
| 72 |
"""simple docstring"""
import argparse
import logging
import os
import time
import timeit
import datasets
import numpy as np
import pycuda.autoinit # noqa: F401
import pycuda.driver as cuda
import tensorrt as trt
import torch
from absl import logging as absl_logging
from accelerate import Accelerator
from datasets import load_dataset, load_metric
from torch.utils.data import DataLoader
from utils_qa import postprocess_qa_predictions
import transformers
from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed
from transformers.trainer_pt_utils import nested_concat, nested_truncate
_lowerCamelCase = trt.Logger(trt.Logger.WARNING)
_lowerCamelCase = absl_logging.get_absl_logger()
absl_logger.setLevel(logging.WARNING)
_lowerCamelCase = logging.getLogger(__name__)
_lowerCamelCase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--onnx_model_path''',
default=None,
type=str,
required=True,
help='''Path to ONNX model: ''',
)
parser.add_argument(
'''--output_dir''',
default=None,
type=str,
required=True,
help='''The output directory where the model checkpoints and predictions will be written.''',
)
# Other parameters
parser.add_argument(
'''--tokenizer_name''',
default='''''',
type=str,
required=True,
help='''Pretrained tokenizer name or path if not the same as model_name''',
)
parser.add_argument(
'''--version_2_with_negative''',
action='''store_true''',
help='''If true, the SQuAD examples contain some that do not have an answer.''',
)
parser.add_argument(
'''--null_score_diff_threshold''',
type=float,
default=0.0,
help='''If null_score - best_non_null is greater than the threshold predict null.''',
)
parser.add_argument(
'''--max_seq_length''',
default=3_84,
type=int,
help=(
'''The maximum total input sequence length after WordPiece tokenization. Sequences '''
'''longer than this will be truncated, and sequences shorter than this will be padded.'''
),
)
parser.add_argument(
'''--doc_stride''',
default=1_28,
type=int,
help='''When splitting up a long document into chunks, how much stride to take between chunks.''',
)
parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''')
parser.add_argument(
'''--n_best_size''',
default=20,
type=int,
help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''',
)
parser.add_argument(
'''--max_answer_length''',
default=30,
type=int,
help=(
'''The maximum length of an answer that can be generated. This is needed because the start '''
'''and end predictions are not conditioned on one another.'''
),
)
parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''')
parser.add_argument(
'''--dataset_name''',
type=str,
default=None,
required=True,
help='''The name of the dataset to use (via the datasets library).''',
)
parser.add_argument(
'''--dataset_config_name''',
type=str,
default=None,
help='''The configuration name of the dataset to use (via the datasets library).''',
)
parser.add_argument(
'''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.'''
)
parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''')
parser.add_argument(
'''--fp16''',
action='''store_true''',
help='''Whether to use 16-bit (mixed) precision instead of 32-bit''',
)
parser.add_argument(
'''--int8''',
action='''store_true''',
help='''Whether to use INT8''',
)
_lowerCamelCase = parser.parse_args()
if args.tokenizer_name:
_lowerCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True)
else:
raise ValueError(
'''You are instantiating a new tokenizer from scratch. This is not supported by this script.'''
'''You can do it from another script, save it, and load it from here, using --tokenizer_name.'''
)
logger.info('''Training/evaluation parameters %s''', args)
_lowerCamelCase = args.per_device_eval_batch_size
_lowerCamelCase = (args.eval_batch_size, args.max_seq_length)
# TRT Engine properties
_lowerCamelCase = True
_lowerCamelCase = '''temp_engine/bert-fp32.engine'''
if args.fpaa:
_lowerCamelCase = '''temp_engine/bert-fp16.engine'''
if args.inta:
_lowerCamelCase = '''temp_engine/bert-int8.engine'''
# import ONNX file
if not os.path.exists('''temp_engine'''):
os.makedirs('''temp_engine''')
_lowerCamelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser(
network, TRT_LOGGER
) as parser:
with open(args.onnx_model_path, '''rb''') as model:
if not parser.parse(model.read()):
for error in range(parser.num_errors):
print(parser.get_error(error))
# Query input names and shapes from parsed TensorRT network
_lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)]
_lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"]
with builder.create_builder_config() as config:
_lowerCamelCase = 1 << 50
if STRICT_TYPES:
config.set_flag(trt.BuilderFlag.STRICT_TYPES)
if args.fpaa:
config.set_flag(trt.BuilderFlag.FPaa)
if args.inta:
config.set_flag(trt.BuilderFlag.INTa)
_lowerCamelCase = builder.create_optimization_profile()
config.add_optimization_profile(profile)
for i in range(len(input_names)):
profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE)
_lowerCamelCase = builder.build_engine(network, config)
# serialize_engine and store in file (can be directly loaded and deserialized):
with open(engine_name, '''wb''') as f:
f.write(engine.serialize())
def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa )
# Copy inputs
cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase_ )
cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase_ )
cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase_ )
# start time
__SCREAMING_SNAKE_CASE : Tuple = time.time()
# Run inference
context.execute_async(
bindings=[int(lowercase_ ) for d_inp in d_inputs] + [int(lowercase_ ), int(lowercase_ )] , stream_handle=stream.handle )
# Transfer predictions back from GPU
cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ )
cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ )
# Synchronize the stream and take time
stream.synchronize()
# end time
__SCREAMING_SNAKE_CASE : List[str] = time.time()
__SCREAMING_SNAKE_CASE : int = end_time - start_time
__SCREAMING_SNAKE_CASE : int = (h_outputa, h_outputa)
# print(outputs)
return outputs, infer_time
# Initialize the accelerator. We will let the accelerator handle device placement for us in this example.
_lowerCamelCase = Accelerator()
# Make one log on every process with the configuration for debugging.
logging.basicConfig(
format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''',
datefmt='''%m/%d/%Y %H:%M:%S''',
level=logging.INFO,
)
# Setup logging, we only want one process per machine to log things on the screen.
# accelerator.is_local_main_process is only True for one process per machine.
logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR)
if accelerator.is_local_main_process:
datasets.utils.logging.set_verbosity_warning()
transformers.utils.logging.set_verbosity_info()
else:
datasets.utils.logging.set_verbosity_error()
transformers.utils.logging.set_verbosity_error()
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
# (the dataset will be downloaded automatically from the datasets Hub).
#
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
# 'text' is found. You can easily tweak this behavior (see below).
if args.dataset_name is not None:
# Downloading and loading a dataset from the hub.
_lowerCamelCase = load_dataset(args.dataset_name, args.dataset_config_name)
else:
raise ValueError('''Evaluation requires a dataset name''')
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
# Preprocessing the datasets.
# Preprocessing is slighlty different for training and evaluation.
_lowerCamelCase = raw_datasets['''validation'''].column_names
_lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0]
_lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1]
_lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2]
# Padding side determines if we do (question|context) or (context|question).
_lowerCamelCase = tokenizer.padding_side == '''right'''
if args.max_seq_length > tokenizer.model_max_length:
logger.warning(
f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the'
f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.'
)
_lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length)
def lowerCAmelCase_ ( lowercase_ : Tuple ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = [q.lstrip() for q in examples[question_column_name]]
# Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results
# in one example possible giving several features when a context is long, each of those features having a
# context that overlaps a bit the context of the previous feature.
__SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer(
examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=lowercase_ , stride=args.doc_stride , return_overflowing_tokens=lowercase_ , return_offsets_mapping=lowercase_ , padding='''max_length''' , )
# Since one example might give us several features if it has a long context, we need a map from a feature to
# its corresponding example. This key gives us just that.
__SCREAMING_SNAKE_CASE : Optional[int] = tokenized_examples.pop('''overflow_to_sample_mapping''' )
# For evaluation, we will need to convert our predictions to substrings of the context, so we keep the
# corresponding example_id and we will store the offset mappings.
__SCREAMING_SNAKE_CASE : Any = []
for i in range(len(tokenized_examples['''input_ids'''] ) ):
# Grab the sequence corresponding to that example (to know what is the context and what is the question).
__SCREAMING_SNAKE_CASE : int = tokenized_examples.sequence_ids(lowercase_ )
__SCREAMING_SNAKE_CASE : str = 1 if pad_on_right else 0
# One example can give several spans, this is the index of the example containing this span of text.
__SCREAMING_SNAKE_CASE : str = sample_mapping[i]
tokenized_examples["example_id"].append(examples['''id'''][sample_index] )
# Set to None the offset_mapping that are not part of the context so it's easy to determine if a token
# position is part of the context or not.
__SCREAMING_SNAKE_CASE : List[str] = [
(o if sequence_ids[k] == context_index else None)
for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] )
]
return tokenized_examples
_lowerCamelCase = raw_datasets['''validation''']
# Validation Feature Creation
_lowerCamelCase = eval_examples.map(
prepare_validation_features,
batched=True,
num_proc=args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not args.overwrite_cache,
desc='''Running tokenizer on validation dataset''',
)
_lowerCamelCase = default_data_collator
_lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping'''])
_lowerCamelCase = DataLoader(
eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size
)
def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Tuple = postprocess_qa_predictions(
examples=lowercase_ , features=lowercase_ , predictions=lowercase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase_ , )
# Format the result to the format the metric expects.
if args.version_2_with_negative:
__SCREAMING_SNAKE_CASE : Union[str, Any] = [
{'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items()
]
else:
__SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()]
__SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples]
return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ )
_lowerCamelCase = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''')
# Evaluation!
logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path)
with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine(
f.read()
) as engine, engine.create_execution_context() as context:
# setup for TRT inferrence
for i in range(len(input_names)):
context.set_binding_shape(i, INPUT_SHAPE)
assert context.all_binding_shapes_specified
def lowerCAmelCase_ ( lowercase_ : Any ):
'''simple docstring'''
return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize
# Allocate device memory for inputs and outputs.
_lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)]
# Allocate output buffer
_lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa)
_lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa)
_lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes)
_lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes)
# Create a stream in which to copy inputs/outputs and run inference.
_lowerCamelCase = cuda.Stream()
# Evaluation
logger.info('''***** Running Evaluation *****''')
logger.info(f' Num examples = {len(eval_dataset)}')
logger.info(f' Batch size = {args.per_device_eval_batch_size}')
_lowerCamelCase = 0.0
_lowerCamelCase = 0
_lowerCamelCase = timeit.default_timer()
_lowerCamelCase = None
for step, batch in enumerate(eval_dataloader):
_lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream)
total_time += infer_time
niter += 1
_lowerCamelCase , _lowerCamelCase = outputs
_lowerCamelCase = torch.tensor(start_logits)
_lowerCamelCase = torch.tensor(end_logits)
# necessary to pad predictions and labels for being gathered
_lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00)
_lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00)
_lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy())
_lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00)
if all_preds is not None:
_lowerCamelCase = nested_truncate(all_preds, len(eval_dataset))
_lowerCamelCase = timeit.default_timer() - start_time
logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset))
# Inference time from TRT
logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 10_00 / niter))
logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00))
logger.info('''Total Number of Inference = %d''', niter)
_lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds)
_lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids)
logger.info(f'Evaluation metrics: {eval_metric}')
| 674 | 0 |
from typing import List, Optional
import numpy as np
from ...processing_utils import ProcessorMixin
from ...utils import to_numpy
class _snake_case ( A__ ):
_lowercase : Tuple = '''EncodecFeatureExtractor'''
_lowercase : Union[str, Any] = ('''T5Tokenizer''', '''T5TokenizerFast''')
def __init__( self , a , a) -> Optional[Any]:
super().__init__(a , a)
SCREAMING_SNAKE_CASE = self.feature_extractor
SCREAMING_SNAKE_CASE = False
def SCREAMING_SNAKE_CASE__ ( self , a=None , a=None , a=True) -> List[str]:
return self.tokenizer.get_decoder_prompt_ids(task=a , language=a , no_timestamps=a)
def __call__( self , *a , **a) -> Dict:
# For backward compatibility
if self._in_target_context_manager:
return self.current_processor(*a , **a)
SCREAMING_SNAKE_CASE = kwargs.pop('audio' , a)
SCREAMING_SNAKE_CASE = kwargs.pop('sampling_rate' , a)
SCREAMING_SNAKE_CASE = kwargs.pop('text' , a)
if len(a) > 0:
SCREAMING_SNAKE_CASE = args[0]
SCREAMING_SNAKE_CASE = args[1:]
if audio is None and text is None:
raise ValueError('You need to specify either an `audio` or `text` input to process.')
if text is not None:
SCREAMING_SNAKE_CASE = self.tokenizer(a , **a)
if audio is not None:
SCREAMING_SNAKE_CASE = self.feature_extractor(a , *a , sampling_rate=a , **a)
if audio is None:
return inputs
elif text is None:
return audio_inputs
else:
SCREAMING_SNAKE_CASE = audio_inputs['input_values']
if "padding_mask" in audio_inputs:
SCREAMING_SNAKE_CASE = audio_inputs['padding_mask']
return inputs
def SCREAMING_SNAKE_CASE__ ( self , *a , **a) -> List[str]:
SCREAMING_SNAKE_CASE = kwargs.pop('audio' , a)
SCREAMING_SNAKE_CASE = kwargs.pop('padding_mask' , a)
if len(a) > 0:
SCREAMING_SNAKE_CASE = args[0]
SCREAMING_SNAKE_CASE = args[1:]
if audio_values is not None:
return self._decode_audio(a , padding_mask=a)
else:
return self.tokenizer.batch_decode(*a , **a)
def SCREAMING_SNAKE_CASE__ ( self , *a , **a) -> Optional[Any]:
return self.tokenizer.decode(*a , **a)
def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[np.ndarray]:
SCREAMING_SNAKE_CASE = to_numpy(a)
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = audio_values.shape
if padding_mask is None:
return list(a)
SCREAMING_SNAKE_CASE = to_numpy(a)
# match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding**
# token (so that the generated audio values are **not** treated as padded tokens)
SCREAMING_SNAKE_CASE = seq_len - padding_mask.shape[-1]
SCREAMING_SNAKE_CASE = 1 - self.feature_extractor.padding_value
SCREAMING_SNAKE_CASE = np.pad(a , ((0, 0), (0, difference)) , 'constant' , constant_values=a)
SCREAMING_SNAKE_CASE = audio_values.tolist()
for i in range(a):
SCREAMING_SNAKE_CASE = np.asarray(audio_values[i])[
padding_mask[i][None, :] != self.feature_extractor.padding_value
]
SCREAMING_SNAKE_CASE = sliced_audio.reshape(a , -1)
return audio_values
| 73 |
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import is_tf_available, is_torch_available
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow
if is_tf_available():
from transformers import (
AutoConfig,
BertConfig,
GPTaConfig,
TaConfig,
TFAutoModel,
TFAutoModelForCausalLM,
TFAutoModelForMaskedLM,
TFAutoModelForPreTraining,
TFAutoModelForQuestionAnswering,
TFAutoModelForSeqaSeqLM,
TFAutoModelForSequenceClassification,
TFAutoModelWithLMHead,
TFBertForMaskedLM,
TFBertForPreTraining,
TFBertForQuestionAnswering,
TFBertForSequenceClassification,
TFBertModel,
TFGPTaLMHeadModel,
TFRobertaForMaskedLM,
TFTaForConditionalGeneration,
)
from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST
from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST
from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST
if is_torch_available():
from transformers import (
AutoModel,
AutoModelForCausalLM,
AutoModelForMaskedLM,
AutoModelForPreTraining,
AutoModelForQuestionAnswering,
AutoModelForSeqaSeqLM,
AutoModelForSequenceClassification,
AutoModelWithLMHead,
BertForMaskedLM,
BertForPreTraining,
BertForQuestionAnswering,
BertForSequenceClassification,
BertModel,
GPTaLMHeadModel,
RobertaForMaskedLM,
TaForConditionalGeneration,
)
@is_pt_tf_cross_test
class snake_case ( unittest.TestCase ):
@slow
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
__SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
__SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Any ):
for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :int ):
for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
__SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
__SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
| 674 | 0 |
import itertools
from dataclasses import dataclass
from typing import List, Optional
import pyarrow as pa
import pyarrow.parquet as pq
import datasets
from datasets.table import table_cast
lowercase_ = datasets.utils.logging.get_logger(__name__)
@dataclass
class __UpperCamelCase ( datasets.BuilderConfig ):
"""simple docstring"""
lowerCAmelCase_ = 1_00_00
lowerCAmelCase_ = None
lowerCAmelCase_ = None
class __UpperCamelCase ( datasets.ArrowBasedBuilder ):
"""simple docstring"""
lowerCAmelCase_ = ParquetConfig
def UpperCAmelCase__ ( self : Any ):
"""simple docstring"""
return datasets.DatasetInfo(features=self.config.features )
def UpperCAmelCase__ ( self : Any , _A : Optional[Any] ):
"""simple docstring"""
if not self.config.data_files:
raise ValueError(F'''At least one data file must be specified, but got data_files={self.config.data_files}''' )
__SCREAMING_SNAKE_CASE : List[str] = dl_manager.download_and_extract(self.config.data_files )
if isinstance(_A , (str, list, tuple) ):
__SCREAMING_SNAKE_CASE : Tuple = data_files
if isinstance(_A , _A ):
__SCREAMING_SNAKE_CASE : Optional[int] = [files]
# Use `dl_manager.iter_files` to skip hidden files in an extracted archive
__SCREAMING_SNAKE_CASE : List[Any] = [dl_manager.iter_files(_A ) for file in files]
return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )]
__SCREAMING_SNAKE_CASE : int = []
for split_name, files in data_files.items():
if isinstance(_A , _A ):
__SCREAMING_SNAKE_CASE : Any = [files]
# Use `dl_manager.iter_files` to skip hidden files in an extracted archive
__SCREAMING_SNAKE_CASE : Optional[int] = [dl_manager.iter_files(_A ) for file in files]
# Infer features is they are stoed in the arrow schema
if self.info.features is None:
for file in itertools.chain.from_iterable(_A ):
with open(_A , '''rb''' ) as f:
__SCREAMING_SNAKE_CASE : Dict = datasets.Features.from_arrow_schema(pq.read_schema(_A ) )
break
splits.append(datasets.SplitGenerator(name=_A , gen_kwargs={'''files''': files} ) )
return splits
def UpperCAmelCase__ ( self : str , _A : pa.Table ):
"""simple docstring"""
if self.info.features is not None:
# more expensive cast to support nested features with keys in a different order
# allows str <-> int/float or str to Audio for example
__SCREAMING_SNAKE_CASE : str = table_cast(_A , self.info.features.arrow_schema )
return pa_table
def UpperCAmelCase__ ( self : Tuple , _A : str ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Optional[int] = self.info.features.arrow_schema if self.info.features is not None else None
if self.info.features is not None and self.config.columns is not None:
if sorted(field.name for field in schema ) != sorted(self.config.columns ):
raise ValueError(
F'''Tried to load parquet data with columns \'{self.config.columns}\' with mismatching features \'{self.info.features}\'''' )
for file_idx, file in enumerate(itertools.chain.from_iterable(_A ) ):
with open(_A , '''rb''' ) as f:
__SCREAMING_SNAKE_CASE : str = pq.ParquetFile(_A )
try:
for batch_idx, record_batch in enumerate(
parquet_file.iter_batches(batch_size=self.config.batch_size , columns=self.config.columns ) ):
__SCREAMING_SNAKE_CASE : Optional[Any] = pa.Table.from_batches([record_batch] )
# Uncomment for debugging (will print the Arrow table size and elements)
# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
yield F'''{file_idx}_{batch_idx}''', self._cast_table(_A )
except ValueError as e:
logger.error(F'''Failed to read file \'{file}\' with error {type(_A )}: {e}''' )
raise
| 74 |
"""simple docstring"""
import os
import re
import warnings
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
if TYPE_CHECKING:
from ...tokenization_utils_base import TextInput
from ...utils import logging
_lowerCamelCase = logging.get_logger(__name__)
_lowerCamelCase = {'''vocab_file''': '''spiece.model'''}
_lowerCamelCase = {
'''vocab_file''': {
'''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''',
'''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''',
'''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''',
'''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''',
'''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''',
}
}
# TODO(PVP) - this should be removed in Transformers v5
_lowerCamelCase = {
'''t5-small''': 5_12,
'''t5-base''': 5_12,
'''t5-large''': 5_12,
'''t5-3b''': 5_12,
'''t5-11b''': 5_12,
}
_lowerCamelCase = '''▁'''
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = VOCAB_FILES_NAMES
lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP
lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowerCamelCase__ = ['''input_ids''', '''attention_mask''']
def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ):
# Add extra_ids to the special token list
if extra_ids > 0 and additional_special_tokens is None:
__SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )]
elif extra_ids > 0 and additional_special_tokens is not None:
# Check that we have the right number of extra_id special tokens
__SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) )
if extra_tokens != extra_ids:
raise ValueError(
f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are'''
''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids'''
''' tokens''' )
if legacy:
logger.warning_once(
f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to'''
''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' )
__SCREAMING_SNAKE_CASE : Optional[Any] = legacy
__SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , )
__SCREAMING_SNAKE_CASE : Tuple = vocab_file
__SCREAMING_SNAKE_CASE : List[str] = extra_ids
__SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(_lowerCamelCase )
@staticmethod
def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ):
if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes:
__SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path]
if init_max_model_length is not None and init_max_model_length != max_model_length:
return init_max_model_length
elif init_max_model_length is None:
warnings.warn(
'''This tokenizer was incorrectly instantiated with a model max length of'''
f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this'''
''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with'''
''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on'''
f''' {pretrained_model_name_or_path} automatically truncating your input to'''
f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences'''
f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with'''
''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please'''
''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , )
return max_model_length
@property
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
return self.sp_model.get_piece_size() + self._extra_ids
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ):
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase )
# normal case: some special tokens
if token_ids_a is None:
return ([0] * len(_lowerCamelCase )) + [1]
return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1]
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
return list(
set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()]
def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ):
if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id:
warnings.warn(
f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated'''
''' eos tokens being added.''' )
return token_ids
else:
return token_ids + [self.eos_token_id]
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ):
__SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id]
if token_ids_a is None:
return len(token_ids_a + eos ) * [0]
return len(token_ids_a + eos + token_ids_a + eos ) * [0]
def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ):
__SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase )
if token_ids_a is None:
return token_ids_a
else:
__SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase )
return token_ids_a + token_ids_a
def __getstate__( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Any = self.__dict__.copy()
__SCREAMING_SNAKE_CASE : List[str] = None
return state
def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ):
__SCREAMING_SNAKE_CASE : Tuple = d
# for backward compatibility
if not hasattr(self , '''sp_model_kwargs''' ):
__SCREAMING_SNAKE_CASE : Optional[int] = {}
__SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ):
# Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at
# the beginning of the text
if not self.legacy:
__SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' )
return super().tokenize(_lowerCamelCase , **_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ):
if not self.legacy:
__SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase )
if is_first:
__SCREAMING_SNAKE_CASE : str = text[1:]
__SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase )
if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ):
__SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:]
return tokens
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ):
if token.startswith('''<extra_id_''' ):
__SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) )
return self.vocab_size - num - 1
return self.sp_model.piece_to_id(_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ):
if index < self.sp_model.get_piece_size():
__SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase )
else:
__SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>'''
return token
def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ):
__SCREAMING_SNAKE_CASE : str = []
__SCREAMING_SNAKE_CASE : Dict = ''''''
__SCREAMING_SNAKE_CASE : Dict = False
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
if not prev_is_special:
out_string += " "
out_string += self.sp_model.decode(_lowerCamelCase ) + token
__SCREAMING_SNAKE_CASE : List[str] = True
__SCREAMING_SNAKE_CASE : str = []
else:
current_sub_tokens.append(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = False
out_string += self.sp_model.decode(_lowerCamelCase )
return out_string.strip()
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ):
if not os.path.isdir(_lowerCamelCase ):
logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' )
return
__SCREAMING_SNAKE_CASE : List[str] = os.path.join(
_lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , _lowerCamelCase )
elif not os.path.isfile(self.vocab_file ):
with open(_lowerCamelCase , '''wb''' ) as fi:
__SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto()
fi.write(_lowerCamelCase )
return (out_vocab_file,)
| 674 | 0 |
'''simple docstring'''
import argparse
import numpy as np
import torch
from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging
logging.set_verbosity_info()
UpperCamelCase__ = logging.get_logger('''transformers.models.speecht5''')
def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Union[str, Any]:
hf_model.apply_weight_norm()
UpperCAmelCase__ : Tuple = checkpoint['''input_conv.weight_g''']
UpperCAmelCase__ : Any = checkpoint['''input_conv.weight_v''']
UpperCAmelCase__ : Union[str, Any] = checkpoint['''input_conv.bias''']
for i in range(len(config.upsample_rates ) ):
UpperCAmelCase__ : int = checkpoint[F"""upsamples.{i}.1.weight_g"""]
UpperCAmelCase__ : str = checkpoint[F"""upsamples.{i}.1.weight_v"""]
UpperCAmelCase__ : List[Any] = checkpoint[F"""upsamples.{i}.1.bias"""]
for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ):
for j in range(len(config.resblock_dilation_sizes ) ):
UpperCAmelCase__ : int = checkpoint[F"""blocks.{i}.convs1.{j}.1.weight_g"""]
UpperCAmelCase__ : List[Any] = checkpoint[F"""blocks.{i}.convs1.{j}.1.weight_v"""]
UpperCAmelCase__ : Any = checkpoint[F"""blocks.{i}.convs1.{j}.1.bias"""]
UpperCAmelCase__ : Tuple = checkpoint[F"""blocks.{i}.convs2.{j}.1.weight_g"""]
UpperCAmelCase__ : Tuple = checkpoint[F"""blocks.{i}.convs2.{j}.1.weight_v"""]
UpperCAmelCase__ : List[Any] = checkpoint[F"""blocks.{i}.convs2.{j}.1.bias"""]
UpperCAmelCase__ : List[Any] = checkpoint['''output_conv.1.weight_g''']
UpperCAmelCase__ : Union[str, Any] = checkpoint['''output_conv.1.weight_v''']
UpperCAmelCase__ : List[Any] = checkpoint['''output_conv.1.bias''']
hf_model.remove_weight_norm()
@torch.no_grad()
def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=None , lowerCAmelCase__=None , ) -> List[str]:
if config_path is not None:
UpperCAmelCase__ : Tuple = SpeechTaHifiGanConfig.from_pretrained(lowerCAmelCase__ )
else:
UpperCAmelCase__ : Union[str, Any] = SpeechTaHifiGanConfig()
UpperCAmelCase__ : Optional[int] = SpeechTaHifiGan(lowerCAmelCase__ )
UpperCAmelCase__ : Any = torch.load(lowerCAmelCase__ )
load_weights(orig_checkpoint['''model''']['''generator'''] , lowerCAmelCase__ , lowerCAmelCase__ )
UpperCAmelCase__ : Optional[int] = np.load(lowerCAmelCase__ )
UpperCAmelCase__ : str = stats[0].reshape(-1 )
UpperCAmelCase__ : Optional[int] = stats[1].reshape(-1 )
UpperCAmelCase__ : Tuple = torch.from_numpy(lowerCAmelCase__ ).float()
UpperCAmelCase__ : Union[str, Any] = torch.from_numpy(lowerCAmelCase__ ).float()
model.save_pretrained(lowerCAmelCase__ )
if repo_id:
print('''Pushing to the hub...''' )
model.push_to_hub(lowerCAmelCase__ )
if __name__ == "__main__":
UpperCamelCase__ = argparse.ArgumentParser()
parser.add_argument('''--checkpoint_path''', required=True, default=None, type=str, help='''Path to original checkpoint''')
parser.add_argument('''--stats_path''', required=True, default=None, type=str, help='''Path to stats.npy file''')
parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''')
parser.add_argument(
'''--pytorch_dump_folder_path''', required=True, default=None, type=str, help='''Path to the output PyTorch model.'''
)
parser.add_argument(
'''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.'''
)
UpperCamelCase__ = parser.parse_args()
convert_hifigan_checkpoint(
args.checkpoint_path,
args.stats_path,
args.pytorch_dump_folder_path,
args.config_path,
args.push_to_hub,
)
| 75 |
"""simple docstring"""
import os
import pytest
import yaml
from datasets.features.features import Features, Value
from datasets.info import DatasetInfo, DatasetInfosDict
@pytest.mark.parametrize(
'''files''' , [
['''full:README.md''', '''dataset_infos.json'''],
['''empty:README.md''', '''dataset_infos.json'''],
['''dataset_infos.json'''],
['''full:README.md'''],
] , )
def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' )
if "full:README.md" in files:
with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f:
f.write('''---\ndataset_info:\n dataset_size: 42\n---''' )
if "empty:README.md" in files:
with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f:
f.write('''''' )
# we want to support dataset_infos.json for backward compatibility
if "dataset_infos.json" in files:
with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f:
f.write('''{"default": {"dataset_size": 42}}''' )
__SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ )
assert dataset_infos
assert dataset_infos["default"].dataset_size == 42
@pytest.mark.parametrize(
'''dataset_info''' , [
DatasetInfo(),
DatasetInfo(
description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ),
] , )
def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ )
dataset_info.write_to_directory(lowercase_ )
__SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ )
assert dataset_info == reloaded
assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) )
def lowerCAmelCase_ ( ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Tuple = DatasetInfo(
description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , )
__SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict()
assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML )
for key in DatasetInfo._INCLUDED_INFO_IN_YAML:
assert key in dataset_info_yaml_dict
assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) )
__SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ )
__SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ )
assert dataset_info_yaml_dict == reloaded
def lowerCAmelCase_ ( ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo()
__SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict()
assert dataset_info_yaml_dict == {}
@pytest.mark.parametrize(
'''dataset_infos_dict''' , [
DatasetInfosDict(),
DatasetInfosDict({'''default''': DatasetInfo()} ),
DatasetInfosDict({'''my_config_name''': DatasetInfo()} ),
DatasetInfosDict(
{
'''default''': DatasetInfo(
description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , )
} ),
DatasetInfosDict(
{
'''v1''': DatasetInfo(dataset_size=42 ),
'''v2''': DatasetInfo(dataset_size=1337 ),
} ),
] , )
def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ )
dataset_infos_dict.write_to_directory(lowercase_ )
__SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ )
# the config_name of the dataset_infos_dict take over the attribute
for config_name, dataset_info in dataset_infos_dict.items():
__SCREAMING_SNAKE_CASE : Optional[int] = config_name
# the yaml representation doesn't include fields like description or citation
# so we just test that we can recover what we can from the yaml
__SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() )
assert dataset_infos_dict == reloaded
if dataset_infos_dict:
assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
| 674 | 0 |
"""simple docstring"""
a_ = 'Input must be a string of 8 numbers plus letter'
a_ = 'TRWAGMYFPDXBNJZSQVHLCKE'
def __UpperCAmelCase ( __UpperCamelCase ):
if not isinstance(__UpperCamelCase , __UpperCamelCase ):
__lowercase : str = f"""Expected string as input, found {type(__UpperCamelCase ).__name__}"""
raise TypeError(__UpperCamelCase )
__lowercase : int = spanish_id.replace('''-''' , '''''' ).upper()
if len(__UpperCamelCase ) != 9:
raise ValueError(__UpperCamelCase )
try:
__lowercase : Tuple = int(spanish_id_clean[0:8] )
__lowercase : Optional[int] = spanish_id_clean[8]
except ValueError as ex:
raise ValueError(__UpperCamelCase ) from ex
if letter.isdigit():
raise ValueError(__UpperCamelCase )
return letter == LOOKUP_LETTERS[number % 23]
if __name__ == "__main__":
import doctest
doctest.testmod()
| 76 |
"""simple docstring"""
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 snake_case ( __UpperCAmelCase , __UpperCAmelCase ):
@register_to_config
def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ):
super().__init__()
__SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) )
__SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) )
def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ):
__SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) )
__SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) )
return self
def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ):
__SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std
return embeds
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ):
__SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean
return embeds
| 674 | 0 |
"""simple docstring"""
from ..utils import DummyObject, requires_backends
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Any , *UpperCamelCase_ : Dict , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : int , *UpperCamelCase_ : Dict , **UpperCamelCase_ : int):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : List[Any] , *UpperCamelCase_ : List[Any] , **UpperCamelCase_ : List[str]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Optional[Any] , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : List[Any]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : List[str] , *UpperCamelCase_ : Dict , **UpperCamelCase_ : Optional[Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Tuple , *UpperCamelCase_ : Dict , **UpperCamelCase_ : Union[str, Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Dict , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : Tuple):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Union[str, Any] , *UpperCamelCase_ : Any , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Optional[Any] , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : List[str]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : List[Any] , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : Union[str, Any]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Union[str, Any] , *UpperCamelCase_ : Optional[Any] , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Any , *UpperCamelCase_ : Dict , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : List[str] , *UpperCamelCase_ : int , **UpperCamelCase_ : Any):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Union[str, Any] , *UpperCamelCase_ : List[Any] , **UpperCamelCase_ : str):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : List[str] , *UpperCamelCase_ : Tuple , **UpperCamelCase_ : Optional[int]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Any , *UpperCamelCase_ : int , **UpperCamelCase_ : str):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : str , *UpperCamelCase_ : Optional[Any] , **UpperCamelCase_ : Optional[Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : List[str] , *UpperCamelCase_ : Dict , **UpperCamelCase_ : Optional[int]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : List[str] , *UpperCamelCase_ : Optional[Any] , **UpperCamelCase_ : str):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Dict , *UpperCamelCase_ : Any , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : int , *UpperCamelCase_ : Dict , **UpperCamelCase_ : str):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : List[str] , *UpperCamelCase_ : List[Any] , **UpperCamelCase_ : Optional[int]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Tuple , *UpperCamelCase_ : List[Any] , **UpperCamelCase_ : Any):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Optional[int] , *UpperCamelCase_ : Optional[Any] , **UpperCamelCase_ : List[str]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : List[str] , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : Union[str, Any]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Tuple , *UpperCamelCase_ : Any , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Optional[int] , *UpperCamelCase_ : str , **UpperCamelCase_ : Union[str, Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : List[Any] , *UpperCamelCase_ : Any , **UpperCamelCase_ : List[str]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Any , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : str):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Any , *UpperCamelCase_ : Any , **UpperCamelCase_ : List[Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : List[Any] , *UpperCamelCase_ : str , **UpperCamelCase_ : Any):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : List[str] , *UpperCamelCase_ : Dict , **UpperCamelCase_ : Optional[int]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Optional[int] , *UpperCamelCase_ : List[Any] , **UpperCamelCase_ : Optional[Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
def _UpperCamelCase ( *UpperCamelCase , **UpperCamelCase ) -> Optional[int]:
"""simple docstring"""
requires_backends(UpperCamelCase , ["torch"] )
def _UpperCamelCase ( *UpperCamelCase , **UpperCamelCase ) -> List[Any]:
"""simple docstring"""
requires_backends(UpperCamelCase , ["torch"] )
def _UpperCamelCase ( *UpperCamelCase , **UpperCamelCase ) -> Optional[int]:
"""simple docstring"""
requires_backends(UpperCamelCase , ["torch"] )
def _UpperCamelCase ( *UpperCamelCase , **UpperCamelCase ) -> Dict:
"""simple docstring"""
requires_backends(UpperCamelCase , ["torch"] )
def _UpperCamelCase ( *UpperCamelCase , **UpperCamelCase ) -> Optional[int]:
"""simple docstring"""
requires_backends(UpperCamelCase , ["torch"] )
def _UpperCamelCase ( *UpperCamelCase , **UpperCamelCase ) -> List[Any]:
"""simple docstring"""
requires_backends(UpperCamelCase , ["torch"] )
def _UpperCamelCase ( *UpperCamelCase , **UpperCamelCase ) -> List[Any]:
"""simple docstring"""
requires_backends(UpperCamelCase , ["torch"] )
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Optional[int] , *UpperCamelCase_ : Optional[int] , **UpperCamelCase_ : Any):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Optional[int] , *UpperCamelCase_ : Any , **UpperCamelCase_ : Tuple):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : str , *UpperCamelCase_ : Tuple , **UpperCamelCase_ : str):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Tuple , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : int):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Union[str, Any] , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : Optional[int]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Tuple , *UpperCamelCase_ : Dict , **UpperCamelCase_ : List[str]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Tuple , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : List[Any]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : List[str] , *UpperCamelCase_ : Any , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : str , *UpperCamelCase_ : int , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Optional[int] , *UpperCamelCase_ : int , **UpperCamelCase_ : Union[str, Any]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : List[str] , *UpperCamelCase_ : Dict , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Union[str, Any] , *UpperCamelCase_ : List[Any] , **UpperCamelCase_ : Union[str, Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : List[Any] , *UpperCamelCase_ : Optional[Any] , **UpperCamelCase_ : Any):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : List[str] , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : List[str]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : int , *UpperCamelCase_ : Tuple , **UpperCamelCase_ : Optional[Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Union[str, Any] , *UpperCamelCase_ : Optional[Any] , **UpperCamelCase_ : Any):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Union[str, Any] , *UpperCamelCase_ : Optional[int] , **UpperCamelCase_ : str):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Dict , *UpperCamelCase_ : List[Any] , **UpperCamelCase_ : Any):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : List[Any] , *UpperCamelCase_ : int , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Optional[Any] , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : Optional[Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : List[str] , *UpperCamelCase_ : str , **UpperCamelCase_ : Any):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Optional[Any] , *UpperCamelCase_ : Dict , **UpperCamelCase_ : Optional[int]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : int , *UpperCamelCase_ : Tuple , **UpperCamelCase_ : str):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : str , *UpperCamelCase_ : Any , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : List[Any] , *UpperCamelCase_ : List[Any] , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Union[str, Any] , *UpperCamelCase_ : str , **UpperCamelCase_ : List[Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Optional[int] , *UpperCamelCase_ : List[Any] , **UpperCamelCase_ : List[Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : List[Any] , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : Any):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Any , *UpperCamelCase_ : Dict , **UpperCamelCase_ : int):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : List[Any] , *UpperCamelCase_ : List[Any] , **UpperCamelCase_ : Optional[int]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : List[Any] , *UpperCamelCase_ : Dict , **UpperCamelCase_ : Optional[Any]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : int , *UpperCamelCase_ : Optional[int] , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Union[str, Any] , *UpperCamelCase_ : Any , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Dict , *UpperCamelCase_ : Tuple , **UpperCamelCase_ : Optional[Any]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Optional[int] , *UpperCamelCase_ : Any , **UpperCamelCase_ : List[Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Optional[int] , *UpperCamelCase_ : str , **UpperCamelCase_ : Optional[int]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : List[str] , *UpperCamelCase_ : Dict , **UpperCamelCase_ : Any):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Optional[int] , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Optional[int] , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : Optional[Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Tuple , *UpperCamelCase_ : Any , **UpperCamelCase_ : Union[str, Any]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : str , *UpperCamelCase_ : str , **UpperCamelCase_ : List[Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Optional[Any] , *UpperCamelCase_ : str , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : List[Any] , *UpperCamelCase_ : Tuple , **UpperCamelCase_ : Optional[int]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Dict , *UpperCamelCase_ : List[Any] , **UpperCamelCase_ : Any):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : int , *UpperCamelCase_ : str , **UpperCamelCase_ : List[Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Optional[Any] , *UpperCamelCase_ : Optional[Any] , **UpperCamelCase_ : List[str]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Any , *UpperCamelCase_ : str , **UpperCamelCase_ : List[str]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Optional[Any] , *UpperCamelCase_ : int , **UpperCamelCase_ : Optional[Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : int , *UpperCamelCase_ : Any , **UpperCamelCase_ : str):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Tuple , *UpperCamelCase_ : str , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Dict , *UpperCamelCase_ : Tuple , **UpperCamelCase_ : int):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : int , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : Union[str, Any]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : List[Any] , *UpperCamelCase_ : Dict , **UpperCamelCase_ : Union[str, Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Any , *UpperCamelCase_ : Dict , **UpperCamelCase_ : List[str]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : List[str] , *UpperCamelCase_ : Dict , **UpperCamelCase_ : List[str]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Tuple , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : List[Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Optional[Any] , *UpperCamelCase_ : List[Any] , **UpperCamelCase_ : int):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Any , *UpperCamelCase_ : Any , **UpperCamelCase_ : int):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Dict , *UpperCamelCase_ : Any , **UpperCamelCase_ : Union[str, Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : int , *UpperCamelCase_ : Optional[int] , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Optional[int] , *UpperCamelCase_ : Dict , **UpperCamelCase_ : List[Any]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Tuple , *UpperCamelCase_ : Tuple , **UpperCamelCase_ : List[str]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : str , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : int):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : List[str] , *UpperCamelCase_ : Optional[Any] , **UpperCamelCase_ : int):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Tuple , *UpperCamelCase_ : Any , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Any , *UpperCamelCase_ : List[Any] , **UpperCamelCase_ : Optional[Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Dict , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : Optional[int]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : int , *UpperCamelCase_ : Dict , **UpperCamelCase_ : str):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Optional[Any] , *UpperCamelCase_ : Optional[Any] , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Any , *UpperCamelCase_ : Any , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : List[str] , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : Optional[Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : List[str] , *UpperCamelCase_ : Dict , **UpperCamelCase_ : List[str]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Dict , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : Union[str, Any]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Dict , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : Union[str, Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Dict , *UpperCamelCase_ : List[Any] , **UpperCamelCase_ : Tuple):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Any , *UpperCamelCase_ : str , **UpperCamelCase_ : Optional[int]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : List[Any] , *UpperCamelCase_ : Dict , **UpperCamelCase_ : Tuple):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Any , *UpperCamelCase_ : str , **UpperCamelCase_ : Optional[Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : List[Any] , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : int , *UpperCamelCase_ : Dict , **UpperCamelCase_ : Any):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Any , *UpperCamelCase_ : Optional[Any] , **UpperCamelCase_ : List[str]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : List[str] , *UpperCamelCase_ : Optional[Any] , **UpperCamelCase_ : Any):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : List[Any] , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : List[str]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Union[str, Any] , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Union[str, Any] , *UpperCamelCase_ : Any , **UpperCamelCase_ : List[Any]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Any , *UpperCamelCase_ : Any , **UpperCamelCase_ : Any):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : int , *UpperCamelCase_ : Optional[Any] , **UpperCamelCase_ : Union[str, Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Optional[int] , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : Optional[int]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Optional[int] , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : str):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : int , *UpperCamelCase_ : Any , **UpperCamelCase_ : List[Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Optional[Any] , *UpperCamelCase_ : Any , **UpperCamelCase_ : Any):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Optional[Any] , *UpperCamelCase_ : str , **UpperCamelCase_ : Tuple):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Dict , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : List[Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Optional[Any] , *UpperCamelCase_ : List[Any] , **UpperCamelCase_ : Union[str, Any]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Dict , *UpperCamelCase_ : str , **UpperCamelCase_ : Tuple):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Any , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : Union[str, Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Tuple , *UpperCamelCase_ : Dict , **UpperCamelCase_ : Any):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : str , *UpperCamelCase_ : List[str] , **UpperCamelCase_ : Union[str, Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Any , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : str):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : List[str] , *UpperCamelCase_ : Any , **UpperCamelCase_ : Optional[int]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Optional[int] , *UpperCamelCase_ : List[Any] , **UpperCamelCase_ : int):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Optional[Any] , *UpperCamelCase_ : Optional[int] , **UpperCamelCase_ : int):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Optional[int] , *UpperCamelCase_ : Any , **UpperCamelCase_ : int):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : List[Any] , *UpperCamelCase_ : Optional[int] , **UpperCamelCase_ : List[str]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Tuple , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : Union[str, Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Union[str, Any] , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : Optional[Any]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Union[str, Any] , *UpperCamelCase_ : Optional[int] , **UpperCamelCase_ : str):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Union[str, Any] , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : Optional[int]):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Optional[int] , *UpperCamelCase_ : int , **UpperCamelCase_ : Union[str, Any]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Any , *UpperCamelCase_ : Dict , **UpperCamelCase_ : Optional[Any]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : str , *UpperCamelCase_ : List[Any] , **UpperCamelCase_ : Tuple):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Optional[Any] , *UpperCamelCase_ : Dict , **UpperCamelCase_ : Optional[int]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Dict , *UpperCamelCase_ : Optional[int] , **UpperCamelCase_ : Dict):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Dict , *UpperCamelCase_ : List[Any] , **UpperCamelCase_ : int):
"""simple docstring"""
requires_backends(cls , ["torch"])
class a__ ( metaclass=__magic_name__ ):
lowercase_ = ["torch"]
def __init__( self : Tuple , *UpperCamelCase_ : Tuple , **UpperCamelCase_ : Optional[int]):
"""simple docstring"""
requires_backends(self , ["torch"])
@classmethod
def a_ ( cls : Dict , *UpperCamelCase_ : Dict , **UpperCamelCase_ : List[str]):
"""simple docstring"""
requires_backends(cls , ["torch"])
@classmethod
def a_ ( cls : Union[str, Any] , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : str):
"""simple docstring"""
requires_backends(cls , ["torch"])
| 77 |
"""simple docstring"""
import argparse
import torch
from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert
from transformers.utils import logging
logging.set_verbosity_info()
def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ )
print(F'''Building PyTorch model from configuration: {config}''' )
__SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ )
# Load weights from tf checkpoint
load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ )
# Save pytorch-model
print(F'''Save PyTorch model to {pytorch_dump_path}''' )
torch.save(model.state_dict() , lowercase_ )
if __name__ == "__main__":
_lowerCamelCase = 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(
'''--bert_config_file''',
default=None,
type=str,
required=True,
help=(
'''The config json file corresponding to the pre-trained BERT model. \n'''
'''This specifies the model architecture.'''
),
)
parser.add_argument(
'''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
)
_lowerCamelCase = parser.parse_args()
convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
| 674 | 0 |
'''simple docstring'''
import unittest
from transformers import GPTSwaTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
SCREAMING_SNAKE_CASE_: Any =get_tests_dir('fixtures/test_sentencepiece_with_bytefallback.model')
@require_sentencepiece
@require_tokenizers
class __A ( UpperCamelCase__ , unittest.TestCase ):
a__ : int = GPTSwaTokenizer
a__ : Optional[Any] = False
a__ : str = True
a__ : Optional[int] = False
def _lowercase (self : int ):
super().setUp()
# We have a SentencePiece fixture for testing
UpperCAmelCase_ = GPTSwaTokenizer(__a , eos_token="<unk>" , bos_token="<unk>" , pad_token="<unk>" )
tokenizer.save_pretrained(self.tmpdirname )
def _lowercase (self : Union[str, Any] , __a : Optional[int] ):
UpperCAmelCase_ = "This is a test"
UpperCAmelCase_ = "This is a test"
return input_text, output_text
def _lowercase (self : List[str] ):
UpperCAmelCase_ = "<s>"
UpperCAmelCase_ = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a ) , __a )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a ) , __a )
def _lowercase (self : Any ):
UpperCAmelCase_ = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , "<unk>" )
self.assertEqual(vocab_keys[1] , "<s>" )
self.assertEqual(vocab_keys[-1] , "j" )
self.assertEqual(len(__a ) , 2000 )
def _lowercase (self : Optional[Any] ):
self.assertEqual(self.get_tokenizer().vocab_size , 2000 )
def _lowercase (self : List[Any] ):
UpperCAmelCase_ = GPTSwaTokenizer(__a )
UpperCAmelCase_ = tokenizer.tokenize("This is a test" )
self.assertListEqual(__a , ["▁This", "▁is", "▁a", "▁t", "est"] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [465, 287, 265, 631, 842] )
UpperCAmelCase_ = tokenizer.tokenize("I was born in 92000, and this is falsé." )
# fmt: off
self.assertListEqual(
__a , ["▁I", "▁was", "▁bor", "n", "▁in", "▁", "<0x39>", "2", "0", "0", "0", ",", "▁and", "▁this", "▁is", "▁f", "al", "s", "<0xC3>", "<0xA9>", "."] , )
# fmt: on
UpperCAmelCase_ = tokenizer.convert_tokens_to_ids(__a )
self.assertListEqual(
__a , [262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260] , )
UpperCAmelCase_ = tokenizer.convert_ids_to_tokens(__a )
# fmt: off
self.assertListEqual(
__a , ["▁I", "▁was", "▁bor", "n", "▁in", "▁", "<0x39>", "2", "0", "0", "0", ",", "▁and", "▁this", "▁is", "▁f", "al", "s", "<0xC3>", "<0xA9>", "."] )
# fmt: on
def _lowercase (self : Optional[int] ):
UpperCAmelCase_ = GPTSwaTokenizer(__a )
UpperCAmelCase_ = ["This is a test", "I was born in 92000, and this is falsé."]
UpperCAmelCase_ = [
[465, 287, 265, 631, 842],
[262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260],
]
# Test that encode_fast returns the same as tokenize + convert_tokens_to_ids
for text, expected_ids in zip(__a , __a ):
self.assertListEqual(tokenizer.encode_fast(__a ) , __a )
# Test that decode_fast returns the input text
for text, token_ids in zip(__a , __a ):
self.assertEqual(tokenizer.decode_fast(__a ) , __a )
@slow
def _lowercase (self : Optional[int] ):
UpperCAmelCase_ = [
"<|python|>def fibonacci(n)\n if n < 0:\n print('Incorrect input')",
"Hey there, how are you doing this fine day?",
"This is a text with a trailing spaces followed by a dot .",
"Häj sväjs lillebrör! =)",
"Det är inget fel på Mr. Cool",
]
# fmt: off
UpperCAmelCase_ = {"input_ids": [[63423, 5, 6811, 14954, 282, 816, 3821, 63466, 63425, 63462, 18, 63978, 678, 301, 1320, 63423, 63455, 63458, 18, 63982, 4246, 3940, 1901, 47789, 5547, 18994], [19630, 1100, 63446, 1342, 633, 544, 4488, 593, 5102, 2416, 63495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1652, 428, 268, 1936, 515, 268, 58593, 22413, 9106, 546, 268, 33213, 63979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [55130, 63450, 924, 63449, 2249, 4062, 1558, 318, 63504, 21498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2827, 2559, 332, 6575, 63443, 26801, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=__a , model_name="AI-Sweden/gpt-sw3-126m" , sequences=__a , )
| 78 |
"""simple docstring"""
# 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 numpy as np
import torch
from ..models.clipseg import CLIPSegForImageSegmentation
from ..utils import is_vision_available, requires_backends
from .base import PipelineTool
if is_vision_available():
from PIL import Image
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = (
'''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.'''
'''It takes two arguments named `image` which should be the original image, and `label` which should be a text '''
'''describing the elements what should be identified in the segmentation mask. The tool returns the mask.'''
)
lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined'''
lowerCamelCase__ = '''image_segmenter'''
lowerCamelCase__ = CLIPSegForImageSegmentation
lowerCamelCase__ = ['''image''', '''text''']
lowerCamelCase__ = ['''image''']
def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ):
requires_backends(self , ['''vision'''] )
super().__init__(*_lowerCamelCase , **_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ):
return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ):
with torch.no_grad():
__SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits
return logits
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ):
__SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy()
__SCREAMING_SNAKE_CASE : str = 0
__SCREAMING_SNAKE_CASE : str = 1
return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
| 674 | 0 |
import enum
import os
from hashlib import shaaaa
from typing import Optional
from .. import config
from .logging import get_logger
SCREAMING_SNAKE_CASE__ : Dict = get_logger(__name__)
class UpperCAmelCase_ ( enum.Enum ):
__lowerCamelCase = 'all_checks'
__lowerCamelCase = 'basic_checks'
__lowerCamelCase = 'no_checks'
class UpperCAmelCase_ ( __lowerCamelCase ):
pass
class UpperCAmelCase_ ( __lowerCamelCase ):
pass
class UpperCAmelCase_ ( __lowerCamelCase ):
pass
class UpperCAmelCase_ ( __lowerCamelCase ):
pass
def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None ) -> Any:
'''simple docstring'''
if expected_checksums is None:
logger.info("""Unable to verify checksums.""" )
return
if len(set(__lowerCamelCase ) - set(__lowerCamelCase ) ) > 0:
raise ExpectedMoreDownloadedFiles(str(set(__lowerCamelCase ) - set(__lowerCamelCase ) ) )
if len(set(__lowerCamelCase ) - set(__lowerCamelCase ) ) > 0:
raise UnexpectedDownloadedFile(str(set(__lowerCamelCase ) - set(__lowerCamelCase ) ) )
UpperCAmelCase__ : str = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]]
UpperCAmelCase__ : Dict = """ for """ + verification_name if verification_name is not None else """"""
if len(__lowerCamelCase ) > 0:
raise NonMatchingChecksumError(
F"Checksums didn't match{for_verification_name}:\n"
F"{bad_urls}\n"
"""Set `verification_mode='no_checks'` to skip checksums verification and ignore this error""" )
logger.info("""All the checksums matched successfully""" + for_verification_name )
class UpperCAmelCase_ ( __lowerCamelCase ):
pass
class UpperCAmelCase_ ( __lowerCamelCase ):
pass
class UpperCAmelCase_ ( __lowerCamelCase ):
pass
class UpperCAmelCase_ ( __lowerCamelCase ):
pass
def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase ) -> Union[str, Any]:
'''simple docstring'''
if expected_splits is None:
logger.info("""Unable to verify splits sizes.""" )
return
if len(set(__lowerCamelCase ) - set(__lowerCamelCase ) ) > 0:
raise ExpectedMoreSplits(str(set(__lowerCamelCase ) - set(__lowerCamelCase ) ) )
if len(set(__lowerCamelCase ) - set(__lowerCamelCase ) ) > 0:
raise UnexpectedSplits(str(set(__lowerCamelCase ) - set(__lowerCamelCase ) ) )
UpperCAmelCase__ : List[Any] = [
{"""expected""": expected_splits[name], """recorded""": recorded_splits[name]}
for name in expected_splits
if expected_splits[name].num_examples != recorded_splits[name].num_examples
]
if len(__lowerCamelCase ) > 0:
raise NonMatchingSplitsSizesError(str(__lowerCamelCase ) )
logger.info("""All the splits matched successfully.""" )
def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase = True ) -> dict:
'''simple docstring'''
if record_checksum:
UpperCAmelCase__ : List[Any] = shaaaa()
with open(__lowerCamelCase , """rb""" ) as f:
for chunk in iter(lambda: f.read(1 << 20 ) , B"""""" ):
m.update(__lowerCamelCase )
UpperCAmelCase__ : int = m.hexdigest()
else:
UpperCAmelCase__ : Dict = None
return {"num_bytes": os.path.getsize(__lowerCamelCase ), "checksum": checksum}
def _lowerCamelCase ( __lowerCamelCase ) -> List[Any]:
'''simple docstring'''
if dataset_size and config.IN_MEMORY_MAX_SIZE:
return dataset_size < config.IN_MEMORY_MAX_SIZE
else:
return False
| 79 |
"""simple docstring"""
import json
import os
import shutil
import tempfile
import unittest
import numpy as np
from transformers import BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer
from transformers.testing_utils import require_tokenizers, require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available
if is_vision_available():
from PIL import Image
from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor
@require_tokenizers
@require_vision
class snake_case ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp()
# fmt: off
__SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''']
# fmt: on
__SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer:
vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) )
__SCREAMING_SNAKE_CASE : Optional[int] = {
'''do_resize''': True,
'''size''': {'''height''': 1_8, '''width''': 1_8},
'''do_normalize''': True,
'''image_mean''': [0.5, 0.5, 0.5],
'''image_std''': [0.5, 0.5, 0.5],
}
__SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase )
with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp:
json.dump(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ):
return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ):
return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
shutil.rmtree(self.tmpdirname )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )]
__SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def SCREAMING_SNAKE_CASE_ ( self :int ):
__SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor()
__SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
processor.save_pretrained(self.tmpdirname )
__SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() )
self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) )
self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() )
self.assertIsInstance(processor.image_processor , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
__SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor(
tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
__SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' )
__SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 )
__SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(
self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :int ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor()
__SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs()
__SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' )
__SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''np''' )
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
__SCREAMING_SNAKE_CASE : Any = self.get_image_processor()
__SCREAMING_SNAKE_CASE : Any = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer'''
__SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE : str = self.get_image_processor()
__SCREAMING_SNAKE_CASE : int = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = '''lower newer'''
__SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs()
__SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase )
self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] )
# test if it raises when no input is passed
with self.assertRaises(_lowerCamelCase ):
processor()
def SCREAMING_SNAKE_CASE_ ( self :Any ):
__SCREAMING_SNAKE_CASE : Dict = self.get_image_processor()
__SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
__SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase )
self.assertListEqual(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
__SCREAMING_SNAKE_CASE : str = self.get_image_processor()
__SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = '''lower newer'''
__SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs()
__SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase )
self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
| 674 | 0 |
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 __UpperCamelCase ( _lowerCAmelCase , unittest.TestCase ):
__snake_case :Optional[int] = ShapEPipeline
__snake_case :Optional[int] = ['prompt']
__snake_case :str = ['prompt']
__snake_case :Tuple = [
'num_images_per_prompt',
'num_inference_steps',
'generator',
'latents',
'guidance_scale',
'frame_size',
'output_type',
'return_dict',
]
__snake_case :str = False
@property
def _a ( self : Optional[int] ) -> Optional[Any]:
"""simple docstring"""
return 32
@property
def _a ( self : str ) -> str:
"""simple docstring"""
return 32
@property
def _a ( self : Optional[Any] ) -> Dict:
"""simple docstring"""
return self.time_input_dim * 4
@property
def _a ( self : str ) -> Union[str, Any]:
"""simple docstring"""
return 8
@property
def _a ( self : Union[str, Any] ) -> Optional[int]:
"""simple docstring"""
__lowercase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" )
return tokenizer
@property
def _a ( self : int ) -> Optional[int]:
"""simple docstring"""
torch.manual_seed(0 )
__lowercase = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , )
return CLIPTextModelWithProjection(_lowerCAmelCase )
@property
def _a ( self : Dict ) -> List[str]:
"""simple docstring"""
torch.manual_seed(0 )
__lowercase = {
"""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,
}
__lowercase = PriorTransformer(**_lowerCAmelCase )
return model
@property
def _a ( self : Any ) -> int:
"""simple docstring"""
torch.manual_seed(0 )
__lowercase = {
"""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,
),
}
__lowercase = ShapERenderer(**_lowerCAmelCase )
return model
def _a ( self : List[Any] ) -> str:
"""simple docstring"""
__lowercase = self.dummy_prior
__lowercase = self.dummy_text_encoder
__lowercase = self.dummy_tokenizer
__lowercase = self.dummy_renderer
__lowercase = HeunDiscreteScheduler(
beta_schedule="""exp""" , num_train_timesteps=1024 , prediction_type="""sample""" , use_karras_sigmas=_lowerCAmelCase , clip_sample=_lowerCAmelCase , clip_sample_range=1.0 , )
__lowercase = {
"""prior""": prior,
"""text_encoder""": text_encoder,
"""tokenizer""": tokenizer,
"""renderer""": renderer,
"""scheduler""": scheduler,
}
return components
def _a ( self : Any , _lowerCAmelCase : int , _lowerCAmelCase : Union[str, Any]=0 ) -> Dict:
"""simple docstring"""
if str(_lowerCAmelCase ).startswith("""mps""" ):
__lowercase = torch.manual_seed(_lowerCAmelCase )
else:
__lowercase = torch.Generator(device=_lowerCAmelCase ).manual_seed(_lowerCAmelCase )
__lowercase = {
"""prompt""": """horse""",
"""generator""": generator,
"""num_inference_steps""": 1,
"""frame_size""": 32,
"""output_type""": """np""",
}
return inputs
def _a ( self : str ) -> Any:
"""simple docstring"""
__lowercase = """cpu"""
__lowercase = self.get_dummy_components()
__lowercase = self.pipeline_class(**_lowerCAmelCase )
__lowercase = pipe.to(_lowerCAmelCase )
pipe.set_progress_bar_config(disable=_lowerCAmelCase )
__lowercase = pipe(**self.get_dummy_inputs(_lowerCAmelCase ) )
__lowercase = output.images[0]
__lowercase = image[0, -3:, -3:, -1]
assert image.shape == (20, 32, 32, 3)
__lowercase = np.array(
[
0.00_039_216,
0.00_039_216,
0.00_039_216,
0.00_039_216,
0.00_039_216,
0.00_039_216,
0.00_039_216,
0.00_039_216,
0.00_039_216,
] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def _a ( self : Union[str, Any] ) -> int:
"""simple docstring"""
self._test_inference_batch_consistent(batch_sizes=[1, 2] )
def _a ( self : Dict ) -> int:
"""simple docstring"""
__lowercase = torch_device == """cpu"""
__lowercase = True
self._test_inference_batch_single_identical(
batch_size=2 , test_max_difference=_lowerCAmelCase , relax_max_difference=_lowerCAmelCase , )
def _a ( self : Any ) -> str:
"""simple docstring"""
__lowercase = self.get_dummy_components()
__lowercase = self.pipeline_class(**_lowerCAmelCase )
__lowercase = pipe.to(_lowerCAmelCase )
pipe.set_progress_bar_config(disable=_lowerCAmelCase )
__lowercase = 1
__lowercase = 2
__lowercase = self.get_dummy_inputs(_lowerCAmelCase )
for key in inputs.keys():
if key in self.batch_params:
__lowercase = batch_size * [inputs[key]]
__lowercase = pipe(**_lowerCAmelCase , num_images_per_prompt=_lowerCAmelCase )[0]
assert images.shape[0] == batch_size * num_images_per_prompt
@slow
@require_torch_gpu
class __UpperCamelCase ( unittest.TestCase ):
def _a ( self : Dict ) -> List[str]:
"""simple docstring"""
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def _a ( self : Any ) -> Optional[Any]:
"""simple docstring"""
__lowercase = load_numpy(
"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
"""/shap_e/test_shap_e_np_out.npy""" )
__lowercase = ShapEPipeline.from_pretrained("""openai/shap-e""" )
__lowercase = pipe.to(_lowerCAmelCase )
pipe.set_progress_bar_config(disable=_lowerCAmelCase )
__lowercase = torch.Generator(device=_lowerCAmelCase ).manual_seed(0 )
__lowercase = pipe(
"""a shark""" , generator=_lowerCAmelCase , 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(_lowerCAmelCase , _lowerCAmelCase )
| 80 |
"""simple docstring"""
import inspect
import unittest
import numpy as np
from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel
if is_vision_available():
from transformers import MaskFormerImageProcessor
if is_vision_available():
from PIL import Image
class snake_case :
def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ):
__SCREAMING_SNAKE_CASE : List[str] = parent
__SCREAMING_SNAKE_CASE : Tuple = batch_size
__SCREAMING_SNAKE_CASE : Optional[Any] = is_training
__SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss
__SCREAMING_SNAKE_CASE : List[str] = num_queries
__SCREAMING_SNAKE_CASE : Optional[int] = num_channels
__SCREAMING_SNAKE_CASE : List[Any] = min_size
__SCREAMING_SNAKE_CASE : int = max_size
__SCREAMING_SNAKE_CASE : Any = num_labels
__SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size
def SCREAMING_SNAKE_CASE_ ( self :Any ):
__SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to(
_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = (
torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5
).float()
__SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long()
__SCREAMING_SNAKE_CASE : str = self.get_config()
return config, pixel_values, pixel_mask, mask_labels, class_labels
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
return MaskFormerConfig.from_backbone_and_decoder_configs(
backbone_config=SwinConfig(
depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig(
decoder_ffn_dim=1_2_8 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , )
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs()
__SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
return config, inputs_dict
def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states
__SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states
__SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states
self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers )
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ):
with torch.no_grad():
__SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
__SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase )
# the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
# encoder and pixel decoder
self.parent.assertEqual(
output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , )
# let's ensure the other two hidden state exists
self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(output.encoder_last_hidden_state is not None )
if output_hidden_states:
self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ):
__SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
def comm_check_on_output(_lowerCamelCase :Optional[Any] ):
# let's still check that all the required stuff is there
self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.encoder_last_hidden_state is not None )
# okay, now we need to check the logits shape
# due to the encoder compression, masks have a //4 spatial size
self.parent.assertEqual(
result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , )
# + 1 for null class
self.parent.assertEqual(
result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) )
with torch.no_grad():
__SCREAMING_SNAKE_CASE : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase )
comm_check_on_output(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Dict = model(
pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase )
comm_check_on_output(_lowerCamelCase )
self.parent.assertTrue(result.loss is not None )
self.parent.assertEqual(result.loss.shape , torch.Size([1] ) )
@require_torch
class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ):
lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
lowerCamelCase__ = (
{'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation}
if is_torch_available()
else {}
)
lowerCamelCase__ = False
lowerCamelCase__ = False
lowerCamelCase__ = False
lowerCamelCase__ = False
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
__SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self )
__SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
self.config_tester.run_common_tests()
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
__SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase )
@unittest.skip(reason='''MaskFormer does not use inputs_embeds''' )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
pass
@unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' )
def SCREAMING_SNAKE_CASE_ ( self :int ):
pass
@unittest.skip(reason='''MaskFormer is not a generative model''' )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
pass
@unittest.skip(reason='''MaskFormer does not use token embeddings''' )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
pass
@require_torch_multi_gpu
@unittest.skip(
reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
pass
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
pass
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__SCREAMING_SNAKE_CASE : Tuple = model_class(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()]
__SCREAMING_SNAKE_CASE : Optional[Any] = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
for model_name in ["facebook/maskformer-swin-small-coco"]:
__SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2
__SCREAMING_SNAKE_CASE : Dict = {
'''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ),
'''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ),
'''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(),
}
__SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase )
self.assertTrue(outputs.loss is not None )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__SCREAMING_SNAKE_CASE : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase )
self.assertTrue(outputs.attentions is not None )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
if not self.model_tester.is_training:
return
# only MaskFormerForInstanceSegmentation has the loss
__SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1]
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs()
__SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase )
model.to(_lowerCamelCase )
model.train()
__SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss
loss.backward()
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# only MaskFormerForInstanceSegmentation has the loss
__SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1]
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs()
__SCREAMING_SNAKE_CASE : Tuple = True
__SCREAMING_SNAKE_CASE : List[str] = True
__SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase )
model.to(_lowerCamelCase )
model.train()
__SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = outputs.encoder_hidden_states[0]
encoder_hidden_states.retain_grad()
__SCREAMING_SNAKE_CASE : str = outputs.pixel_decoder_hidden_states[0]
pixel_decoder_hidden_states.retain_grad()
# we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
__SCREAMING_SNAKE_CASE : Optional[int] = outputs.transformer_decoder_hidden_states[0]
transformer_decoder_hidden_states.retain_grad()
__SCREAMING_SNAKE_CASE : int = outputs.attentions[0]
attentions.retain_grad()
outputs.loss.backward(retain_graph=_lowerCamelCase )
self.assertIsNotNone(encoder_hidden_states.grad )
self.assertIsNotNone(pixel_decoder_hidden_states.grad )
self.assertIsNotNone(transformer_decoder_hidden_states.grad )
self.assertIsNotNone(attentions.grad )
_lowerCamelCase = 1e-4
def lowerCAmelCase_ ( ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_vision
@slow
class snake_case ( unittest.TestCase ):
@cached_property
def SCREAMING_SNAKE_CASE_ ( self :str ):
return (
MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' )
if is_vision_available()
else None
)
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = self.default_image_processor
__SCREAMING_SNAKE_CASE : Tuple = prepare_img()
__SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 )
# check size
self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) )
with torch.no_grad():
__SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor(
[[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase )
self.assertTrue(
torch.allclose(
outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
__SCREAMING_SNAKE_CASE : Any = torch.tensor(
[[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase )
self.assertTrue(
torch.allclose(
outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
__SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(
[[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase )
self.assertTrue(
torch.allclose(
outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
__SCREAMING_SNAKE_CASE : Tuple = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
.to(_lowerCamelCase )
.eval()
)
__SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor
__SCREAMING_SNAKE_CASE : Tuple = prepare_img()
__SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 )
# check size
self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) )
with torch.no_grad():
__SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase )
# masks_queries_logits
__SCREAMING_SNAKE_CASE : Any = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
__SCREAMING_SNAKE_CASE : List[Any] = [
[-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3],
[-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5],
[-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2],
]
__SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
# class_queries_logits
__SCREAMING_SNAKE_CASE : List[Any] = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
__SCREAMING_SNAKE_CASE : List[str] = torch.tensor(
[
[1.65_12e00, -5.25_72e00, -3.35_19e00],
[3.61_69e-02, -5.90_25e00, -2.93_13e00],
[1.07_66e-04, -7.76_30e00, -5.12_63e00],
] ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
def SCREAMING_SNAKE_CASE_ ( self :Any ):
__SCREAMING_SNAKE_CASE : Tuple = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' )
.to(_lowerCamelCase )
.eval()
)
__SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor
__SCREAMING_SNAKE_CASE : str = prepare_img()
__SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 )
# check size
self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) )
with torch.no_grad():
__SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase )
# masks_queries_logits
__SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
__SCREAMING_SNAKE_CASE : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]]
__SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
# class_queries_logits
__SCREAMING_SNAKE_CASE : int = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
__SCREAMING_SNAKE_CASE : List[str] = torch.tensor(
[[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
def SCREAMING_SNAKE_CASE_ ( self :int ):
__SCREAMING_SNAKE_CASE : int = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
.to(_lowerCamelCase )
.eval()
)
__SCREAMING_SNAKE_CASE : Any = self.default_image_processor
__SCREAMING_SNAKE_CASE : int = image_processor(
[np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , )
__SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']]
__SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']]
with torch.no_grad():
__SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase )
self.assertTrue(outputs.loss is not None )
| 674 | 0 |
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
_snake_case : Dict = logging.get_logger(__name__)
_snake_case : Dict = {
"facebook/xmod-base": "https://huggingface.co/facebook/xmod-base/resolve/main/config.json",
"facebook/xmod-large-prenorm": "https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json",
"facebook/xmod-base-13-125k": "https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json",
"facebook/xmod-base-30-125k": "https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json",
"facebook/xmod-base-30-195k": "https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json",
"facebook/xmod-base-60-125k": "https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json",
"facebook/xmod-base-60-265k": "https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json",
"facebook/xmod-base-75-125k": "https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json",
"facebook/xmod-base-75-269k": "https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json",
}
class a (_lowerCAmelCase ):
"""simple docstring"""
__UpperCAmelCase : Optional[Any] = "xmod"
def __init__( self : Tuple , lowerCamelCase : Any=30522 , lowerCamelCase : Union[str, Any]=768 , lowerCamelCase : Union[str, Any]=12 , lowerCamelCase : List[str]=12 , lowerCamelCase : List[Any]=3072 , lowerCamelCase : List[Any]="gelu" , lowerCamelCase : Union[str, Any]=0.1 , lowerCamelCase : Dict=0.1 , lowerCamelCase : Any=512 , lowerCamelCase : Any=2 , lowerCamelCase : List[str]=0.02 , lowerCamelCase : Union[str, Any]=1E-12 , lowerCamelCase : List[Any]=1 , lowerCamelCase : Union[str, Any]=0 , lowerCamelCase : List[str]=2 , lowerCamelCase : List[str]="absolute" , lowerCamelCase : Dict=True , lowerCamelCase : List[Any]=None , lowerCamelCase : Union[str, Any]=False , lowerCamelCase : int=2 , lowerCamelCase : Union[str, Any]=False , lowerCamelCase : List[Any]=True , lowerCamelCase : Union[str, Any]=True , lowerCamelCase : Optional[Any]=("en_XX",) , lowerCamelCase : List[Any]=None , **lowerCamelCase : Union[str, Any] , ) -> Optional[Any]:
super().__init__(pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , **lowerCamelCase )
__snake_case : Union[str, Any] = vocab_size
__snake_case : List[Any] = hidden_size
__snake_case : Any = num_hidden_layers
__snake_case : Tuple = num_attention_heads
__snake_case : List[str] = hidden_act
__snake_case : Optional[int] = intermediate_size
__snake_case : Optional[int] = hidden_dropout_prob
__snake_case : Dict = attention_probs_dropout_prob
__snake_case : Any = max_position_embeddings
__snake_case : Optional[Any] = type_vocab_size
__snake_case : List[Any] = initializer_range
__snake_case : List[str] = layer_norm_eps
__snake_case : str = position_embedding_type
__snake_case : int = use_cache
__snake_case : List[str] = classifier_dropout
__snake_case : Tuple = pre_norm
__snake_case : Any = adapter_reduction_factor
__snake_case : str = adapter_layer_norm
__snake_case : Optional[Any] = adapter_reuse_layer_norm
__snake_case : List[Any] = ln_before_adapter
__snake_case : List[str] = list(lowerCamelCase )
__snake_case : int = default_language
class a (_lowerCAmelCase ):
"""simple docstring"""
@property
def __snake_case ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]:
if self.task == "multiple-choice":
__snake_case : Dict = {0: "batch", 1: "choice", 2: "sequence"}
else:
__snake_case : Dict = {0: "batch", 1: "sequence"}
return OrderedDict(
[
("input_ids", dynamic_axis),
("attention_mask", dynamic_axis),
] )
| 81 |
"""simple docstring"""
import contextlib
import importlib
import io
import unittest
import transformers
# Try to import everything from transformers to ensure every object can be loaded.
from transformers import * # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available
if is_torch_available():
from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification
if is_tf_available():
from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification
if is_flax_available():
from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification
_lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co
_lowerCamelCase = '''main'''
# Default branch name
_lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'''
# One particular commit (not the top of `main`)
_lowerCamelCase = '''aaaaaaa'''
# This commit does not exist, so we should 404.
_lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684'''
# Sha-1 of config.json on the top of `main`, for checking purposes
_lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'''
@contextlib.contextmanager
def lowerCAmelCase_ ( ):
'''simple docstring'''
print('''Welcome!''' )
yield
print('''Bye!''' )
@contextlib.contextmanager
def lowerCAmelCase_ ( ):
'''simple docstring'''
print('''Bonjour!''' )
yield
print('''Au revoir!''' )
class snake_case ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
# If the spec is missing, importlib would not be able to import the module dynamically.
assert transformers.__spec__ is not None
assert importlib.util.find_spec('''transformers''' ) is not None
class snake_case ( unittest.TestCase ):
@unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO )
def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ):
with ContextManagers([] ):
print('''Transformers are awesome!''' )
# The print statement adds a new line at the end of the output
self.assertEqual(mock_stdout.getvalue() , '''Transformers are awesome!\n''' )
@unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO )
def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ):
with ContextManagers([context_en()] ):
print('''Transformers are awesome!''' )
# The output should be wrapped with an English welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , '''Welcome!\nTransformers are awesome!\nBye!\n''' )
@unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO )
def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ):
with ContextManagers([context_fr(), context_en()] ):
print('''Transformers are awesome!''' )
# The output should be wrapped with an English and French welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , '''Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n''' )
@require_torch
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] )
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] )
self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] )
class snake_case ( __UpperCAmelCase ):
pass
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] )
@require_tf
def SCREAMING_SNAKE_CASE_ ( self :int ):
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] )
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] )
self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] )
class snake_case ( __UpperCAmelCase ):
pass
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] )
@require_flax
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
# Flax models don't have labels
self.assertEqual(find_labels(_lowerCamelCase ) , [] )
self.assertEqual(find_labels(_lowerCamelCase ) , [] )
self.assertEqual(find_labels(_lowerCamelCase ) , [] )
class snake_case ( __UpperCAmelCase ):
pass
self.assertEqual(find_labels(_lowerCamelCase ) , [] )
| 674 | 0 |
"""simple docstring"""
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 lowercase__ ( SCREAMING_SNAKE_CASE ):
'''simple docstring'''
UpperCamelCase = field(default='''image-classification''' , metadata={'''include_in_asdict_even_if_is_default''': True} )
UpperCamelCase = Features({'''image''': Image()} )
UpperCamelCase = Features({'''labels''': ClassLabel} )
UpperCamelCase = "image"
UpperCamelCase = "labels"
def lowercase__ ( self : str , _UpperCAmelCase : str ) -> Dict:
'''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.""" )
UpperCAmelCase_ = copy.deepcopy(self )
UpperCAmelCase_ = self.label_schema.copy()
UpperCAmelCase_ = features[self.label_column]
UpperCAmelCase_ = label_schema
return task_template
@property
def lowercase__ ( self : List[str] ) -> Dict[str, str]:
'''simple docstring'''
return {
self.image_column: "image",
self.label_column: "labels",
}
| 82 |
"""simple docstring"""
import json
import pathlib
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import YolosImageProcessor
class snake_case ( unittest.TestCase ):
def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ):
# by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
__SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3}
__SCREAMING_SNAKE_CASE : List[str] = parent
__SCREAMING_SNAKE_CASE : Dict = batch_size
__SCREAMING_SNAKE_CASE : str = num_channels
__SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution
__SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution
__SCREAMING_SNAKE_CASE : Tuple = do_resize
__SCREAMING_SNAKE_CASE : Union[str, Any] = size
__SCREAMING_SNAKE_CASE : int = do_normalize
__SCREAMING_SNAKE_CASE : List[Any] = image_mean
__SCREAMING_SNAKE_CASE : Tuple = image_std
__SCREAMING_SNAKE_CASE : Dict = do_rescale
__SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor
__SCREAMING_SNAKE_CASE : List[Any] = do_pad
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
return {
"do_resize": self.do_resize,
"size": self.size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_rescale": self.do_rescale,
"rescale_factor": self.rescale_factor,
"do_pad": self.do_pad,
}
def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ):
if not batched:
__SCREAMING_SNAKE_CASE : str = image_inputs[0]
if isinstance(_lowerCamelCase , Image.Image ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size
else:
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2]
if w < h:
__SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w )
__SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge''']
elif w > h:
__SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge''']
__SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h )
else:
__SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge''']
__SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge''']
else:
__SCREAMING_SNAKE_CASE : Optional[Any] = []
for image in image_inputs:
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] )
expected_values.append((expected_height, expected_width) )
__SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0]
__SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1]
return expected_height, expected_width
@require_torch
@require_vision
class snake_case ( __UpperCAmelCase , unittest.TestCase ):
lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
__SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self )
@property
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
return self.image_processor_tester.prepare_image_processor_dict()
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
__SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) )
self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) )
self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) )
self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) )
self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} )
self.assertEqual(image_processor.do_pad , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict(
self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase )
self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} )
self.assertEqual(image_processor.do_pad , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
pass
def SCREAMING_SNAKE_CASE_ ( self :int ):
# Initialize image_processing
__SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
__SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , Image.Image )
# Test not batched input
__SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# Initialize image_processing
__SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
__SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , np.ndarray )
# Test not batched input
__SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def SCREAMING_SNAKE_CASE_ ( self :Any ):
# Initialize image_processing
__SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
__SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , torch.Tensor )
# Test not batched input
__SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
# Initialize image_processings
__SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict )
__SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase )
# create random PyTorch tensors
__SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , torch.Tensor )
# Test whether the method "pad" and calling the image processor return the same tensors
__SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' )
__SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' )
self.assertTrue(
torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) )
@slow
def SCREAMING_SNAKE_CASE_ ( self :int ):
# prepare image and target
__SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f:
__SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() )
__SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target}
# encode them
__SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' )
__SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' )
# verify pixel values
__SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] )
self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] )
self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) )
# verify area
__SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) )
# verify boxes
__SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] )
self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) )
# verify image_id
__SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) )
# verify is_crowd
__SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) )
# verify class_labels
__SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) )
# verify orig_size
__SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) )
# verify size
__SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# prepare image, target and masks_path
__SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f:
__SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() )
__SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target}
__SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' )
# encode them
__SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' )
__SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' )
# verify pixel values
__SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] )
self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] )
self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) )
# verify area
__SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) )
# verify boxes
__SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] )
self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) )
# verify image_id
__SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) )
# verify is_crowd
__SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) )
# verify class_labels
__SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) )
# verify masks
__SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3
self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase )
# verify orig_size
__SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) )
# verify size
__SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
| 674 | 0 |
"""simple docstring"""
import gc
import random
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DiffusionPipeline,
EulerDiscreteScheduler,
StableDiffusionXLImgaImgPipeline,
UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
from ..pipeline_params import (
IMAGE_TO_IMAGE_IMAGE_PARAMS,
TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin
enable_full_determinism()
class __snake_case ( _lowercase , _lowercase , unittest.TestCase):
snake_case__ : Optional[Any] = StableDiffusionXLImgaImgPipeline
snake_case__ : Union[str, Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"}
snake_case__ : int = PipelineTesterMixin.required_optional_params - {"latents"}
snake_case__ : Union[str, Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
snake_case__ : Dict = IMAGE_TO_IMAGE_IMAGE_PARAMS
snake_case__ : Any = IMAGE_TO_IMAGE_IMAGE_PARAMS
def SCREAMING_SNAKE_CASE ( self : Optional[Any] ):
"""simple docstring"""
torch.manual_seed(0 )
_lowerCamelCase : Union[str, Any] = UNetaDConditionModel(
block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , attention_head_dim=(2, 4) , use_linear_projection=__lowerCAmelCase , addition_embed_type='''text_time''' , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=8_0 , cross_attention_dim=6_4 , )
_lowerCamelCase : Dict = EulerDiscreteScheduler(
beta_start=0.0_00_85 , beta_end=0.0_12 , steps_offset=1 , beta_schedule='''scaled_linear''' , timestep_spacing='''leading''' , )
torch.manual_seed(0 )
_lowerCamelCase : str = AutoencoderKL(
block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=1_2_8 , )
torch.manual_seed(0 )
_lowerCamelCase : Any = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='''gelu''' , projection_dim=3_2 , )
_lowerCamelCase : Dict = CLIPTextModel(__lowerCAmelCase )
_lowerCamelCase : Dict = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' , local_files_only=__lowerCAmelCase )
_lowerCamelCase : List[str] = CLIPTextModelWithProjection(__lowerCAmelCase )
_lowerCamelCase : str = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' , local_files_only=__lowerCAmelCase )
_lowerCamelCase : List[Any] = {
'''unet''': unet,
'''scheduler''': scheduler,
'''vae''': vae,
'''text_encoder''': text_encoder,
'''tokenizer''': tokenizer,
'''text_encoder_2''': text_encoder_a,
'''tokenizer_2''': tokenizer_a,
# "safety_checker": None,
# "feature_extractor": None,
}
return components
def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : Tuple , __lowerCAmelCase : Any=0 ):
"""simple docstring"""
_lowerCamelCase : Dict = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__lowerCAmelCase ) ).to(__lowerCAmelCase )
_lowerCamelCase : str = image / 2 + 0.5
if str(__lowerCAmelCase ).startswith('''mps''' ):
_lowerCamelCase : Any = torch.manual_seed(__lowerCAmelCase )
else:
_lowerCamelCase : str = torch.Generator(device=__lowerCAmelCase ).manual_seed(__lowerCAmelCase )
_lowerCamelCase : Union[str, Any] = {
'''prompt''': '''A painting of a squirrel eating a burger''',
'''image''': image,
'''generator''': generator,
'''num_inference_steps''': 2,
'''guidance_scale''': 5.0,
'''output_type''': '''numpy''',
'''strength''': 0.75,
}
return inputs
def SCREAMING_SNAKE_CASE ( self : Dict ):
"""simple docstring"""
_lowerCamelCase : Dict = '''cpu''' # ensure determinism for the device-dependent torch.Generator
_lowerCamelCase : int = self.get_dummy_components()
_lowerCamelCase : Any = StableDiffusionXLImgaImgPipeline(**__lowerCAmelCase )
_lowerCamelCase : List[Any] = sd_pipe.to(__lowerCAmelCase )
sd_pipe.set_progress_bar_config(disable=__lowerCAmelCase )
_lowerCamelCase : Optional[Any] = self.get_dummy_inputs(__lowerCAmelCase )
_lowerCamelCase : List[Any] = sd_pipe(**__lowerCAmelCase ).images
_lowerCamelCase : Tuple = image[0, -3:, -3:, -1]
assert image.shape == (1, 3_2, 3_2, 3)
_lowerCamelCase : Any = np.array([0.46_56, 0.48_40, 0.44_39, 0.66_98, 0.55_74, 0.45_24, 0.57_99, 0.59_43, 0.51_65] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def SCREAMING_SNAKE_CASE ( self : str ):
"""simple docstring"""
super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 )
def SCREAMING_SNAKE_CASE ( self : List[str] ):
"""simple docstring"""
super().test_inference_batch_single_identical(expected_max_diff=3E-3 )
def SCREAMING_SNAKE_CASE ( self : Any ):
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE ( self : int ):
"""simple docstring"""
_lowerCamelCase : Dict = self.get_dummy_components()
_lowerCamelCase : Dict = StableDiffusionXLImgaImgPipeline(**__lowerCAmelCase )
_lowerCamelCase : Optional[Any] = sd_pipe.to(__lowerCAmelCase )
_lowerCamelCase : Optional[int] = sd_pipe.to(__lowerCAmelCase )
sd_pipe.set_progress_bar_config(disable=__lowerCAmelCase )
# forward without prompt embeds
_lowerCamelCase : List[Any] = self.get_dummy_inputs(__lowerCAmelCase )
_lowerCamelCase : str = 3 * ['''this is a negative prompt''']
_lowerCamelCase : Dict = negative_prompt
_lowerCamelCase : int = 3 * [inputs['''prompt''']]
_lowerCamelCase : Dict = sd_pipe(**__lowerCAmelCase )
_lowerCamelCase : Tuple = output.images[0, -3:, -3:, -1]
# forward with prompt embeds
_lowerCamelCase : List[str] = self.get_dummy_inputs(__lowerCAmelCase )
_lowerCamelCase : str = 3 * ['''this is a negative prompt''']
_lowerCamelCase : int = 3 * [inputs.pop('''prompt''' )]
(
(
_lowerCamelCase
) , (
_lowerCamelCase
) , (
_lowerCamelCase
) , (
_lowerCamelCase
) ,
) : Any = sd_pipe.encode_prompt(__lowerCAmelCase , negative_prompt=__lowerCAmelCase )
_lowerCamelCase : Optional[Any] = sd_pipe(
**__lowerCAmelCase , prompt_embeds=__lowerCAmelCase , negative_prompt_embeds=__lowerCAmelCase , pooled_prompt_embeds=__lowerCAmelCase , negative_pooled_prompt_embeds=__lowerCAmelCase , )
_lowerCamelCase : str = output.images[0, -3:, -3:, -1]
# make sure that it's equal
assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4
@slow
@require_torch_gpu
class __snake_case ( unittest.TestCase):
def SCREAMING_SNAKE_CASE ( self : List[str] ):
"""simple docstring"""
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : Any , __lowerCAmelCase : Tuple="cpu" , __lowerCAmelCase : Tuple=torch.floataa , __lowerCAmelCase : Dict=0 ):
"""simple docstring"""
_lowerCamelCase : Tuple = torch.Generator(device=__lowerCAmelCase ).manual_seed(__lowerCAmelCase )
_lowerCamelCase : Optional[Any] = np.random.RandomState(__lowerCAmelCase ).standard_normal((1, 4, 6_4, 6_4) )
_lowerCamelCase : List[Any] = torch.from_numpy(__lowerCAmelCase ).to(device=__lowerCAmelCase , dtype=__lowerCAmelCase )
_lowerCamelCase : Optional[Any] = {
'''prompt''': '''a photograph of an astronaut riding a horse''',
'''latents''': latents,
'''generator''': generator,
'''num_inference_steps''': 3,
'''guidance_scale''': 7.5,
'''output_type''': '''numpy''',
}
return inputs
def SCREAMING_SNAKE_CASE ( self : Optional[int] ):
"""simple docstring"""
_lowerCamelCase : List[str] = DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base''' )
pipe.to(__lowerCAmelCase )
pipe.set_progress_bar_config(disable=__lowerCAmelCase )
_lowerCamelCase : List[Any] = self.get_inputs(__lowerCAmelCase )
_lowerCamelCase : int = pipe(**__lowerCAmelCase ).images
_lowerCamelCase : Tuple = image[0, -3:, -3:, -1].flatten()
assert image.shape == (1, 5_1_2, 5_1_2, 3)
_lowerCamelCase : Optional[int] = np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06] )
assert np.abs(image_slice - expected_slice ).max() < 7E-3
| 83 |
"""simple docstring"""
from __future__ import annotations
def lowerCAmelCase_ ( lowercase_ : int ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ )
return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' )
def lowerCAmelCase_ ( ):
'''simple docstring'''
for base_num in range(9999 , 4999 , -1 ):
__SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num
if is_9_pandigital(lowercase_ ):
return candidate
for base_num in range(333 , 99 , -1 ):
__SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num
if is_9_pandigital(lowercase_ ):
return candidate
return None
if __name__ == "__main__":
print(f'{solution() = }')
| 674 | 0 |
import argparse
from collections import OrderedDict
from pathlib import Path
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from torchvision.transforms import functional as F
from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection
from transformers.utils import logging
logging.set_verbosity_info()
UpperCAmelCase = logging.get_logger(__name__)
# here we list all keys to be renamed (original name on the left, our name on the right)
UpperCAmelCase = []
for i in range(6):
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
rename_keys.append(
(F"""transformer.encoder.layers.{i}.self_attn.out_proj.weight""", F"""encoder.layers.{i}.self_attn.out_proj.weight""")
)
rename_keys.append(
(F"""transformer.encoder.layers.{i}.self_attn.out_proj.bias""", F"""encoder.layers.{i}.self_attn.out_proj.bias""")
)
rename_keys.append((F"""transformer.encoder.layers.{i}.linear1.weight""", F"""encoder.layers.{i}.fc1.weight"""))
rename_keys.append((F"""transformer.encoder.layers.{i}.linear1.bias""", F"""encoder.layers.{i}.fc1.bias"""))
rename_keys.append((F"""transformer.encoder.layers.{i}.linear2.weight""", F"""encoder.layers.{i}.fc2.weight"""))
rename_keys.append((F"""transformer.encoder.layers.{i}.linear2.bias""", F"""encoder.layers.{i}.fc2.bias"""))
rename_keys.append(
(F"""transformer.encoder.layers.{i}.norm1.weight""", F"""encoder.layers.{i}.self_attn_layer_norm.weight""")
)
rename_keys.append((F"""transformer.encoder.layers.{i}.norm1.bias""", F"""encoder.layers.{i}.self_attn_layer_norm.bias"""))
rename_keys.append((F"""transformer.encoder.layers.{i}.norm2.weight""", F"""encoder.layers.{i}.final_layer_norm.weight"""))
rename_keys.append((F"""transformer.encoder.layers.{i}.norm2.bias""", F"""encoder.layers.{i}.final_layer_norm.bias"""))
# decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms
rename_keys.append(
(F"""transformer.decoder.layers.{i}.self_attn.out_proj.weight""", F"""decoder.layers.{i}.self_attn.out_proj.weight""")
)
rename_keys.append(
(F"""transformer.decoder.layers.{i}.self_attn.out_proj.bias""", F"""decoder.layers.{i}.self_attn.out_proj.bias""")
)
rename_keys.append(
(
F"""transformer.decoder.layers.{i}.multihead_attn.out_proj.weight""",
F"""decoder.layers.{i}.encoder_attn.out_proj.weight""",
)
)
rename_keys.append(
(
F"""transformer.decoder.layers.{i}.multihead_attn.out_proj.bias""",
F"""decoder.layers.{i}.encoder_attn.out_proj.bias""",
)
)
rename_keys.append((F"""transformer.decoder.layers.{i}.linear1.weight""", F"""decoder.layers.{i}.fc1.weight"""))
rename_keys.append((F"""transformer.decoder.layers.{i}.linear1.bias""", F"""decoder.layers.{i}.fc1.bias"""))
rename_keys.append((F"""transformer.decoder.layers.{i}.linear2.weight""", F"""decoder.layers.{i}.fc2.weight"""))
rename_keys.append((F"""transformer.decoder.layers.{i}.linear2.bias""", F"""decoder.layers.{i}.fc2.bias"""))
rename_keys.append(
(F"""transformer.decoder.layers.{i}.norm1.weight""", F"""decoder.layers.{i}.self_attn_layer_norm.weight""")
)
rename_keys.append((F"""transformer.decoder.layers.{i}.norm1.bias""", F"""decoder.layers.{i}.self_attn_layer_norm.bias"""))
rename_keys.append(
(F"""transformer.decoder.layers.{i}.norm2.weight""", F"""decoder.layers.{i}.encoder_attn_layer_norm.weight""")
)
rename_keys.append(
(F"""transformer.decoder.layers.{i}.norm2.bias""", F"""decoder.layers.{i}.encoder_attn_layer_norm.bias""")
)
rename_keys.append((F"""transformer.decoder.layers.{i}.norm3.weight""", F"""decoder.layers.{i}.final_layer_norm.weight"""))
rename_keys.append((F"""transformer.decoder.layers.{i}.norm3.bias""", F"""decoder.layers.{i}.final_layer_norm.bias"""))
# convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads
rename_keys.extend(
[
('''input_proj.weight''', '''input_projection.weight'''),
('''input_proj.bias''', '''input_projection.bias'''),
('''query_embed.weight''', '''query_position_embeddings.weight'''),
('''transformer.encoder.norm.weight''', '''encoder.layernorm.weight'''),
('''transformer.encoder.norm.bias''', '''encoder.layernorm.bias'''),
('''transformer.decoder.norm.weight''', '''decoder.layernorm.weight'''),
('''transformer.decoder.norm.bias''', '''decoder.layernorm.bias'''),
('''class_embed.weight''', '''class_labels_classifier.weight'''),
('''class_embed.bias''', '''class_labels_classifier.bias'''),
('''bbox_embed.layers.0.weight''', '''bbox_predictor.layers.0.weight'''),
('''bbox_embed.layers.0.bias''', '''bbox_predictor.layers.0.bias'''),
('''bbox_embed.layers.1.weight''', '''bbox_predictor.layers.1.weight'''),
('''bbox_embed.layers.1.bias''', '''bbox_predictor.layers.1.bias'''),
('''bbox_embed.layers.2.weight''', '''bbox_predictor.layers.2.weight'''),
('''bbox_embed.layers.2.bias''', '''bbox_predictor.layers.2.bias'''),
]
)
def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
lowercase = state_dict.pop(__SCREAMING_SNAKE_CASE )
lowercase = val
def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE ):
lowercase = OrderedDict()
for key, value in state_dict.items():
if "backbone.0.body" in key:
lowercase = key.replace('backbone.0.body' , 'backbone.conv_encoder.model' )
lowercase = value
else:
lowercase = value
return new_state_dict
def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE ):
lowercase = ''
# first: transformer encoder
for i in range(6 ):
# read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias)
lowercase = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' )
lowercase = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias''' )
# next, add query, keys and values (in that order) to the state dict
lowercase = in_proj_weight[:256, :]
lowercase = in_proj_bias[:256]
lowercase = in_proj_weight[256:512, :]
lowercase = in_proj_bias[256:512]
lowercase = in_proj_weight[-256:, :]
lowercase = in_proj_bias[-256:]
# next: transformer decoder (which is a bit more complex because it also includes cross-attention)
for i in range(6 ):
# read in weights + bias of input projection layer of self-attention
lowercase = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight''' )
lowercase = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias''' )
# next, add query, keys and values (in that order) to the state dict
lowercase = in_proj_weight[:256, :]
lowercase = in_proj_bias[:256]
lowercase = in_proj_weight[256:512, :]
lowercase = in_proj_bias[256:512]
lowercase = in_proj_weight[-256:, :]
lowercase = in_proj_bias[-256:]
# read in weights + bias of input projection layer of cross-attention
lowercase = state_dict.pop(
F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight''' )
lowercase = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias''' )
# next, add query, keys and values (in that order) of cross-attention to the state dict
lowercase = in_proj_weight_cross_attn[:256, :]
lowercase = in_proj_bias_cross_attn[:256]
lowercase = in_proj_weight_cross_attn[256:512, :]
lowercase = in_proj_bias_cross_attn[256:512]
lowercase = in_proj_weight_cross_attn[-256:, :]
lowercase = in_proj_bias_cross_attn[-256:]
def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
lowercase , lowercase = image.size
lowercase = max(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
lowercase = 800 if 'detection' in checkpoint_url else 1000
lowercase = target_max_size / current_max_size
lowercase = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) )
return resized_image
def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE ):
lowercase = F.to_tensor(__SCREAMING_SNAKE_CASE )
lowercase = F.normalize(__SCREAMING_SNAKE_CASE , mean=[0.4_85, 0.4_56, 0.4_06] , std=[0.2_29, 0.2_24, 0.2_25] )
return image
@torch.no_grad()
def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
logger.info('Converting model...' )
# load original state dict
lowercase = torch.hub.load_state_dict_from_url(__SCREAMING_SNAKE_CASE , map_location='cpu' )
# rename keys
for src, dest in rename_keys:
rename_key(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
lowercase = rename_backbone_keys(__SCREAMING_SNAKE_CASE )
# query, key and value matrices need special treatment
read_in_q_k_v(__SCREAMING_SNAKE_CASE )
# important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them
lowercase = 'model.'
for key in state_dict.copy().keys():
if not key.startswith('class_labels_classifier' ) and not key.startswith('bbox_predictor' ):
lowercase = state_dict.pop(__SCREAMING_SNAKE_CASE )
lowercase = val
# create HuggingFace model and load state dict
lowercase = TableTransformerConfig(
backbone='resnet18' , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , )
if "detection" in checkpoint_url:
lowercase = 15
lowercase = 2
lowercase = {0: 'table', 1: 'table rotated'}
lowercase = idalabel
lowercase = {v: k for k, v in idalabel.items()}
else:
lowercase = 125
lowercase = 6
lowercase = {
0: 'table',
1: 'table column',
2: 'table row',
3: 'table column header',
4: 'table projected row header',
5: 'table spanning cell',
}
lowercase = idalabel
lowercase = {v: k for k, v in idalabel.items()}
lowercase = DetrImageProcessor(
format='coco_detection' , max_size=800 if 'detection' in checkpoint_url else 1000 )
lowercase = TableTransformerForObjectDetection(__SCREAMING_SNAKE_CASE )
model.load_state_dict(__SCREAMING_SNAKE_CASE )
model.eval()
# verify our conversion
lowercase = 'example_pdf.png' if 'detection' in checkpoint_url else 'example_table.png'
lowercase = hf_hub_download(repo_id='nielsr/example-pdf' , repo_type='dataset' , filename=__SCREAMING_SNAKE_CASE )
lowercase = Image.open(__SCREAMING_SNAKE_CASE ).convert('RGB' )
lowercase = normalize(resize(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ).unsqueeze(0 )
lowercase = model(__SCREAMING_SNAKE_CASE )
if "detection" in checkpoint_url:
lowercase = (1, 15, 3)
lowercase = torch.tensor(
[[-6.78_97, -16.99_85, 6.79_37], [-8.01_86, -22.21_92, 6.96_77], [-7.31_17, -21.07_08, 7.40_55]] )
lowercase = torch.tensor([[0.48_67, 0.17_67, 0.67_32], [0.67_18, 0.44_79, 0.38_30], [0.47_16, 0.17_60, 0.63_64]] )
else:
lowercase = (1, 125, 7)
lowercase = torch.tensor(
[[-18.14_30, -8.32_14, 4.82_74], [-18.46_85, -7.13_61, -4.26_67], [-26.36_93, -9.34_29, -4.99_62]] )
lowercase = torch.tensor([[0.49_83, 0.55_95, 0.94_40], [0.49_16, 0.63_15, 0.59_54], [0.61_08, 0.86_37, 0.11_35]] )
assert outputs.logits.shape == expected_shape
assert torch.allclose(outputs.logits[0, :3, :3] , __SCREAMING_SNAKE_CASE , atol=1e-4 )
assert torch.allclose(outputs.pred_boxes[0, :3, :3] , __SCREAMING_SNAKE_CASE , atol=1e-4 )
print('Looks ok!' )
if pytorch_dump_folder_path is not None:
# Save model and image processor
logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' )
Path(__SCREAMING_SNAKE_CASE ).mkdir(exist_ok=__SCREAMING_SNAKE_CASE )
model.save_pretrained(__SCREAMING_SNAKE_CASE )
image_processor.save_pretrained(__SCREAMING_SNAKE_CASE )
if push_to_hub:
# Push model to HF hub
logger.info('Pushing model to the hub...' )
lowercase = (
'microsoft/table-transformer-detection'
if 'detection' in checkpoint_url
else 'microsoft/table-transformer-structure-recognition'
)
model.push_to_hub(__SCREAMING_SNAKE_CASE )
image_processor.push_to_hub(__SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
UpperCAmelCase = argparse.ArgumentParser()
parser.add_argument(
'''--checkpoint_url''',
default='''https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth''',
type=str,
choices=[
'''https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth''',
'''https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth''',
],
help='''URL of the Table Transformer checkpoint you\'d like to convert.''',
)
parser.add_argument(
'''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.'''
)
parser.add_argument(
'''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.'''
)
UpperCAmelCase = parser.parse_args()
convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
| 84 |
"""simple docstring"""
import json
import sys
import tempfile
import unittest
from pathlib import Path
import transformers
from transformers import (
CONFIG_MAPPING,
IMAGE_PROCESSOR_MAPPING,
AutoConfig,
AutoImageProcessor,
CLIPConfig,
CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER
sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils'''))
from test_module.custom_configuration import CustomConfig # noqa E402
from test_module.custom_image_processing import CustomImageProcessor # noqa E402
class snake_case ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE_ ( self :int ):
__SCREAMING_SNAKE_CASE : Tuple = 0
def SCREAMING_SNAKE_CASE_ ( self :Any ):
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :int ):
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json'''
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) )
__SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# Ensure we can load the image processor from the feature extractor config
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json'''
__SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json'''
json.dump(
{'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) )
__SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :int ):
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : str = CLIPConfig()
# Create a dummy config file with image_proceesor_type
__SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json'''
__SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) )
# remove image_processor_type to make sure config.json alone is enough to load image processor locally
__SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict()
config_dict.pop('''image_processor_type''' )
__SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase )
# save in new folder
model_config.save_pretrained(_lowerCamelCase )
config.save_pretrained(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase )
# make sure private variable is not incorrectly saved
__SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() )
self.assertTrue('''_processor_class''' not in dict_as_saved )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , )
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
with self.assertRaisesRegex(
_lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ):
__SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
with self.assertRaisesRegex(
_lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ):
__SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
with self.assertRaisesRegex(
_lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ):
__SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
# If remote code is not set, we will time out when asking whether to load the model.
with self.assertRaises(_lowerCamelCase ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' )
# If remote code is disabled, we can't load this config.
with self.assertRaises(_lowerCamelCase ):
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
# Test image processor can be reloaded.
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase )
self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
try:
AutoConfig.register('''custom''' , _lowerCamelCase )
AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase )
# Trying to register something existing in the Transformers library will raise an error
with self.assertRaises(_lowerCamelCase ):
AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase )
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json'''
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json'''
json.dump(
{'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) )
__SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase )
# Now that the config is registered, it can be used as any other config with the auto-API
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = True
try:
AutoConfig.register('''custom''' , _lowerCamelCase )
AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase )
# If remote code is not set, the default is to use local
__SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
self.assertTrue(image_processor.is_local )
# If remote code is disabled, we load the local one.
__SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
self.assertTrue(image_processor.is_local )
# If remote is enabled, we load from the Hub
__SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
self.assertTrue(not hasattr(_lowerCamelCase , '''is_local''' ) )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
| 674 | 0 |
import collections
import tempfile
import unittest
import numpy as np
from transformers.testing_utils import (
is_pt_flax_cross_test,
require_flax,
require_torch,
require_vision,
slow,
torch_device,
)
from transformers.utils import is_flax_available, is_torch_available, is_vision_available
from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_flax_bert import FlaxBertModelTester
from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester
from ..vit.test_modeling_flax_vit import FlaxViTModelTester
if is_flax_available():
from transformers import (
FlaxBertModel,
FlaxCLIPVisionModel,
FlaxVisionTextDualEncoderModel,
FlaxViTModel,
VisionTextDualEncoderConfig,
VisionTextDualEncoderProcessor,
)
from transformers.modeling_flax_pytorch_utils import (
convert_pytorch_state_dict_to_flax,
load_flax_weights_in_pytorch_model,
)
if is_torch_available():
import torch
from transformers import VisionTextDualEncoderModel
if is_vision_available():
from PIL import Image
def _a ( lowercase__ : Dict ):
'''simple docstring'''
if isinstance(lowercase__ , collections.abc.Iterable ):
return x
return (x, x)
@require_flax
class snake_case :
def __lowercase( self : Dict , a_ : List[Any] , a_ : List[Any] )-> int:
"""simple docstring"""
pass
def __lowercase( self : Union[str, Any] )-> str:
"""simple docstring"""
pass
def __lowercase( self : Union[str, Any] )-> List[Any]:
"""simple docstring"""
pass
def __lowercase( self : Any , a_ : np.ndarray , a_ : np.ndarray , a_ : float )-> Optional[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Any = np.abs((a - b) ).max()
self.assertLessEqual(a_ , a_ , F'''Difference between torch and flax is {diff} (>= {tol}).''' )
def __lowercase( self : Optional[Any] , a_ : Optional[int] , a_ : Any , a_ : Optional[Any] , a_ : Dict , a_ : List[Any]=None , **a_ : Optional[int] )-> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Dict = VisionTextDualEncoderConfig.from_vision_text_configs(a_ , a_ )
SCREAMING_SNAKE_CASE__ : Dict = FlaxVisionTextDualEncoderModel(a_ )
SCREAMING_SNAKE_CASE__ : Dict = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ )
self.assertEqual(output['text_embeds'].shape , (input_ids.shape[0], config.projection_dim) )
self.assertEqual(output['image_embeds'].shape , (pixel_values.shape[0], config.projection_dim) )
def __lowercase( self : str , a_ : List[Any] , a_ : Dict , a_ : str , a_ : Optional[Any] , a_ : Optional[int]=None , **a_ : List[Any] )-> Optional[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_vision_text_model(a_ , a_ )
SCREAMING_SNAKE_CASE__ : Tuple = {'vision_model': vision_model, 'text_model': text_model}
SCREAMING_SNAKE_CASE__ : Any = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**a_ )
SCREAMING_SNAKE_CASE__ : Dict = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ )
self.assertEqual(output['text_embeds'].shape , (input_ids.shape[0], model.config.projection_dim) )
self.assertEqual(output['image_embeds'].shape , (pixel_values.shape[0], model.config.projection_dim) )
def __lowercase( self : Dict , a_ : Any , a_ : Any , a_ : List[str] , a_ : str , a_ : int=None , **a_ : Any )-> str:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.get_vision_text_model(a_ , a_ )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'vision_model': vision_model, 'text_model': text_model}
SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**a_ )
SCREAMING_SNAKE_CASE__ : Optional[int] = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ )
SCREAMING_SNAKE_CASE__ : List[str] = output[0]
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(a_ )
SCREAMING_SNAKE_CASE__ : Dict = FlaxVisionTextDualEncoderModel.from_pretrained(a_ )
SCREAMING_SNAKE_CASE__ : Tuple = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ )
SCREAMING_SNAKE_CASE__ : List[Any] = after_output[0]
SCREAMING_SNAKE_CASE__ : Any = np.amax(np.abs(out_a - out_a ) )
self.assertLessEqual(a_ , 1e-3 )
def __lowercase( self : Optional[int] , a_ : List[Any] , a_ : Optional[int] , a_ : List[str] , a_ : int , a_ : int=None , **a_ : Union[str, Any] )-> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = self.get_vision_text_model(a_ , a_ )
SCREAMING_SNAKE_CASE__ : Optional[int] = {'vision_model': vision_model, 'text_model': text_model}
SCREAMING_SNAKE_CASE__ : List[str] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**a_ )
SCREAMING_SNAKE_CASE__ : List[str] = model(
input_ids=a_ , pixel_values=a_ , attention_mask=a_ , output_attentions=a_ )
SCREAMING_SNAKE_CASE__ : int = output.vision_model_output.attentions
self.assertEqual(len(a_ ) , vision_config.num_hidden_layers )
# in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
SCREAMING_SNAKE_CASE__ : Any = to_atuple(vision_model.config.image_size )
SCREAMING_SNAKE_CASE__ : Dict = to_atuple(vision_model.config.patch_size )
SCREAMING_SNAKE_CASE__ : str = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
SCREAMING_SNAKE_CASE__ : Dict = num_patches + 1
self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) )
SCREAMING_SNAKE_CASE__ : int = output.text_model_output.attentions
self.assertEqual(len(a_ ) , text_config.num_hidden_layers )
self.assertEqual(
text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , )
def __lowercase( self : str , a_ : Optional[Any] , a_ : Optional[int] , a_ : List[str] )-> Optional[int]:
"""simple docstring"""
pt_model.to(a_ )
pt_model.eval()
# prepare inputs
SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs_dict
SCREAMING_SNAKE_CASE__ : Tuple = {k: torch.tensor(v.tolist() ) for k, v in flax_inputs.items()}
with torch.no_grad():
SCREAMING_SNAKE_CASE__ : Any = pt_model(**a_ ).to_tuple()
SCREAMING_SNAKE_CASE__ : Union[str, Any] = fx_model(**a_ ).to_tuple()
self.assertEqual(len(a_ ) , len(a_ ) , 'Output lengths differ between Flax and PyTorch' )
for fx_output, pt_output in zip(fx_outputs[:4] , pt_outputs[:4] ):
self.assert_almost_equals(a_ , pt_output.numpy() , 4e-2 )
# PT -> Flax
with tempfile.TemporaryDirectory() as tmpdirname:
pt_model.save_pretrained(a_ )
SCREAMING_SNAKE_CASE__ : str = FlaxVisionTextDualEncoderModel.from_pretrained(a_ , from_pt=a_ )
SCREAMING_SNAKE_CASE__ : int = fx_model_loaded(**a_ ).to_tuple()
self.assertEqual(len(a_ ) , len(a_ ) , 'Output lengths differ between Flax and PyTorch' )
for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4] , pt_outputs[:4] ):
self.assert_almost_equals(a_ , pt_output.numpy() , 4e-2 )
# Flax -> PT
with tempfile.TemporaryDirectory() as tmpdirname:
fx_model.save_pretrained(a_ )
SCREAMING_SNAKE_CASE__ : List[Any] = VisionTextDualEncoderModel.from_pretrained(a_ , from_flax=a_ )
pt_model_loaded.to(a_ )
pt_model_loaded.eval()
with torch.no_grad():
SCREAMING_SNAKE_CASE__ : str = pt_model_loaded(**a_ ).to_tuple()
self.assertEqual(len(a_ ) , len(a_ ) , 'Output lengths differ between Flax and PyTorch' )
for fx_output, pt_output_loaded in zip(fx_outputs[:4] , pt_outputs_loaded[:4] ):
self.assert_almost_equals(a_ , pt_output_loaded.numpy() , 4e-2 )
def __lowercase( self : int , a_ : List[str] , a_ : str , a_ : Tuple )-> List[str]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Tuple = VisionTextDualEncoderConfig.from_vision_text_configs(a_ , a_ )
SCREAMING_SNAKE_CASE__ : Optional[Any] = VisionTextDualEncoderModel(a_ )
SCREAMING_SNAKE_CASE__ : Optional[Any] = FlaxVisionTextDualEncoderModel(a_ )
SCREAMING_SNAKE_CASE__ : Tuple = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , a_ )
SCREAMING_SNAKE_CASE__ : str = fx_state
self.check_pt_flax_equivalence(a_ , a_ , a_ )
def __lowercase( self : int , a_ : List[Any] , a_ : int , a_ : List[Any] )-> Optional[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Tuple = VisionTextDualEncoderConfig.from_vision_text_configs(a_ , a_ )
SCREAMING_SNAKE_CASE__ : List[str] = VisionTextDualEncoderModel(a_ )
SCREAMING_SNAKE_CASE__ : Optional[Any] = FlaxVisionTextDualEncoderModel(a_ )
SCREAMING_SNAKE_CASE__ : Optional[Any] = load_flax_weights_in_pytorch_model(a_ , fx_model.params )
self.check_pt_flax_equivalence(a_ , a_ , a_ )
def __lowercase( self : Union[str, Any] )-> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_config_and_inputs()
self.check_model_from_pretrained_configs(**a_ )
def __lowercase( self : Any )-> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : int = self.prepare_config_and_inputs()
self.check_vision_text_dual_encoder_from_pretrained(**a_ )
def __lowercase( self : str )-> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs()
self.check_save_load(**a_ )
def __lowercase( self : int )-> Tuple:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Optional[Any] = self.prepare_config_and_inputs()
self.check_vision_text_output_attention(**a_ )
@is_pt_flax_cross_test
def __lowercase( self : int )-> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : int = self.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE__ : Optional[int] = config_inputs_dict.pop('vision_config' )
SCREAMING_SNAKE_CASE__ : List[Any] = config_inputs_dict.pop('text_config' )
SCREAMING_SNAKE_CASE__ : Tuple = config_inputs_dict
self.check_equivalence_pt_to_flax(a_ , a_ , a_ )
self.check_equivalence_flax_to_pt(a_ , a_ , a_ )
@slow
def __lowercase( self : str )-> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.get_pretrained_model_and_inputs()
SCREAMING_SNAKE_CASE__ : Any = model_a(**a_ )
SCREAMING_SNAKE_CASE__ : str = outputs[0]
with tempfile.TemporaryDirectory() as tmp_dirname:
model_a.save_pretrained(a_ )
SCREAMING_SNAKE_CASE__ : Any = FlaxVisionTextDualEncoderModel.from_pretrained(a_ )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_a(**a_ )
SCREAMING_SNAKE_CASE__ : List[Any] = after_outputs[0]
SCREAMING_SNAKE_CASE__ : List[Any] = np.amax(np.abs(out_a - out_a ) )
self.assertLessEqual(a_ , 1e-5 )
@require_flax
class snake_case ( UpperCamelCase_ , unittest.TestCase ):
def __lowercase( self : Union[str, Any] )-> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Any = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
'hf-internal-testing/tiny-random-vit' , 'hf-internal-testing/tiny-bert' , vision_from_pt=a_ , text_from_pt=a_ , )
SCREAMING_SNAKE_CASE__ : Tuple = 13
SCREAMING_SNAKE_CASE__ : Dict = floats_tensor(
[
batch_size,
model.config.vision_config.num_channels,
model.config.vision_config.image_size,
model.config.vision_config.image_size,
] )
SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = random_attention_mask([batch_size, 4] )
SCREAMING_SNAKE_CASE__ : Tuple = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}
return model, inputs
def __lowercase( self : List[str] , a_ : Any , a_ : Tuple )-> str:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Optional[int] = FlaxViTModel(a_ )
SCREAMING_SNAKE_CASE__ : int = FlaxBertModel(a_ )
return vision_model, text_model
def __lowercase( self : Union[str, Any] )-> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : List[Any] = FlaxViTModelTester(self )
SCREAMING_SNAKE_CASE__ : Dict = FlaxBertModelTester(self )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = vit_model_tester.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE__ : Dict = bert_model_tester.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = vision_config_and_inputs
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = text_config_and_inputs
# make sure that cross attention layers are added
return {
"text_config": text_config,
"vision_config": vision_config,
"pixel_values": pixel_values,
"attention_mask": attention_mask,
"input_ids": input_ids,
"token_type_ids": token_type_ids,
}
@require_torch
class snake_case ( UpperCamelCase_ , unittest.TestCase ):
def __lowercase( self : List[Any] )-> str:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : str = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
'hf-internal-testing/tiny-random-clip' , 'hf-internal-testing/tiny-bert' , vision_from_pt=a_ , text_from_pt=a_ , )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = 13
SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor(
[
batch_size,
model.config.vision_config.num_channels,
model.config.vision_config.image_size,
model.config.vision_config.image_size,
] )
SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = random_attention_mask([batch_size, 4] )
SCREAMING_SNAKE_CASE__ : List[str] = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}
return model, inputs
def __lowercase( self : str , a_ : Optional[int] , a_ : str )-> List[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : str = FlaxCLIPVisionModel(a_ )
SCREAMING_SNAKE_CASE__ : Optional[int] = FlaxBertModel(a_ )
return vision_model, text_model
def __lowercase( self : str )-> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaxCLIPVisionModelTester(self )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaxBertModelTester(self )
SCREAMING_SNAKE_CASE__ : Any = clip_model_tester.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE__ : int = bert_model_tester.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = vision_config_and_inputs
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = text_config_and_inputs
# make sure that cross attention layers are added
return {
"text_config": text_config,
"vision_config": vision_config,
"pixel_values": pixel_values,
"attention_mask": attention_mask,
"input_ids": input_ids,
"token_type_ids": token_type_ids,
}
@require_flax
@require_vision
class snake_case ( unittest.TestCase ):
@slow
def __lowercase( self : Optional[int] )-> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian' , logit_scale_init_value=1.0 )
SCREAMING_SNAKE_CASE__ : Tuple = VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian' )
SCREAMING_SNAKE_CASE__ : Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
SCREAMING_SNAKE_CASE__ : Optional[int] = processor(
text=['una foto di un gatto', 'una foto di un cane'] , images=a_ , padding=a_ , return_tensors='np' )
SCREAMING_SNAKE_CASE__ : Tuple = model(**a_ )
# verify the logits
self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) )
self.assertEqual(
outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , )
SCREAMING_SNAKE_CASE__ : Any = np.array([[1.228_4727, 0.310_4122]] )
self.assertTrue(np.allclose(outputs.logits_per_image , a_ , atol=1e-3 ) )
| 85 |
"""simple docstring"""
from __future__ import annotations
from typing import Any
class snake_case ( __UpperCAmelCase ):
pass
class snake_case :
def __init__( self :List[Any] , _lowerCamelCase :Any ):
__SCREAMING_SNAKE_CASE : Any = data
__SCREAMING_SNAKE_CASE : Node | None = None
def __iter__( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : List[str] = self
__SCREAMING_SNAKE_CASE : List[str] = []
while node:
if node in visited:
raise ContainsLoopError
visited.append(_lowerCamelCase )
yield node.data
__SCREAMING_SNAKE_CASE : List[str] = node.next_node
@property
def SCREAMING_SNAKE_CASE_ ( self :Any ):
try:
list(self )
return False
except ContainsLoopError:
return True
if __name__ == "__main__":
_lowerCamelCase = Node(1)
_lowerCamelCase = Node(2)
_lowerCamelCase = Node(3)
_lowerCamelCase = Node(4)
print(root_node.has_loop) # False
_lowerCamelCase = root_node.next_node
print(root_node.has_loop) # True
_lowerCamelCase = Node(5)
_lowerCamelCase = Node(6)
_lowerCamelCase = Node(5)
_lowerCamelCase = Node(6)
print(root_node.has_loop) # False
_lowerCamelCase = Node(1)
print(root_node.has_loop) # False
| 674 | 0 |
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import GLPNImageProcessor
class _a ( unittest.TestCase ):
"""simple docstring"""
def __init__( self : List[Any] , UpperCAmelCase : List[str] , UpperCAmelCase : Any=7 , UpperCAmelCase : Dict=3 , UpperCAmelCase : Optional[Any]=18 , UpperCAmelCase : List[str]=30 , UpperCAmelCase : Optional[Any]=400 , UpperCAmelCase : str=True , UpperCAmelCase : Optional[int]=32 , UpperCAmelCase : Dict=True , ):
A_ = parent
A_ = batch_size
A_ = num_channels
A_ = image_size
A_ = min_resolution
A_ = max_resolution
A_ = do_resize
A_ = size_divisor
A_ = do_rescale
def __A ( self : Tuple ):
return {
"do_resize": self.do_resize,
"size_divisor": self.size_divisor,
"do_rescale": self.do_rescale,
}
@require_torch
@require_vision
class _a ( snake_case_ , unittest.TestCase ):
"""simple docstring"""
_lowerCamelCase : Any = GLPNImageProcessor if is_vision_available() else None
def __A ( self : Any ):
A_ = GLPNImageProcessingTester(self )
@property
def __A ( self : List[str] ):
return self.image_processor_tester.prepare_image_processor_dict()
def __A ( self : Optional[Any] ):
A_ = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(UpperCAmelCase , "do_resize" ) )
self.assertTrue(hasattr(UpperCAmelCase , "size_divisor" ) )
self.assertTrue(hasattr(UpperCAmelCase , "resample" ) )
self.assertTrue(hasattr(UpperCAmelCase , "do_rescale" ) )
def __A ( self : List[str] ):
pass
def __A ( self : Optional[Any] ):
# Initialize image_processing
A_ = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
A_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase )
for image in image_inputs:
self.assertIsInstance(UpperCAmelCase , Image.Image )
# Test not batched input (GLPNImageProcessor doesn't support batching)
A_ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 )
self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
def __A ( self : str ):
# Initialize image_processing
A_ = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
A_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase , numpify=UpperCAmelCase )
for image in image_inputs:
self.assertIsInstance(UpperCAmelCase , np.ndarray )
# Test not batched input (GLPNImageProcessor doesn't support batching)
A_ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 )
self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
def __A ( self : str ):
# Initialize image_processing
A_ = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
A_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase , torchify=UpperCAmelCase )
for image in image_inputs:
self.assertIsInstance(UpperCAmelCase , torch.Tensor )
# Test not batched input (GLPNImageProcessor doesn't support batching)
A_ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 )
self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) | 86 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_lowerCamelCase = logging.get_logger(__name__)
_lowerCamelCase = {
'''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''',
}
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = '''roc_bert'''
def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ):
__SCREAMING_SNAKE_CASE : List[str] = vocab_size
__SCREAMING_SNAKE_CASE : int = max_position_embeddings
__SCREAMING_SNAKE_CASE : List[str] = hidden_size
__SCREAMING_SNAKE_CASE : str = num_hidden_layers
__SCREAMING_SNAKE_CASE : int = num_attention_heads
__SCREAMING_SNAKE_CASE : Any = intermediate_size
__SCREAMING_SNAKE_CASE : Optional[int] = hidden_act
__SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob
__SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob
__SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range
__SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size
__SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps
__SCREAMING_SNAKE_CASE : Optional[int] = use_cache
__SCREAMING_SNAKE_CASE : str = enable_pronunciation
__SCREAMING_SNAKE_CASE : List[str] = enable_shape
__SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim
__SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size
__SCREAMING_SNAKE_CASE : str = shape_embed_dim
__SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size
__SCREAMING_SNAKE_CASE : Tuple = concat_input
__SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type
__SCREAMING_SNAKE_CASE : str = classifier_dropout
super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
| 674 | 0 |
import warnings
from ...utils import logging
from .image_processing_yolos import YolosImageProcessor
_lowerCamelCase : Any = logging.get_logger(__name__)
class UpperCamelCase_ ( UpperCAmelCase__ ):
'''simple docstring'''
def __init__( self : Any , *UpperCAmelCase__ : Optional[int] , **UpperCAmelCase__ : Tuple) ->None:
'''simple docstring'''
warnings.warn(
'''The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please'''
''' use YolosImageProcessor instead.''' , UpperCAmelCase__ , )
super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__)
| 87 |
"""simple docstring"""
import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List
import git
import torch
from torch.utils.data import Dataset
from transformers import BartTokenizer, RagTokenizer, TaTokenizer
def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {}
__SCREAMING_SNAKE_CASE : Optional[int] = padding_side
return tokenizer(
[line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , )
def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 )
if attention_mask is None:
return input_ids[:, keep_column_mask]
else:
return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])
class snake_case ( __UpperCAmelCase ):
def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ):
super().__init__()
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' )
__SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' )
__SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file )
__SCREAMING_SNAKE_CASE : List[str] = max_source_length
__SCREAMING_SNAKE_CASE : Dict = max_target_length
assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}'''
__SCREAMING_SNAKE_CASE : Dict = tokenizer
__SCREAMING_SNAKE_CASE : Union[str, Any] = prefix
if n_obs is not None:
__SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs]
__SCREAMING_SNAKE_CASE : List[str] = src_lang
__SCREAMING_SNAKE_CASE : str = tgt_lang
def __len__( self :int ):
return len(self.src_lens )
def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ):
__SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1
__SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' )
__SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' )
assert source_line, f'''empty source line for index {index}'''
assert tgt_line, f'''empty tgt line for index {index}'''
# Need to add eos token manually for T5
if isinstance(self.tokenizer , _lowerCamelCase ):
source_line += self.tokenizer.eos_token
tgt_line += self.tokenizer.eos_token
# Pad source and target to the right
__SCREAMING_SNAKE_CASE : Dict = (
self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer
)
__SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer
__SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' )
__SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' )
__SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze()
__SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze()
__SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze()
return {
"input_ids": source_ids,
"attention_mask": src_mask,
"decoder_input_ids": target_ids,
}
@staticmethod
def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ):
return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()]
def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ):
__SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] )
__SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] )
__SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] )
__SCREAMING_SNAKE_CASE : str = (
self.tokenizer.generator.pad_token_id
if isinstance(self.tokenizer , _lowerCamelCase )
else self.tokenizer.pad_token_id
)
__SCREAMING_SNAKE_CASE : Union[str, Any] = (
self.tokenizer.question_encoder.pad_token_id
if isinstance(self.tokenizer , _lowerCamelCase )
else self.tokenizer.pad_token_id
)
__SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Dict = {
'''input_ids''': source_ids,
'''attention_mask''': source_mask,
'''decoder_input_ids''': y,
}
return batch
_lowerCamelCase = getLogger(__name__)
def lowerCAmelCase_ ( lowercase_ : List[List] ):
'''simple docstring'''
return list(itertools.chain.from_iterable(lowercase_ ) )
def lowerCAmelCase_ ( lowercase_ : str ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = get_git_info()
save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) )
def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ):
'''simple docstring'''
with open(lowercase_ , '''w''' ) as f:
json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ )
def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ):
'''simple docstring'''
with open(lowercase_ ) as f:
return json.load(lowercase_ )
def lowerCAmelCase_ ( ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ )
__SCREAMING_SNAKE_CASE : List[str] = {
'''repo_id''': str(lowercase_ ),
'''repo_sha''': str(repo.head.object.hexsha ),
'''repo_branch''': str(repo.active_branch ),
'''hostname''': str(socket.gethostname() ),
}
return repo_infos
def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ):
'''simple docstring'''
return list(map(lowercase_ , lowercase_ ) )
def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ):
'''simple docstring'''
with open(lowercase_ , '''wb''' ) as f:
return pickle.dump(lowercase_ , lowercase_ )
def lowerCAmelCase_ ( lowercase_ : Any ):
'''simple docstring'''
def remove_articles(lowercase_ : Dict ):
return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ )
def white_space_fix(lowercase_ : Optional[int] ):
return " ".join(text.split() )
def remove_punc(lowercase_ : Any ):
__SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation )
return "".join(ch for ch in text if ch not in exclude )
def lower(lowercase_ : int ):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) )
def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split()
__SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split()
__SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ )
__SCREAMING_SNAKE_CASE : Tuple = sum(common.values() )
if num_same == 0:
return 0
__SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ )
__SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ )
__SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall)
return fa
def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ):
'''simple docstring'''
return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ )
def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ):
'''simple docstring'''
assert len(lowercase_ ) == len(lowercase_ )
__SCREAMING_SNAKE_CASE : Union[str, Any] = 0
for hypo, pred in zip(lowercase_ , lowercase_ ):
em += exact_match_score(lowercase_ , lowercase_ )
if len(lowercase_ ) > 0:
em /= len(lowercase_ )
return {"em": em}
def lowerCAmelCase_ ( lowercase_ : str ):
'''simple docstring'''
return model_prefix.startswith('''rag''' )
def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params}
# T5 models don't have `dropout` param, they have `dropout_rate` instead
__SCREAMING_SNAKE_CASE : Any = '''dropout_rate'''
for p in extra_params:
if getattr(lowercase_ , lowercase_ , lowercase_ ):
if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ):
logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) )
delattr(lowercase_ , lowercase_ )
continue
__SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p]
setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) )
delattr(lowercase_ , lowercase_ )
return hparams, config
| 674 | 0 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_tokenizers_available,
is_torch_available,
)
UpperCAmelCase = {"""configuration_fnet""": ["""FNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FNetConfig"""]}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase = ["""FNetTokenizer"""]
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase = ["""FNetTokenizerFast"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase = [
"""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
UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 88 |
"""simple docstring"""
from collections.abc import Callable
import numpy as np
def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) )
__SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) )
__SCREAMING_SNAKE_CASE : List[Any] = ya
__SCREAMING_SNAKE_CASE : Dict = xa
for k in range(lowercase_ ):
__SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] )
__SCREAMING_SNAKE_CASE : int = y[k] + (
(step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ ))
)
x += step_size
return y
if __name__ == "__main__":
import doctest
doctest.testmod()
| 674 | 0 |
import gc
import unittest
import numpy as np
import torch
from diffusers import StableDiffusionKDiffusionPipeline
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
enable_full_determinism()
@slow
@require_torch_gpu
class _lowerCamelCase( unittest.TestCase ):
def UpperCamelCase ( self) -> Tuple:
"""simple docstring"""
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCamelCase ( self) -> Union[str, Any]:
"""simple docstring"""
_lowercase : Any = StableDiffusionKDiffusionPipeline.from_pretrained('CompVis/stable-diffusion-v1-4')
_lowercase : Optional[Any] = sd_pipe.to(lowerCamelCase)
sd_pipe.set_progress_bar_config(disable=lowerCamelCase)
sd_pipe.set_scheduler('sample_euler')
_lowercase : str = 'A painting of a squirrel eating a burger'
_lowercase : int = torch.manual_seed(0)
_lowercase : int = sd_pipe([prompt], generator=lowerCamelCase, guidance_scale=9.0, num_inference_steps=20, output_type='np')
_lowercase : Union[str, Any] = output.images
_lowercase : Optional[Any] = image[0, -3:, -3:, -1]
assert image.shape == (1, 5_12, 5_12, 3)
_lowercase : Dict = np.array([0.0_4_4_7, 0.0_4_9_2, 0.0_4_6_8, 0.0_4_0_8, 0.0_3_8_3, 0.0_4_0_8, 0.0_3_5_4, 0.0_3_8_0, 0.0_3_3_9])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
def UpperCamelCase ( self) -> Dict:
"""simple docstring"""
_lowercase : int = StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base')
_lowercase : Optional[int] = sd_pipe.to(lowerCamelCase)
sd_pipe.set_progress_bar_config(disable=lowerCamelCase)
sd_pipe.set_scheduler('sample_euler')
_lowercase : Any = 'A painting of a squirrel eating a burger'
_lowercase : Any = torch.manual_seed(0)
_lowercase : Union[str, Any] = sd_pipe([prompt], generator=lowerCamelCase, guidance_scale=9.0, num_inference_steps=20, output_type='np')
_lowercase : List[str] = output.images
_lowercase : str = image[0, -3:, -3:, -1]
assert image.shape == (1, 5_12, 5_12, 3)
_lowercase : Tuple = np.array([0.1_2_3_7, 0.1_3_2_0, 0.1_4_3_8, 0.1_3_5_9, 0.1_3_9_0, 0.1_1_3_2, 0.1_2_7_7, 0.1_1_7_5, 0.1_1_1_2])
assert np.abs(image_slice.flatten() - expected_slice).max() < 5E-1
def UpperCamelCase ( self) -> Tuple:
"""simple docstring"""
_lowercase : Any = StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base')
_lowercase : List[str] = sd_pipe.to(lowerCamelCase)
sd_pipe.set_progress_bar_config(disable=lowerCamelCase)
sd_pipe.set_scheduler('sample_dpmpp_2m')
_lowercase : Optional[Any] = 'A painting of a squirrel eating a burger'
_lowercase : Optional[Any] = torch.manual_seed(0)
_lowercase : Union[str, Any] = sd_pipe(
[prompt], generator=lowerCamelCase, guidance_scale=7.5, num_inference_steps=15, output_type='np', use_karras_sigmas=lowerCamelCase, )
_lowercase : List[Any] = output.images
_lowercase : Tuple = image[0, -3:, -3:, -1]
assert image.shape == (1, 5_12, 5_12, 3)
_lowercase : Dict = np.array(
[0.1_1_3_8_1_6_8_9, 0.1_2_1_1_2_9_2_1, 0.1_3_8_9_4_5_7, 0.1_2_5_4_9_6_0_6, 0.1_2_4_4_9_6_4, 0.1_0_8_3_1_5_1_7, 0.1_1_5_6_2_8_6_6, 0.1_0_8_6_7_8_1_6, 0.1_0_4_9_9_0_4_8])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
| 89 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...file_utils import _LazyModule, is_torch_available
from ...utils import OptionalDependencyNotAvailable
_lowerCamelCase = {
'''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''],
'''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase = [
'''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''GPTNeoXJapaneseForCausalLM''',
'''GPTNeoXJapaneseLayer''',
'''GPTNeoXJapaneseModel''',
'''GPTNeoXJapanesePreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig
from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_gpt_neox_japanese import (
GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST,
GPTNeoXJapaneseForCausalLM,
GPTNeoXJapaneseLayer,
GPTNeoXJapaneseModel,
GPTNeoXJapanesePreTrainedModel,
)
else:
import sys
_lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 674 | 0 |
'''simple docstring'''
def _snake_case ( A , A , A ) -> float:
return round(float(moles / volume ) * nfactor )
def _snake_case ( A , A , A ) -> float:
return round(float((moles * 0.0_821 * temperature) / (volume) ) )
def _snake_case ( A , A , A ) -> float:
return round(float((moles * 0.0_821 * temperature) / (pressure) ) )
def _snake_case ( A , A , A ) -> float:
return round(float((pressure * volume) / (0.0_821 * moles) ) )
if __name__ == "__main__":
import doctest
doctest.testmod() | 90 |
"""simple docstring"""
from __future__ import annotations
from typing import Any
class snake_case :
def __init__( self :Optional[Any] , _lowerCamelCase :int ):
__SCREAMING_SNAKE_CASE : int = num_of_nodes
__SCREAMING_SNAKE_CASE : list[list[int]] = []
__SCREAMING_SNAKE_CASE : dict[int, int] = {}
def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ):
self.m_edges.append([u_node, v_node, weight] )
def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ):
if self.m_component[u_node] == u_node:
return u_node
return self.find_component(self.m_component[u_node] )
def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ):
if self.m_component[u_node] != u_node:
for k in self.m_component:
__SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ):
if component_size[u_node] <= component_size[v_node]:
__SCREAMING_SNAKE_CASE : List[Any] = v_node
component_size[v_node] += component_size[u_node]
self.set_component(_lowerCamelCase )
elif component_size[u_node] >= component_size[v_node]:
__SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase )
component_size[u_node] += component_size[v_node]
self.set_component(_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
__SCREAMING_SNAKE_CASE : Optional[int] = []
__SCREAMING_SNAKE_CASE : str = 0
__SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes
# A list of components (initialized to all of the nodes)
for node in range(self.m_num_of_nodes ):
self.m_component.update({node: node} )
component_size.append(1 )
__SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes
while num_of_components > 1:
for edge in self.m_edges:
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge
__SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u]
__SCREAMING_SNAKE_CASE : int = self.m_component[v]
if u_component != v_component:
for component in (u_component, v_component):
if (
minimum_weight_edge[component] == -1
or minimum_weight_edge[component][2] > w
):
__SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w]
for edge in minimum_weight_edge:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge
__SCREAMING_SNAKE_CASE : Tuple = self.m_component[u]
__SCREAMING_SNAKE_CASE : int = self.m_component[v]
if u_component != v_component:
mst_weight += w
self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' )
num_of_components -= 1
__SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes
print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' )
def lowerCAmelCase_ ( ):
'''simple docstring'''
if __name__ == "__main__":
import doctest
doctest.testmod()
| 674 | 0 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_torch_available,
)
_lowercase = {
'''configuration_gpt_bigcode''': ['''GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTBigCodeConfig'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = [
'''GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''GPTBigCodeForSequenceClassification''',
'''GPTBigCodeForTokenClassification''',
'''GPTBigCodeForCausalLM''',
'''GPTBigCodeModel''',
'''GPTBigCodePreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_gpt_bigcode import (
GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST,
GPTBigCodeForCausalLM,
GPTBigCodeForSequenceClassification,
GPTBigCodeForTokenClassification,
GPTBigCodeModel,
GPTBigCodePreTrainedModel,
)
else:
import sys
_lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__) | 91 |
"""simple docstring"""
import argparse
import pickle
import numpy as np
import torch
from torch import nn
from transformers import ReformerConfig, ReformerModelWithLMHead
from transformers.utils import logging
logging.set_verbosity_info()
def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ):
'''simple docstring'''
assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match'''
__SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ )
if bias is not None:
assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match'''
__SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ )
def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] )
__SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] )
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] )
set_param(
torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , )
def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] )
__SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] )
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] )
__SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] )
set_param(
torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , )
def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = weights[0][0][0]
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] )
__SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] )
set_param(
torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , )
# lsh weights + output
__SCREAMING_SNAKE_CASE : Tuple = weights[0][1]
if len(lowercase_ ) < 4:
set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ )
else:
set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ )
# intermediate weighs
__SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2]
# Chunked Feed Forward
if len(lowercase_ ) == 4:
__SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2]
# layernorm 2
__SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] )
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] )
set_param(
torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , )
# intermediate dense
__SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] )
set_param(
torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , )
# intermediate out
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] )
__SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] )
set_param(
torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , )
def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Dict = torch_model.reformer
# word embeds
__SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] )
set_param(
torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , )
if isinstance(weights[3] , lowercase_ ):
__SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings
for emb_idx in range(len(position_embeddings.weights ) ):
__SCREAMING_SNAKE_CASE : Dict = np.asarray(weights[3][emb_idx][0] )
assert (
position_embeddings.weights[emb_idx].shape == emb_weights.shape
), F'''{position_embeddings[emb_idx]} emb does not match'''
__SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) )
__SCREAMING_SNAKE_CASE : List[Any] = weights[5]
assert len(torch_model_reformer.encoder.layers ) * 4 == len(
lowercase_ ), "HF and trax model do not have the same number of layers"
for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)]
set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ )
# output layer norm
__SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] )
set_param(
torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , )
# output embeddings
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] )
__SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] )
set_param(
torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , )
def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ )
print(F'''Building PyTorch model from configuration: {config}''' )
__SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ )
with open(lowercase_ , '''rb''' ) as f:
__SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights''']
set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size )
# Save pytorch-model
print(F'''Save PyTorch model to {pytorch_dump_path}''' )
torch.save(model.state_dict() , lowercase_ )
if __name__ == "__main__":
_lowerCamelCase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--trax_model_pkl_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.'''
)
parser.add_argument(
'''--config_file''',
default=None,
type=str,
required=True,
help=(
'''The config json file corresponding to the pre-trained Reformer model. \n'''
'''This specifies the model architecture.'''
),
)
parser.add_argument(
'''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
)
_lowerCamelCase = parser.parse_args()
convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
| 674 | 0 |
'''simple docstring'''
import numpy as np
from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey
def _lowerCAmelCase ( __magic_name__ : int , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int ) -> np.ndarray:
# prepare kernel
# the kernel size have to be odd
if (ksize % 2) == 0:
lowercase : int =ksize + 1
lowercase : str =np.zeros((ksize, ksize) , dtype=np.floataa )
# each value
for y in range(__magic_name__ ):
for x in range(__magic_name__ ):
# distance from center
lowercase : Optional[Any] =x - ksize // 2
lowercase : List[str] =y - ksize // 2
# degree to radiant
lowercase : Optional[int] =theta / 180 * np.pi
lowercase : Union[str, Any] =np.cos(_theta )
lowercase : Optional[int] =np.sin(_theta )
# get kernel x
lowercase : Tuple =cos_theta * px + sin_theta * py
# get kernel y
lowercase : Dict =-sin_theta * px + cos_theta * py
# fill kernel
lowercase : str =np.exp(
-(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi )
return gabor
if __name__ == "__main__":
import doctest
doctest.testmod()
# read original image
UpperCamelCase_ = imread("""../image_data/lena.jpg""")
# turn image in gray scale value
UpperCamelCase_ = cvtColor(img, COLOR_BGR2GRAY)
# Apply multiple Kernel to detect edges
UpperCamelCase_ = np.zeros(gray.shape[:2])
for theta in [0, 30, 60, 90, 120, 150]:
UpperCamelCase_ = gabor_filter_kernel(10, 8, theta, 10, 0, 0)
out += filteraD(gray, CV_8UC3, kernel_aa)
UpperCamelCase_ = out / out.max() * 255
UpperCamelCase_ = out.astype(np.uinta)
imshow("""Original""", gray)
imshow("""Gabor filter with 20x20 mask and 6 directions""", out)
waitKey(0)
| 92 |
"""simple docstring"""
from typing import Callable, Optional, Union
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_lowerCamelCase = logging.get_logger(__name__)
_lowerCamelCase = {
'''microsoft/xprophetnet-large-wiki100-cased''': (
'''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json'''
),
}
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = '''xlm-prophetnet'''
lowerCamelCase__ = ['''past_key_values''']
lowerCamelCase__ = {
'''num_attention_heads''': '''num_encoder_attention_heads''',
}
def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size
__SCREAMING_SNAKE_CASE : Optional[int] = hidden_size
__SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim
__SCREAMING_SNAKE_CASE : str = num_encoder_layers
__SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads
__SCREAMING_SNAKE_CASE : str = decoder_ffn_dim
__SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers
__SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads
__SCREAMING_SNAKE_CASE : Dict = max_position_embeddings
__SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter)
__SCREAMING_SNAKE_CASE : Any = activation_function
# parameters for xlmprophetnet
__SCREAMING_SNAKE_CASE : List[Any] = ngram
__SCREAMING_SNAKE_CASE : int = num_buckets
__SCREAMING_SNAKE_CASE : List[str] = relative_max_distance
__SCREAMING_SNAKE_CASE : str = disable_ngram_loss
__SCREAMING_SNAKE_CASE : Optional[int] = eps
# 3 Types of Dropout
__SCREAMING_SNAKE_CASE : int = attention_dropout
__SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout
__SCREAMING_SNAKE_CASE : Dict = dropout
__SCREAMING_SNAKE_CASE : Any = use_cache
super().__init__(
pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , )
@property
def SCREAMING_SNAKE_CASE_ ( self :int ):
return self.num_encoder_layers + self.num_decoder_layers
@num_hidden_layers.setter
def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ):
raise NotImplementedError(
'''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and'''
''' `num_decoder_layers`.''' )
| 674 | 0 |
"""simple docstring"""
from __future__ import annotations
def __A (_SCREAMING_SNAKE_CASE ) ->float:
"""simple docstring"""
if not nums:
raise ValueError('List is empty' )
return sum(_SCREAMING_SNAKE_CASE ) / len(_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 93 |
"""simple docstring"""
import ast
import os
import re
import shutil
import tempfile
import unittest
from unittest import mock
import torch
from accelerate.test_utils.examples import compare_against_test
from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow
from accelerate.utils import write_basic_config
# DataLoaders built from `test_samples/MRPC` for quick testing
# Should mock `{script_name}.get_dataloaders` via:
# @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders)
_lowerCamelCase = [
'''cross_validation.py''',
'''gradient_accumulation.py''',
'''local_sgd.py''',
'''multi_process_metrics.py''',
'''memory.py''',
'''automatic_gradient_accumulation.py''',
'''fsdp_with_peak_mem_tracking.py''',
'''deepspeed_with_config_support.py''',
'''megatron_lm_gpt_pretraining.py''',
]
class snake_case ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ):
__SCREAMING_SNAKE_CASE : List[str] = None
__SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) )
__SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' )
for item in os.listdir(_lowerCamelCase ):
if item not in EXCLUDE_EXAMPLES:
__SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase )
if os.path.isfile(_lowerCamelCase ) and ".py" in item_path:
with self.subTest(
tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ):
__SCREAMING_SNAKE_CASE : Tuple = compare_against_test(
os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase )
if special_strings is not None:
for string in special_strings:
__SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' )
self.assertEqual(_lowerCamelCase , '''''' )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase )
self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) )
__SCREAMING_SNAKE_CASE : Optional[int] = [
''' ''' * 1_6 + '''{\n\n''',
''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''',
''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''',
''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''',
''' ''' * 2_0 + '''"epoch": epoch,\n\n''',
''' ''' * 1_6 + '''},\n\n''',
''' ''' * 1_6 + '''step=epoch,\n''',
''' ''' * 1_2,
''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''',
]
self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
@mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} )
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = False
@classmethod
def SCREAMING_SNAKE_CASE_ ( cls :Dict ):
super().setUpClass()
__SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp()
__SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' )
write_basic_config(save_location=cls.configPath )
__SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath]
@classmethod
def SCREAMING_SNAKE_CASE_ ( cls :Dict ):
super().tearDownClass()
shutil.rmtree(cls._tmpdir )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
__SCREAMING_SNAKE_CASE : str = f'''
examples/by_feature/checkpointing.py
--checkpointing_steps epoch
--output_dir {self.tmpdir}
'''.split()
run_command(self._launch_args + testargs )
self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
__SCREAMING_SNAKE_CASE : Optional[Any] = f'''
examples/by_feature/checkpointing.py
--checkpointing_steps 1
--output_dir {self.tmpdir}
'''.split()
__SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs )
self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
__SCREAMING_SNAKE_CASE : Optional[int] = f'''
examples/by_feature/checkpointing.py
--resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )}
'''.split()
__SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase )
self.assertNotIn('''epoch 0:''' , _lowerCamelCase )
self.assertIn('''epoch 1:''' , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Optional[int] = f'''
examples/by_feature/checkpointing.py
--resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )}
'''.split()
__SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase )
if torch.cuda.is_available():
__SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count()
else:
__SCREAMING_SNAKE_CASE : Optional[int] = 1
if num_processes > 1:
self.assertNotIn('''epoch 0:''' , _lowerCamelCase )
self.assertIn('''epoch 1:''' , _lowerCamelCase )
else:
self.assertIn('''epoch 0:''' , _lowerCamelCase )
self.assertIn('''epoch 1:''' , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE : Optional[Any] = '''
examples/by_feature/cross_validation.py
--num_folds 2
'''.split()
with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1]
__SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase )
self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 )
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py''']
run_command(self._launch_args + testargs )
@require_trackers
@mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
with tempfile.TemporaryDirectory() as tmpdir:
__SCREAMING_SNAKE_CASE : int = f'''
examples/by_feature/tracking.py
--with_tracking
--project_dir {tmpdir}
'''.split()
run_command(self._launch_args + testargs )
self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py''']
run_command(self._launch_args + testargs )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
__SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py''']
run_command(self._launch_args + testargs )
| 674 | 0 |
'''simple docstring'''
import json
import os
import shutil
import tempfile
import unittest
import numpy as np
import pytest
from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available
if is_vision_available():
from PIL import Image
from transformers import CLIPSegProcessor, ViTImageProcessor
@require_vision
class UpperCAmelCase_ ( unittest.TestCase ):
"""simple docstring"""
def A__ ( self : Union[str, Any] ) -> Tuple:
'''simple docstring'''
lowercase : Dict =tempfile.mkdtemp()
# fmt: off
lowercase : str =['''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''lo''', '''l</w>''', '''w</w>''', '''r</w>''', '''t</w>''', '''low</w>''', '''er</w>''', '''lowest</w>''', '''newer</w>''', '''wider''', '''<unk>''', '''<|startoftext|>''', '''<|endoftext|>''']
# fmt: on
lowercase : Any =dict(zip(UpperCAmelCase , range(len(UpperCAmelCase ) ) ) )
lowercase : str =['''#version: 0.2''', '''l o''', '''lo w</w>''', '''e r</w>''', '''''']
lowercase : List[Any] ={'''unk_token''': '''<unk>'''}
lowercase : Any =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
lowercase : Dict =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp:
fp.write(json.dumps(UpperCAmelCase ) + '''\n''' )
with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp:
fp.write('''\n'''.join(UpperCAmelCase ) )
lowercase : Dict ={
'''do_resize''': True,
'''size''': 20,
'''do_center_crop''': True,
'''crop_size''': 18,
'''do_normalize''': True,
'''image_mean''': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3],
'''image_std''': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1],
}
lowercase : int =os.path.join(self.tmpdirname , UpperCAmelCase )
with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp:
json.dump(UpperCAmelCase , UpperCAmelCase )
def A__ ( self : Dict , **UpperCAmelCase : List[str] ) -> Union[str, Any]:
'''simple docstring'''
return CLIPTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase )
def A__ ( self : Optional[Any] , **UpperCAmelCase : Tuple ) -> List[Any]:
'''simple docstring'''
return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **UpperCAmelCase )
def A__ ( self : Tuple , **UpperCAmelCase : Dict ) -> int:
'''simple docstring'''
return ViTImageProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase )
def A__ ( self : List[Any] ) -> Any:
'''simple docstring'''
shutil.rmtree(self.tmpdirname )
def A__ ( self : Tuple ) -> Optional[Any]:
'''simple docstring'''
lowercase : Dict =[np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )]
lowercase : str =[Image.fromarray(np.moveaxis(UpperCAmelCase , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def A__ ( self : int ) -> List[Any]:
'''simple docstring'''
lowercase : str =self.get_tokenizer()
lowercase : List[str] =self.get_rust_tokenizer()
lowercase : Union[str, Any] =self.get_image_processor()
lowercase : str =CLIPSegProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase )
processor_slow.save_pretrained(self.tmpdirname )
lowercase : List[Any] =CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=UpperCAmelCase )
lowercase : List[Any] =CLIPSegProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase )
processor_fast.save_pretrained(self.tmpdirname )
lowercase : int =CLIPSegProcessor.from_pretrained(self.tmpdirname )
self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() )
self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() )
self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() )
self.assertIsInstance(processor_slow.tokenizer , UpperCAmelCase )
self.assertIsInstance(processor_fast.tokenizer , UpperCAmelCase )
self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() )
self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() )
self.assertIsInstance(processor_slow.image_processor , UpperCAmelCase )
self.assertIsInstance(processor_fast.image_processor , UpperCAmelCase )
def A__ ( self : Union[str, Any] ) -> int:
'''simple docstring'''
lowercase : Optional[int] =CLIPSegProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
lowercase : Dict =self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' )
lowercase : Dict =self.get_image_processor(do_normalize=UpperCAmelCase , padding_value=1.0 )
lowercase : List[str] =CLIPSegProcessor.from_pretrained(
self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=UpperCAmelCase , padding_value=1.0 )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer , UpperCAmelCase )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , UpperCAmelCase )
def A__ ( self : Tuple ) -> Optional[Any]:
'''simple docstring'''
lowercase : str =self.get_image_processor()
lowercase : Optional[int] =self.get_tokenizer()
lowercase : str =CLIPSegProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase )
lowercase : Union[str, Any] =self.prepare_image_inputs()
lowercase : int =image_processor(UpperCAmelCase , return_tensors='''np''' )
lowercase : Optional[int] =processor(images=UpperCAmelCase , return_tensors='''np''' )
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 )
def A__ ( self : Any ) -> List[Any]:
'''simple docstring'''
lowercase : Optional[int] =self.get_image_processor()
lowercase : Dict =self.get_tokenizer()
lowercase : List[str] =CLIPSegProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase )
lowercase : Any ='''lower newer'''
lowercase : int =processor(text=UpperCAmelCase )
lowercase : str =tokenizer(UpperCAmelCase )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def A__ ( self : List[str] ) -> List[Any]:
'''simple docstring'''
lowercase : Optional[int] =self.get_image_processor()
lowercase : Union[str, Any] =self.get_tokenizer()
lowercase : Any =CLIPSegProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase )
lowercase : Optional[int] ='''lower newer'''
lowercase : Union[str, Any] =self.prepare_image_inputs()
lowercase : Union[str, Any] =processor(text=UpperCAmelCase , images=UpperCAmelCase )
self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''pixel_values'''] )
# test if it raises when no input is passed
with pytest.raises(UpperCAmelCase ):
processor()
def A__ ( self : Optional[int] ) -> Tuple:
'''simple docstring'''
lowercase : int =self.get_image_processor()
lowercase : List[Any] =self.get_tokenizer()
lowercase : List[Any] =CLIPSegProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase )
lowercase : str =self.prepare_image_inputs()
lowercase : int =self.prepare_image_inputs()
lowercase : Union[str, Any] =processor(images=UpperCAmelCase , visual_prompt=UpperCAmelCase )
self.assertListEqual(list(inputs.keys() ) , ['''pixel_values''', '''conditional_pixel_values'''] )
# test if it raises when no input is passed
with pytest.raises(UpperCAmelCase ):
processor()
def A__ ( self : Optional[Any] ) -> Dict:
'''simple docstring'''
lowercase : Dict =self.get_image_processor()
lowercase : Optional[Any] =self.get_tokenizer()
lowercase : Union[str, Any] =CLIPSegProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase )
lowercase : Union[str, Any] =[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
lowercase : Union[str, Any] =processor.batch_decode(UpperCAmelCase )
lowercase : str =tokenizer.batch_decode(UpperCAmelCase )
self.assertListEqual(UpperCAmelCase , UpperCAmelCase )
| 94 |
"""simple docstring"""
import argparse
import logging
import os
import time
import timeit
import datasets
import numpy as np
import pycuda.autoinit # noqa: F401
import pycuda.driver as cuda
import tensorrt as trt
import torch
from absl import logging as absl_logging
from accelerate import Accelerator
from datasets import load_dataset, load_metric
from torch.utils.data import DataLoader
from utils_qa import postprocess_qa_predictions
import transformers
from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed
from transformers.trainer_pt_utils import nested_concat, nested_truncate
_lowerCamelCase = trt.Logger(trt.Logger.WARNING)
_lowerCamelCase = absl_logging.get_absl_logger()
absl_logger.setLevel(logging.WARNING)
_lowerCamelCase = logging.getLogger(__name__)
_lowerCamelCase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--onnx_model_path''',
default=None,
type=str,
required=True,
help='''Path to ONNX model: ''',
)
parser.add_argument(
'''--output_dir''',
default=None,
type=str,
required=True,
help='''The output directory where the model checkpoints and predictions will be written.''',
)
# Other parameters
parser.add_argument(
'''--tokenizer_name''',
default='''''',
type=str,
required=True,
help='''Pretrained tokenizer name or path if not the same as model_name''',
)
parser.add_argument(
'''--version_2_with_negative''',
action='''store_true''',
help='''If true, the SQuAD examples contain some that do not have an answer.''',
)
parser.add_argument(
'''--null_score_diff_threshold''',
type=float,
default=0.0,
help='''If null_score - best_non_null is greater than the threshold predict null.''',
)
parser.add_argument(
'''--max_seq_length''',
default=3_84,
type=int,
help=(
'''The maximum total input sequence length after WordPiece tokenization. Sequences '''
'''longer than this will be truncated, and sequences shorter than this will be padded.'''
),
)
parser.add_argument(
'''--doc_stride''',
default=1_28,
type=int,
help='''When splitting up a long document into chunks, how much stride to take between chunks.''',
)
parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''')
parser.add_argument(
'''--n_best_size''',
default=20,
type=int,
help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''',
)
parser.add_argument(
'''--max_answer_length''',
default=30,
type=int,
help=(
'''The maximum length of an answer that can be generated. This is needed because the start '''
'''and end predictions are not conditioned on one another.'''
),
)
parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''')
parser.add_argument(
'''--dataset_name''',
type=str,
default=None,
required=True,
help='''The name of the dataset to use (via the datasets library).''',
)
parser.add_argument(
'''--dataset_config_name''',
type=str,
default=None,
help='''The configuration name of the dataset to use (via the datasets library).''',
)
parser.add_argument(
'''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.'''
)
parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''')
parser.add_argument(
'''--fp16''',
action='''store_true''',
help='''Whether to use 16-bit (mixed) precision instead of 32-bit''',
)
parser.add_argument(
'''--int8''',
action='''store_true''',
help='''Whether to use INT8''',
)
_lowerCamelCase = parser.parse_args()
if args.tokenizer_name:
_lowerCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True)
else:
raise ValueError(
'''You are instantiating a new tokenizer from scratch. This is not supported by this script.'''
'''You can do it from another script, save it, and load it from here, using --tokenizer_name.'''
)
logger.info('''Training/evaluation parameters %s''', args)
_lowerCamelCase = args.per_device_eval_batch_size
_lowerCamelCase = (args.eval_batch_size, args.max_seq_length)
# TRT Engine properties
_lowerCamelCase = True
_lowerCamelCase = '''temp_engine/bert-fp32.engine'''
if args.fpaa:
_lowerCamelCase = '''temp_engine/bert-fp16.engine'''
if args.inta:
_lowerCamelCase = '''temp_engine/bert-int8.engine'''
# import ONNX file
if not os.path.exists('''temp_engine'''):
os.makedirs('''temp_engine''')
_lowerCamelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser(
network, TRT_LOGGER
) as parser:
with open(args.onnx_model_path, '''rb''') as model:
if not parser.parse(model.read()):
for error in range(parser.num_errors):
print(parser.get_error(error))
# Query input names and shapes from parsed TensorRT network
_lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)]
_lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"]
with builder.create_builder_config() as config:
_lowerCamelCase = 1 << 50
if STRICT_TYPES:
config.set_flag(trt.BuilderFlag.STRICT_TYPES)
if args.fpaa:
config.set_flag(trt.BuilderFlag.FPaa)
if args.inta:
config.set_flag(trt.BuilderFlag.INTa)
_lowerCamelCase = builder.create_optimization_profile()
config.add_optimization_profile(profile)
for i in range(len(input_names)):
profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE)
_lowerCamelCase = builder.build_engine(network, config)
# serialize_engine and store in file (can be directly loaded and deserialized):
with open(engine_name, '''wb''') as f:
f.write(engine.serialize())
def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa )
# Copy inputs
cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase_ )
cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase_ )
cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase_ )
# start time
__SCREAMING_SNAKE_CASE : Tuple = time.time()
# Run inference
context.execute_async(
bindings=[int(lowercase_ ) for d_inp in d_inputs] + [int(lowercase_ ), int(lowercase_ )] , stream_handle=stream.handle )
# Transfer predictions back from GPU
cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ )
cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ )
# Synchronize the stream and take time
stream.synchronize()
# end time
__SCREAMING_SNAKE_CASE : List[str] = time.time()
__SCREAMING_SNAKE_CASE : int = end_time - start_time
__SCREAMING_SNAKE_CASE : int = (h_outputa, h_outputa)
# print(outputs)
return outputs, infer_time
# Initialize the accelerator. We will let the accelerator handle device placement for us in this example.
_lowerCamelCase = Accelerator()
# Make one log on every process with the configuration for debugging.
logging.basicConfig(
format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''',
datefmt='''%m/%d/%Y %H:%M:%S''',
level=logging.INFO,
)
# Setup logging, we only want one process per machine to log things on the screen.
# accelerator.is_local_main_process is only True for one process per machine.
logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR)
if accelerator.is_local_main_process:
datasets.utils.logging.set_verbosity_warning()
transformers.utils.logging.set_verbosity_info()
else:
datasets.utils.logging.set_verbosity_error()
transformers.utils.logging.set_verbosity_error()
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
# (the dataset will be downloaded automatically from the datasets Hub).
#
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
# 'text' is found. You can easily tweak this behavior (see below).
if args.dataset_name is not None:
# Downloading and loading a dataset from the hub.
_lowerCamelCase = load_dataset(args.dataset_name, args.dataset_config_name)
else:
raise ValueError('''Evaluation requires a dataset name''')
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
# Preprocessing the datasets.
# Preprocessing is slighlty different for training and evaluation.
_lowerCamelCase = raw_datasets['''validation'''].column_names
_lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0]
_lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1]
_lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2]
# Padding side determines if we do (question|context) or (context|question).
_lowerCamelCase = tokenizer.padding_side == '''right'''
if args.max_seq_length > tokenizer.model_max_length:
logger.warning(
f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the'
f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.'
)
_lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length)
def lowerCAmelCase_ ( lowercase_ : Tuple ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = [q.lstrip() for q in examples[question_column_name]]
# Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results
# in one example possible giving several features when a context is long, each of those features having a
# context that overlaps a bit the context of the previous feature.
__SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer(
examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=lowercase_ , stride=args.doc_stride , return_overflowing_tokens=lowercase_ , return_offsets_mapping=lowercase_ , padding='''max_length''' , )
# Since one example might give us several features if it has a long context, we need a map from a feature to
# its corresponding example. This key gives us just that.
__SCREAMING_SNAKE_CASE : Optional[int] = tokenized_examples.pop('''overflow_to_sample_mapping''' )
# For evaluation, we will need to convert our predictions to substrings of the context, so we keep the
# corresponding example_id and we will store the offset mappings.
__SCREAMING_SNAKE_CASE : Any = []
for i in range(len(tokenized_examples['''input_ids'''] ) ):
# Grab the sequence corresponding to that example (to know what is the context and what is the question).
__SCREAMING_SNAKE_CASE : int = tokenized_examples.sequence_ids(lowercase_ )
__SCREAMING_SNAKE_CASE : str = 1 if pad_on_right else 0
# One example can give several spans, this is the index of the example containing this span of text.
__SCREAMING_SNAKE_CASE : str = sample_mapping[i]
tokenized_examples["example_id"].append(examples['''id'''][sample_index] )
# Set to None the offset_mapping that are not part of the context so it's easy to determine if a token
# position is part of the context or not.
__SCREAMING_SNAKE_CASE : List[str] = [
(o if sequence_ids[k] == context_index else None)
for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] )
]
return tokenized_examples
_lowerCamelCase = raw_datasets['''validation''']
# Validation Feature Creation
_lowerCamelCase = eval_examples.map(
prepare_validation_features,
batched=True,
num_proc=args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not args.overwrite_cache,
desc='''Running tokenizer on validation dataset''',
)
_lowerCamelCase = default_data_collator
_lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping'''])
_lowerCamelCase = DataLoader(
eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size
)
def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Tuple = postprocess_qa_predictions(
examples=lowercase_ , features=lowercase_ , predictions=lowercase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase_ , )
# Format the result to the format the metric expects.
if args.version_2_with_negative:
__SCREAMING_SNAKE_CASE : Union[str, Any] = [
{'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items()
]
else:
__SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()]
__SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples]
return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ )
_lowerCamelCase = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''')
# Evaluation!
logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path)
with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine(
f.read()
) as engine, engine.create_execution_context() as context:
# setup for TRT inferrence
for i in range(len(input_names)):
context.set_binding_shape(i, INPUT_SHAPE)
assert context.all_binding_shapes_specified
def lowerCAmelCase_ ( lowercase_ : Any ):
'''simple docstring'''
return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize
# Allocate device memory for inputs and outputs.
_lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)]
# Allocate output buffer
_lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa)
_lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa)
_lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes)
_lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes)
# Create a stream in which to copy inputs/outputs and run inference.
_lowerCamelCase = cuda.Stream()
# Evaluation
logger.info('''***** Running Evaluation *****''')
logger.info(f' Num examples = {len(eval_dataset)}')
logger.info(f' Batch size = {args.per_device_eval_batch_size}')
_lowerCamelCase = 0.0
_lowerCamelCase = 0
_lowerCamelCase = timeit.default_timer()
_lowerCamelCase = None
for step, batch in enumerate(eval_dataloader):
_lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream)
total_time += infer_time
niter += 1
_lowerCamelCase , _lowerCamelCase = outputs
_lowerCamelCase = torch.tensor(start_logits)
_lowerCamelCase = torch.tensor(end_logits)
# necessary to pad predictions and labels for being gathered
_lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00)
_lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00)
_lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy())
_lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00)
if all_preds is not None:
_lowerCamelCase = nested_truncate(all_preds, len(eval_dataset))
_lowerCamelCase = timeit.default_timer() - start_time
logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset))
# Inference time from TRT
logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 10_00 / niter))
logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00))
logger.info('''Total Number of Inference = %d''', niter)
_lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds)
_lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids)
logger.info(f'Evaluation metrics: {eval_metric}')
| 674 | 0 |
"""simple docstring"""
import os
import tempfile
import unittest
from pathlib import Path
from transformers import AutoConfig, is_torch_available
from transformers.testing_utils import require_torch, torch_device
if is_torch_available():
from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments
@require_torch
class UpperCamelCase_ (unittest.TestCase ):
def _SCREAMING_SNAKE_CASE ( self : str , lowerCAmelCase_ : Optional[int] ) -> Optional[Any]:
for model_result in results.values():
for batch_size, sequence_length in zip(model_result["bs"] , model_result["ss"] ):
UpperCAmelCase_ : int = model_result["result"][batch_size][sequence_length]
self.assertIsNotNone(lowerCAmelCase_ )
def _SCREAMING_SNAKE_CASE ( self : int ) -> Dict:
UpperCAmelCase_ : List[Any] = "sshleifer/tiny-gpt2"
UpperCAmelCase_ : Any = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=lowerCAmelCase_ , inference=lowerCAmelCase_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=lowerCAmelCase_ , )
UpperCAmelCase_ : int = PyTorchBenchmark(lowerCAmelCase_ )
UpperCAmelCase_ : List[Any] = benchmark.run()
self.check_results_dict_not_empty(results.time_inference_result )
self.check_results_dict_not_empty(results.memory_inference_result )
def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]:
UpperCAmelCase_ : Optional[Any] = "sgugger/tiny-distilbert-classification"
UpperCAmelCase_ : Tuple = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=lowerCAmelCase_ , inference=lowerCAmelCase_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=lowerCAmelCase_ , only_pretrain_model=lowerCAmelCase_ , )
UpperCAmelCase_ : Optional[Any] = PyTorchBenchmark(lowerCAmelCase_ )
UpperCAmelCase_ : Any = benchmark.run()
self.check_results_dict_not_empty(results.time_inference_result )
self.check_results_dict_not_empty(results.memory_inference_result )
def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]:
UpperCAmelCase_ : Optional[Any] = "sshleifer/tiny-gpt2"
UpperCAmelCase_ : List[Any] = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=lowerCAmelCase_ , inference=lowerCAmelCase_ , torchscript=lowerCAmelCase_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=lowerCAmelCase_ , )
UpperCAmelCase_ : List[Any] = PyTorchBenchmark(lowerCAmelCase_ )
UpperCAmelCase_ : Any = benchmark.run()
self.check_results_dict_not_empty(results.time_inference_result )
self.check_results_dict_not_empty(results.memory_inference_result )
@unittest.skipIf(torch_device == "cpu" , "Cant do half precision" )
def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]:
UpperCAmelCase_ : Union[str, Any] = "sshleifer/tiny-gpt2"
UpperCAmelCase_ : Optional[Any] = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=lowerCAmelCase_ , inference=lowerCAmelCase_ , fpaa=lowerCAmelCase_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=lowerCAmelCase_ , )
UpperCAmelCase_ : Optional[int] = PyTorchBenchmark(lowerCAmelCase_ )
UpperCAmelCase_ : Any = benchmark.run()
self.check_results_dict_not_empty(results.time_inference_result )
self.check_results_dict_not_empty(results.memory_inference_result )
def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[str]:
UpperCAmelCase_ : Optional[int] = "sshleifer/tiny-gpt2"
UpperCAmelCase_ : Union[str, Any] = AutoConfig.from_pretrained(lowerCAmelCase_ )
# set architectures equal to `None`
UpperCAmelCase_ : Optional[int] = None
UpperCAmelCase_ : List[Any] = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=lowerCAmelCase_ , inference=lowerCAmelCase_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=lowerCAmelCase_ , )
UpperCAmelCase_ : Any = PyTorchBenchmark(lowerCAmelCase_ , configs=[config] )
UpperCAmelCase_ : List[Any] = benchmark.run()
self.check_results_dict_not_empty(results.time_inference_result )
self.check_results_dict_not_empty(results.memory_inference_result )
def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]:
UpperCAmelCase_ : Union[str, Any] = "sshleifer/tiny-gpt2"
UpperCAmelCase_ : Any = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=lowerCAmelCase_ , inference=lowerCAmelCase_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=lowerCAmelCase_ , )
UpperCAmelCase_ : Dict = PyTorchBenchmark(lowerCAmelCase_ )
UpperCAmelCase_ : str = benchmark.run()
self.check_results_dict_not_empty(results.time_train_result )
self.check_results_dict_not_empty(results.memory_train_result )
@unittest.skipIf(torch_device == "cpu" , "Can't do half precision" )
def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> int:
UpperCAmelCase_ : Any = "sshleifer/tiny-gpt2"
UpperCAmelCase_ : List[str] = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=lowerCAmelCase_ , inference=lowerCAmelCase_ , sequence_lengths=[8] , batch_sizes=[1] , fpaa=lowerCAmelCase_ , multi_process=lowerCAmelCase_ , )
UpperCAmelCase_ : Any = PyTorchBenchmark(lowerCAmelCase_ )
UpperCAmelCase_ : Dict = benchmark.run()
self.check_results_dict_not_empty(results.time_train_result )
self.check_results_dict_not_empty(results.memory_train_result )
def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict:
UpperCAmelCase_ : int = "sshleifer/tiny-gpt2"
UpperCAmelCase_ : str = AutoConfig.from_pretrained(lowerCAmelCase_ )
UpperCAmelCase_ : Optional[int] = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=lowerCAmelCase_ , inference=lowerCAmelCase_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=lowerCAmelCase_ , )
UpperCAmelCase_ : Union[str, Any] = PyTorchBenchmark(lowerCAmelCase_ , configs=[config] )
UpperCAmelCase_ : str = benchmark.run()
self.check_results_dict_not_empty(results.time_inference_result )
self.check_results_dict_not_empty(results.memory_inference_result )
def _SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple:
UpperCAmelCase_ : str = "sshleifer/tinier_bart"
UpperCAmelCase_ : Dict = AutoConfig.from_pretrained(lowerCAmelCase_ )
UpperCAmelCase_ : Tuple = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=lowerCAmelCase_ , inference=lowerCAmelCase_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=lowerCAmelCase_ , )
UpperCAmelCase_ : Union[str, Any] = PyTorchBenchmark(lowerCAmelCase_ , configs=[config] )
UpperCAmelCase_ : int = benchmark.run()
self.check_results_dict_not_empty(results.time_inference_result )
self.check_results_dict_not_empty(results.memory_inference_result )
def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str:
UpperCAmelCase_ : Optional[int] = "sshleifer/tiny-gpt2"
UpperCAmelCase_ : List[str] = AutoConfig.from_pretrained(lowerCAmelCase_ )
UpperCAmelCase_ : Tuple = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=lowerCAmelCase_ , inference=lowerCAmelCase_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=lowerCAmelCase_ , )
UpperCAmelCase_ : str = PyTorchBenchmark(lowerCAmelCase_ , configs=[config] )
UpperCAmelCase_ : List[Any] = benchmark.run()
self.check_results_dict_not_empty(results.time_train_result )
self.check_results_dict_not_empty(results.memory_train_result )
def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]:
UpperCAmelCase_ : Any = "sshleifer/tinier_bart"
UpperCAmelCase_ : Tuple = AutoConfig.from_pretrained(lowerCAmelCase_ )
UpperCAmelCase_ : Optional[int] = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=lowerCAmelCase_ , inference=lowerCAmelCase_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=lowerCAmelCase_ , )
UpperCAmelCase_ : Optional[Any] = PyTorchBenchmark(lowerCAmelCase_ , configs=[config] )
UpperCAmelCase_ : List[str] = benchmark.run()
self.check_results_dict_not_empty(results.time_train_result )
self.check_results_dict_not_empty(results.memory_train_result )
def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Union[str, Any]:
UpperCAmelCase_ : List[Any] = "sshleifer/tiny-gpt2"
with tempfile.TemporaryDirectory() as tmp_dir:
UpperCAmelCase_ : Any = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=lowerCAmelCase_ , inference=lowerCAmelCase_ , save_to_csv=lowerCAmelCase_ , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(lowerCAmelCase_ , "inf_time.csv" ) , train_memory_csv_file=os.path.join(lowerCAmelCase_ , "train_mem.csv" ) , inference_memory_csv_file=os.path.join(lowerCAmelCase_ , "inf_mem.csv" ) , train_time_csv_file=os.path.join(lowerCAmelCase_ , "train_time.csv" ) , env_info_csv_file=os.path.join(lowerCAmelCase_ , "env.csv" ) , multi_process=lowerCAmelCase_ , )
UpperCAmelCase_ : Dict = PyTorchBenchmark(lowerCAmelCase_ )
benchmark.run()
self.assertTrue(Path(os.path.join(lowerCAmelCase_ , "inf_time.csv" ) ).exists() )
self.assertTrue(Path(os.path.join(lowerCAmelCase_ , "train_time.csv" ) ).exists() )
self.assertTrue(Path(os.path.join(lowerCAmelCase_ , "inf_mem.csv" ) ).exists() )
self.assertTrue(Path(os.path.join(lowerCAmelCase_ , "train_mem.csv" ) ).exists() )
self.assertTrue(Path(os.path.join(lowerCAmelCase_ , "env.csv" ) ).exists() )
def _SCREAMING_SNAKE_CASE ( self : str ) -> Dict:
UpperCAmelCase_ : int = "sshleifer/tiny-gpt2"
def _check_summary_is_not_empty(lowerCAmelCase_ : str ):
self.assertTrue(hasattr(lowerCAmelCase_ , "sequential" ) )
self.assertTrue(hasattr(lowerCAmelCase_ , "cumulative" ) )
self.assertTrue(hasattr(lowerCAmelCase_ , "current" ) )
self.assertTrue(hasattr(lowerCAmelCase_ , "total" ) )
with tempfile.TemporaryDirectory() as tmp_dir:
UpperCAmelCase_ : Any = PyTorchBenchmarkArguments(
models=[MODEL_ID] , training=lowerCAmelCase_ , inference=lowerCAmelCase_ , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(lowerCAmelCase_ , "log.txt" ) , log_print=lowerCAmelCase_ , trace_memory_line_by_line=lowerCAmelCase_ , multi_process=lowerCAmelCase_ , )
UpperCAmelCase_ : List[str] = PyTorchBenchmark(lowerCAmelCase_ )
UpperCAmelCase_ : Optional[int] = benchmark.run()
_check_summary_is_not_empty(result.inference_summary )
_check_summary_is_not_empty(result.train_summary )
self.assertTrue(Path(os.path.join(lowerCAmelCase_ , "log.txt" ) ).exists() )
| 95 |
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import is_tf_available, is_torch_available
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow
if is_tf_available():
from transformers import (
AutoConfig,
BertConfig,
GPTaConfig,
TaConfig,
TFAutoModel,
TFAutoModelForCausalLM,
TFAutoModelForMaskedLM,
TFAutoModelForPreTraining,
TFAutoModelForQuestionAnswering,
TFAutoModelForSeqaSeqLM,
TFAutoModelForSequenceClassification,
TFAutoModelWithLMHead,
TFBertForMaskedLM,
TFBertForPreTraining,
TFBertForQuestionAnswering,
TFBertForSequenceClassification,
TFBertModel,
TFGPTaLMHeadModel,
TFRobertaForMaskedLM,
TFTaForConditionalGeneration,
)
from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST
from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST
from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST
if is_torch_available():
from transformers import (
AutoModel,
AutoModelForCausalLM,
AutoModelForMaskedLM,
AutoModelForPreTraining,
AutoModelForQuestionAnswering,
AutoModelForSeqaSeqLM,
AutoModelForSequenceClassification,
AutoModelWithLMHead,
BertForMaskedLM,
BertForPreTraining,
BertForQuestionAnswering,
BertForSequenceClassification,
BertModel,
GPTaLMHeadModel,
RobertaForMaskedLM,
TaForConditionalGeneration,
)
@is_pt_tf_cross_test
class snake_case ( unittest.TestCase ):
@slow
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
__SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
__SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Any ):
for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :int ):
for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
__SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
__SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
| 674 | 0 |
"""simple docstring"""
import gc
import random
import unittest
import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
EulerAncestralDiscreteScheduler,
LMSDiscreteScheduler,
PNDMScheduler,
StableDiffusionInstructPixaPixPipeline,
UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.utils import floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
from ..pipeline_params import (
IMAGE_TO_IMAGE_IMAGE_PARAMS,
TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin
enable_full_determinism()
class __A ( SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,unittest.TestCase ):
UpperCAmelCase__ = StableDiffusionInstructPixaPixPipeline
UpperCAmelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width", "cross_attention_kwargs"}
UpperCAmelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
UpperCAmelCase__ = IMAGE_TO_IMAGE_IMAGE_PARAMS
UpperCAmelCase__ = IMAGE_TO_IMAGE_IMAGE_PARAMS
def lowerCamelCase__ ( self : str ) -> Optional[int]:
torch.manual_seed(0 )
__magic_name__: str = UNetaDConditionModel(
block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=8 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=3_2 , )
__magic_name__: Union[str, Any] = PNDMScheduler(skip_prk_steps=__snake_case )
torch.manual_seed(0 )
__magic_name__: Union[str, Any] = AutoencoderKL(
block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , )
torch.manual_seed(0 )
__magic_name__: int = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , )
__magic_name__: Optional[int] = CLIPTextModel(__snake_case )
__magic_name__: Union[str, Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" )
__magic_name__: Tuple = {
"""unet""": unet,
"""scheduler""": scheduler,
"""vae""": vae,
"""text_encoder""": text_encoder,
"""tokenizer""": tokenizer,
"""safety_checker""": None,
"""feature_extractor""": None,
}
return components
def lowerCamelCase__ ( self : Optional[Any] , __snake_case : int , __snake_case : List[Any]=0 ) -> Optional[Any]:
__magic_name__: Optional[int] = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__snake_case ) ).to(__snake_case )
__magic_name__: str = image.cpu().permute(0 , 2 , 3 , 1 )[0]
__magic_name__: Any = Image.fromarray(np.uinta(__snake_case ) ).convert("""RGB""" )
if str(__snake_case ).startswith("""mps""" ):
__magic_name__: Optional[Any] = torch.manual_seed(__snake_case )
else:
__magic_name__: str = torch.Generator(device=__snake_case ).manual_seed(__snake_case )
__magic_name__: Optional[int] = {
"""prompt""": """A painting of a squirrel eating a burger""",
"""image""": image,
"""generator""": generator,
"""num_inference_steps""": 2,
"""guidance_scale""": 6.0,
"""image_guidance_scale""": 1,
"""output_type""": """numpy""",
}
return inputs
def lowerCamelCase__ ( self : Any ) -> Tuple:
__magic_name__: int = """cpu""" # ensure determinism for the device-dependent torch.Generator
__magic_name__: List[Any] = self.get_dummy_components()
__magic_name__: int = StableDiffusionInstructPixaPixPipeline(**__snake_case )
__magic_name__: Union[str, Any] = sd_pipe.to(__snake_case )
sd_pipe.set_progress_bar_config(disable=__snake_case )
__magic_name__: List[Any] = self.get_dummy_inputs(__snake_case )
__magic_name__: Tuple = sd_pipe(**__snake_case ).images
__magic_name__: Optional[int] = image[0, -3:, -3:, -1]
assert image.shape == (1, 3_2, 3_2, 3)
__magic_name__: List[Any] = np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
def lowerCamelCase__ ( self : Optional[int] ) -> List[str]:
__magic_name__: Any = """cpu""" # ensure determinism for the device-dependent torch.Generator
__magic_name__: str = self.get_dummy_components()
__magic_name__: Dict = StableDiffusionInstructPixaPixPipeline(**__snake_case )
__magic_name__: str = sd_pipe.to(__snake_case )
sd_pipe.set_progress_bar_config(disable=__snake_case )
__magic_name__: Optional[Any] = self.get_dummy_inputs(__snake_case )
__magic_name__: List[Any] = """french fries"""
__magic_name__: int = sd_pipe(**__snake_case , negative_prompt=__snake_case )
__magic_name__: Dict = output.images
__magic_name__: Any = image[0, -3:, -3:, -1]
assert image.shape == (1, 3_2, 3_2, 3)
__magic_name__: str = np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
def lowerCamelCase__ ( self : Optional[int] ) -> Tuple:
__magic_name__: Union[str, Any] = """cpu""" # ensure determinism for the device-dependent torch.Generator
__magic_name__: int = self.get_dummy_components()
__magic_name__: Dict = StableDiffusionInstructPixaPixPipeline(**__snake_case )
__magic_name__: Dict = sd_pipe.to(__snake_case )
sd_pipe.set_progress_bar_config(disable=__snake_case )
__magic_name__: str = self.get_dummy_inputs(__snake_case )
__magic_name__: List[str] = [inputs["""prompt"""]] * 2
__magic_name__: List[str] = np.array(inputs["""image"""] ).astype(np.floataa ) / 255.0
__magic_name__: Optional[int] = torch.from_numpy(__snake_case ).unsqueeze(0 ).to(__snake_case )
__magic_name__: Tuple = image / 2 + 0.5
__magic_name__: Dict = image.permute(0 , 3 , 1 , 2 )
__magic_name__: List[str] = image.repeat(2 , 1 , 1 , 1 )
__magic_name__: str = sd_pipe(**__snake_case ).images
__magic_name__: List[str] = image[-1, -3:, -3:, -1]
assert image.shape == (2, 3_2, 3_2, 3)
__magic_name__: Optional[int] = np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
def lowerCamelCase__ ( self : Tuple ) -> Optional[int]:
__magic_name__: Union[str, Any] = """cpu""" # ensure determinism for the device-dependent torch.Generator
__magic_name__: Union[str, Any] = self.get_dummy_components()
__magic_name__: Union[str, Any] = EulerAncestralDiscreteScheduler(
beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" )
__magic_name__: Union[str, Any] = StableDiffusionInstructPixaPixPipeline(**__snake_case )
__magic_name__: Optional[int] = sd_pipe.to(__snake_case )
sd_pipe.set_progress_bar_config(disable=__snake_case )
__magic_name__: List[str] = self.get_dummy_inputs(__snake_case )
__magic_name__: Tuple = sd_pipe(**__snake_case ).images
__magic_name__: Any = image[0, -3:, -3:, -1]
__magic_name__: str = [round(__snake_case , 4 ) for x in image_slice.flatten().tolist()]
print(""",""".join([str(__snake_case ) for x in slice] ) )
assert image.shape == (1, 3_2, 3_2, 3)
__magic_name__: Optional[Any] = np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
def lowerCamelCase__ ( self : Dict ) -> Optional[int]:
super().test_inference_batch_single_identical(expected_max_diff=3E-3 )
def lowerCamelCase__ ( self : Optional[Any] ) -> List[str]:
__magic_name__: Tuple = self.get_dummy_components()
__magic_name__: Tuple = StableDiffusionInstructPixaPixPipeline(**__snake_case )
__magic_name__: str = VaeImageProcessor(do_resize=__snake_case , do_normalize=__snake_case )
__magic_name__: Union[str, Any] = pipe.to(__snake_case )
pipe.set_progress_bar_config(disable=__snake_case )
__magic_name__: Union[str, Any] = pipe(**self.get_dummy_inputs_by_type(__snake_case , input_image_type="""pt""" ) )[0]
__magic_name__: Union[str, Any] = components["""vae"""]
__magic_name__: str = self.get_dummy_inputs_by_type(__snake_case , input_image_type="""pt""" )
for image_param in self.image_latents_params:
if image_param in inputs.keys():
__magic_name__: int = vae.encode(inputs[image_param] ).latent_dist.mode()
__magic_name__: Dict = pipe(**__snake_case )[0]
__magic_name__: Optional[Any] = np.abs(out - out_latents_inputs ).max()
self.assertLess(__snake_case , 1E-4 , """passing latents as image input generate different result from passing image""" )
@slow
@require_torch_gpu
class __A ( unittest.TestCase ):
def lowerCamelCase__ ( self : Optional[Any] ) -> Any:
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def lowerCamelCase__ ( self : str , __snake_case : List[str]=0 ) -> Dict:
__magic_name__: Union[str, Any] = torch.manual_seed(__snake_case )
__magic_name__: Optional[int] = load_image(
"""https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg""" )
__magic_name__: Optional[Any] = {
"""prompt""": """turn him into a cyborg""",
"""image""": image,
"""generator""": generator,
"""num_inference_steps""": 3,
"""guidance_scale""": 7.5,
"""image_guidance_scale""": 1.0,
"""output_type""": """numpy""",
}
return inputs
def lowerCamelCase__ ( self : Any ) -> Any:
__magic_name__: str = StableDiffusionInstructPixaPixPipeline.from_pretrained(
"""timbrooks/instruct-pix2pix""" , safety_checker=__snake_case )
pipe.to(__snake_case )
pipe.set_progress_bar_config(disable=__snake_case )
pipe.enable_attention_slicing()
__magic_name__: Optional[Any] = self.get_inputs()
__magic_name__: str = pipe(**__snake_case ).images
__magic_name__: Optional[int] = image[0, -3:, -3:, -1].flatten()
assert image.shape == (1, 5_1_2, 5_1_2, 3)
__magic_name__: Any = np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555] )
assert np.abs(expected_slice - image_slice ).max() < 1E-3
def lowerCamelCase__ ( self : Optional[Any] ) -> int:
__magic_name__: Tuple = StableDiffusionInstructPixaPixPipeline.from_pretrained(
"""timbrooks/instruct-pix2pix""" , safety_checker=__snake_case )
__magic_name__: List[str] = LMSDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.to(__snake_case )
pipe.set_progress_bar_config(disable=__snake_case )
pipe.enable_attention_slicing()
__magic_name__: List[str] = self.get_inputs()
__magic_name__: Dict = pipe(**__snake_case ).images
__magic_name__: str = image[0, -3:, -3:, -1].flatten()
assert image.shape == (1, 5_1_2, 5_1_2, 3)
__magic_name__: Optional[Any] = np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301] )
assert np.abs(expected_slice - image_slice ).max() < 1E-3
def lowerCamelCase__ ( self : Any ) -> List[str]:
__magic_name__: str = StableDiffusionInstructPixaPixPipeline.from_pretrained(
"""timbrooks/instruct-pix2pix""" , safety_checker=__snake_case )
__magic_name__: int = DDIMScheduler.from_config(pipe.scheduler.config )
pipe.to(__snake_case )
pipe.set_progress_bar_config(disable=__snake_case )
pipe.enable_attention_slicing()
__magic_name__: Union[str, Any] = self.get_inputs()
__magic_name__: Any = pipe(**__snake_case ).images
__magic_name__: int = image[0, -3:, -3:, -1].flatten()
assert image.shape == (1, 5_1_2, 5_1_2, 3)
__magic_name__: Optional[Any] = np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753] )
assert np.abs(expected_slice - image_slice ).max() < 1E-3
def lowerCamelCase__ ( self : int ) -> Dict:
__magic_name__: Tuple = 0
def callback_fn(__snake_case : int , __snake_case : int , __snake_case : torch.FloatTensor ) -> None:
__magic_name__: Union[str, Any] = True
nonlocal number_of_steps
number_of_steps += 1
if step == 1:
__magic_name__: List[str] = latents.detach().cpu().numpy()
assert latents.shape == (1, 4, 6_4, 6_4)
__magic_name__: int = latents[0, -3:, -3:, -1]
__magic_name__: Union[str, Any] = np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983] )
assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2
elif step == 2:
__magic_name__: Union[str, Any] = latents.detach().cpu().numpy()
assert latents.shape == (1, 4, 6_4, 6_4)
__magic_name__: str = latents[0, -3:, -3:, -1]
__magic_name__: Optional[Any] = np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115] )
assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2
__magic_name__: Tuple = False
__magic_name__: List[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained(
"""timbrooks/instruct-pix2pix""" , safety_checker=__snake_case , torch_dtype=torch.floataa )
__magic_name__: Union[str, Any] = pipe.to(__snake_case )
pipe.set_progress_bar_config(disable=__snake_case )
pipe.enable_attention_slicing()
__magic_name__: Dict = self.get_inputs()
pipe(**__snake_case , callback=__snake_case , callback_steps=1 )
assert callback_fn.has_been_called
assert number_of_steps == 3
def lowerCamelCase__ ( self : Tuple ) -> int:
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated()
torch.cuda.reset_peak_memory_stats()
__magic_name__: List[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained(
"""timbrooks/instruct-pix2pix""" , safety_checker=__snake_case , torch_dtype=torch.floataa )
__magic_name__: int = pipe.to(__snake_case )
pipe.set_progress_bar_config(disable=__snake_case )
pipe.enable_attention_slicing(1 )
pipe.enable_sequential_cpu_offload()
__magic_name__: Optional[int] = self.get_inputs()
__magic_name__: Any = pipe(**__snake_case )
__magic_name__: List[str] = torch.cuda.max_memory_allocated()
# make sure that less than 2.2 GB is allocated
assert mem_bytes < 2.2 * 1_0**9
def lowerCamelCase__ ( self : str ) -> Optional[int]:
__magic_name__: Optional[int] = self.get_inputs()
# resize to resolution that is divisible by 8 but not 16 or 32
__magic_name__: Any = inputs["""image"""].resize((5_0_4, 5_0_4) )
__magic_name__: List[str] = """timbrooks/instruct-pix2pix"""
__magic_name__: Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained(
__snake_case , safety_checker=__snake_case , )
pipe.to(__snake_case )
pipe.set_progress_bar_config(disable=__snake_case )
pipe.enable_attention_slicing()
__magic_name__: str = pipe(**__snake_case )
__magic_name__: Optional[int] = output.images[0]
__magic_name__: Union[str, Any] = image[2_5_5:2_5_8, 3_8_3:3_8_6, -1]
assert image.shape == (5_0_4, 5_0_4, 3)
__magic_name__: Optional[Any] = np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-3
| 96 |
"""simple docstring"""
import os
import re
import warnings
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
if TYPE_CHECKING:
from ...tokenization_utils_base import TextInput
from ...utils import logging
_lowerCamelCase = logging.get_logger(__name__)
_lowerCamelCase = {'''vocab_file''': '''spiece.model'''}
_lowerCamelCase = {
'''vocab_file''': {
'''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''',
'''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''',
'''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''',
'''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''',
'''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''',
}
}
# TODO(PVP) - this should be removed in Transformers v5
_lowerCamelCase = {
'''t5-small''': 5_12,
'''t5-base''': 5_12,
'''t5-large''': 5_12,
'''t5-3b''': 5_12,
'''t5-11b''': 5_12,
}
_lowerCamelCase = '''▁'''
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = VOCAB_FILES_NAMES
lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP
lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowerCamelCase__ = ['''input_ids''', '''attention_mask''']
def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ):
# Add extra_ids to the special token list
if extra_ids > 0 and additional_special_tokens is None:
__SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )]
elif extra_ids > 0 and additional_special_tokens is not None:
# Check that we have the right number of extra_id special tokens
__SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) )
if extra_tokens != extra_ids:
raise ValueError(
f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are'''
''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids'''
''' tokens''' )
if legacy:
logger.warning_once(
f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to'''
''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' )
__SCREAMING_SNAKE_CASE : Optional[Any] = legacy
__SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , )
__SCREAMING_SNAKE_CASE : Tuple = vocab_file
__SCREAMING_SNAKE_CASE : List[str] = extra_ids
__SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(_lowerCamelCase )
@staticmethod
def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ):
if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes:
__SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path]
if init_max_model_length is not None and init_max_model_length != max_model_length:
return init_max_model_length
elif init_max_model_length is None:
warnings.warn(
'''This tokenizer was incorrectly instantiated with a model max length of'''
f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this'''
''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with'''
''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on'''
f''' {pretrained_model_name_or_path} automatically truncating your input to'''
f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences'''
f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with'''
''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please'''
''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , )
return max_model_length
@property
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
return self.sp_model.get_piece_size() + self._extra_ids
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ):
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase )
# normal case: some special tokens
if token_ids_a is None:
return ([0] * len(_lowerCamelCase )) + [1]
return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1]
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
return list(
set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()]
def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ):
if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id:
warnings.warn(
f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated'''
''' eos tokens being added.''' )
return token_ids
else:
return token_ids + [self.eos_token_id]
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ):
__SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id]
if token_ids_a is None:
return len(token_ids_a + eos ) * [0]
return len(token_ids_a + eos + token_ids_a + eos ) * [0]
def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ):
__SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase )
if token_ids_a is None:
return token_ids_a
else:
__SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase )
return token_ids_a + token_ids_a
def __getstate__( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Any = self.__dict__.copy()
__SCREAMING_SNAKE_CASE : List[str] = None
return state
def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ):
__SCREAMING_SNAKE_CASE : Tuple = d
# for backward compatibility
if not hasattr(self , '''sp_model_kwargs''' ):
__SCREAMING_SNAKE_CASE : Optional[int] = {}
__SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ):
# Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at
# the beginning of the text
if not self.legacy:
__SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' )
return super().tokenize(_lowerCamelCase , **_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ):
if not self.legacy:
__SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase )
if is_first:
__SCREAMING_SNAKE_CASE : str = text[1:]
__SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase )
if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ):
__SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:]
return tokens
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ):
if token.startswith('''<extra_id_''' ):
__SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) )
return self.vocab_size - num - 1
return self.sp_model.piece_to_id(_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ):
if index < self.sp_model.get_piece_size():
__SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase )
else:
__SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>'''
return token
def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ):
__SCREAMING_SNAKE_CASE : str = []
__SCREAMING_SNAKE_CASE : Dict = ''''''
__SCREAMING_SNAKE_CASE : Dict = False
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
if not prev_is_special:
out_string += " "
out_string += self.sp_model.decode(_lowerCamelCase ) + token
__SCREAMING_SNAKE_CASE : List[str] = True
__SCREAMING_SNAKE_CASE : str = []
else:
current_sub_tokens.append(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = False
out_string += self.sp_model.decode(_lowerCamelCase )
return out_string.strip()
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ):
if not os.path.isdir(_lowerCamelCase ):
logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' )
return
__SCREAMING_SNAKE_CASE : List[str] = os.path.join(
_lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , _lowerCamelCase )
elif not os.path.isfile(self.vocab_file ):
with open(_lowerCamelCase , '''wb''' ) as fi:
__SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto()
fi.write(_lowerCamelCase )
return (out_vocab_file,)
| 674 | 0 |
import json
import os
import re
import shutil
import tempfile
import unittest
from typing import Tuple
from transformers import AddedToken, BatchEncoding, ByTaTokenizer
from transformers.utils import cached_property, is_tf_available, is_torch_available
from ...test_tokenization_common import TokenizerTesterMixin
if is_torch_available():
__a = 'pt'
elif is_tf_available():
__a = 'tf'
else:
__a = 'jax'
class lowercase__( UpperCAmelCase , unittest.TestCase ):
"""simple docstring"""
a :List[str] = ByTaTokenizer
a :Optional[int] = False
def _lowercase ( self : List[Any] ) -> int:
super().setUp()
lowercase_ = ByTaTokenizer()
tokenizer.save_pretrained(self.tmpdirname )
@cached_property
def _lowercase ( self : str ) -> Tuple:
return ByTaTokenizer.from_pretrained('''google/byt5-small''' )
def _lowercase ( self : str , **SCREAMING_SNAKE_CASE_ : List[Any] ) -> ByTaTokenizer:
return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ )
def _lowercase ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[str]=False , SCREAMING_SNAKE_CASE_ : Dict=2_0 , SCREAMING_SNAKE_CASE_ : Tuple=5 ) -> Tuple[str, list]:
# XXX The default common tokenizer tests assume that every ID is decodable on its own.
# This assumption is invalid for ByT5 because single bytes might not be
# valid utf-8 (byte 128 for instance).
# Here we're overriding the smallest possible method to provide
# a clean sequence without making the same assumption.
lowercase_ = []
for i in range(len(SCREAMING_SNAKE_CASE_ ) ):
try:
lowercase_ = tokenizer.decode([i] , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_ )
except UnicodeDecodeError:
pass
toks.append((i, tok) )
lowercase_ = list(filter(lambda SCREAMING_SNAKE_CASE_ : re.match(R'''^[ a-zA-Z]+$''' , t[1] ) , SCREAMING_SNAKE_CASE_ ) )
lowercase_ = list(filter(lambda SCREAMING_SNAKE_CASE_ : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) )
if max_length is not None and len(SCREAMING_SNAKE_CASE_ ) > max_length:
lowercase_ = toks[:max_length]
if min_length is not None and len(SCREAMING_SNAKE_CASE_ ) < min_length and len(SCREAMING_SNAKE_CASE_ ) > 0:
while len(SCREAMING_SNAKE_CASE_ ) < min_length:
lowercase_ = toks + toks
# toks_str = [t[1] for t in toks]
lowercase_ = [t[0] for t in toks]
# Ensure consistency
lowercase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_ )
if " " not in output_txt and len(SCREAMING_SNAKE_CASE_ ) > 1:
lowercase_ = (
tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_ )
+ ''' '''
+ tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_ )
)
if with_prefix_space:
lowercase_ = ''' ''' + output_txt
lowercase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ )
return output_txt, output_ids
def _lowercase ( self : Union[str, Any] ) -> Tuple:
lowercase_ = self.ta_base_tokenizer
lowercase_ = tokenizer(['''hi</s>''', '''I went to the gym</s>''', '''</s>'''] )
lowercase_ = tokenizer(['''hi''', '''I went to the gym''', ''''''] )
self.assertListEqual(batch_with_eos_added['''input_ids'''] , batch_without_eos_added['''input_ids'''] )
def _lowercase ( self : Dict ) -> List[Any]:
lowercase_ = self.ta_base_tokenizer
lowercase_ = '''Unicode €.'''
lowercase_ = tokenizer(SCREAMING_SNAKE_CASE_ )
lowercase_ = [8_8, 1_1_3, 1_0_8, 1_0_2, 1_1_4, 1_0_3, 1_0_4, 3_5, 2_2_9, 1_3_3, 1_7_5, 4_9, 1]
self.assertEqual(encoded['''input_ids'''] , SCREAMING_SNAKE_CASE_ )
# decoding
lowercase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ )
self.assertEqual(SCREAMING_SNAKE_CASE_ , '''Unicode €.</s>''' )
lowercase_ = tokenizer('''e è é ê ë''' )
lowercase_ = [1_0_4, 3_5, 1_9_8, 1_7_1, 3_5, 1_9_8, 1_7_2, 3_5, 1_9_8, 1_7_3, 3_5, 1_9_8, 1_7_4, 1]
self.assertEqual(encoded['''input_ids'''] , SCREAMING_SNAKE_CASE_ )
# decoding
lowercase_ = tokenizer.decode(SCREAMING_SNAKE_CASE_ )
self.assertEqual(SCREAMING_SNAKE_CASE_ , '''e è é ê ë</s>''' )
# encode/decode, but with `encode` instead of `__call__`
self.assertEqual(tokenizer.decode(tokenizer.encode('''e è é ê ë''' ) ) , '''e è é ê ë</s>''' )
def _lowercase ( self : int ) -> List[Any]:
lowercase_ = self.ta_base_tokenizer
lowercase_ = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.''']
# fmt: off
lowercase_ = [6_8, 3_5, 1_1_1, 1_1_4, 1_1_3, 1_0_6, 3_5, 1_1_5, 1_0_0, 1_1_7, 1_0_0, 1_0_6, 1_1_7, 1_0_0, 1_1_5, 1_0_7, 3_5, 1_0_5, 1_1_4, 1_1_7, 3_5, 1_1_8, 1_2_0, 1_1_2, 1_1_2, 1_0_0, 1_1_7, 1_0_8, 1_2_5, 1_0_0, 1_1_9, 1_0_8, 1_1_4, 1_1_3, 4_9, 1, 0]
# fmt: on
lowercase_ = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
if FRAMEWORK != "jax":
lowercase_ = list(batch.input_ids.numpy()[0] )
else:
lowercase_ = list(batch.input_ids.tolist()[0] )
self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertEqual((2, 3_7) , batch.input_ids.shape )
self.assertEqual((2, 3_7) , batch.attention_mask.shape )
def _lowercase ( self : int ) -> List[str]:
lowercase_ = self.ta_base_tokenizer
lowercase_ = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.''']
lowercase_ = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ )
# check if input_ids are returned and no decoder_input_ids
self.assertIn('''input_ids''' , SCREAMING_SNAKE_CASE_ )
self.assertIn('''attention_mask''' , SCREAMING_SNAKE_CASE_ )
self.assertNotIn('''decoder_input_ids''' , SCREAMING_SNAKE_CASE_ )
self.assertNotIn('''decoder_attention_mask''' , SCREAMING_SNAKE_CASE_ )
def _lowercase ( self : List[str] ) -> Any:
lowercase_ = self.ta_base_tokenizer
lowercase_ = [
'''Summary of the text.''',
'''Another summary.''',
]
lowercase_ = tokenizer(
text_target=SCREAMING_SNAKE_CASE_ , max_length=3_2 , padding='''max_length''' , truncation=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ )
self.assertEqual(3_2 , targets['''input_ids'''].shape[1] )
def _lowercase ( self : int ) -> Any:
lowercase_ = self.ta_base_tokenizer
lowercase_ = ['''A long paragraph for summarization. </s>''']
lowercase_ = ['''Summary of the text. </s>''']
# fmt: off
lowercase_ = [6_8, 3_5, 1_1_1, 1_1_4, 1_1_3, 1_0_6, 3_5, 1_1_5, 1_0_0, 1_1_7, 1_0_0, 1_0_6, 1_1_7, 1_0_0, 1_1_5, 1_0_7, 3_5, 1_0_5, 1_1_4, 1_1_7, 3_5, 1_1_8, 1_2_0, 1_1_2, 1_1_2, 1_0_0, 1_1_7, 1_0_8, 1_2_5, 1_0_0, 1_1_9, 1_0_8, 1_1_4, 1_1_3, 4_9, 3_5, 1]
lowercase_ = [8_6, 1_2_0, 1_1_2, 1_1_2, 1_0_0, 1_1_7, 1_2_4, 3_5, 1_1_4, 1_0_5, 3_5, 1_1_9, 1_0_7, 1_0_4, 3_5, 1_1_9, 1_0_4, 1_2_3, 1_1_9, 4_9, 3_5, 1]
# fmt: on
lowercase_ = tokenizer(SCREAMING_SNAKE_CASE_ , text_target=SCREAMING_SNAKE_CASE_ )
self.assertEqual(SCREAMING_SNAKE_CASE_ , batch['''input_ids'''][0] )
self.assertEqual(SCREAMING_SNAKE_CASE_ , batch['''labels'''][0] )
def _lowercase ( self : List[str] ) -> Optional[int]:
# safety check on max_len default value so we are sure the test works
lowercase_ = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(f'''{tokenizer.__class__.__name__}''' ):
self.assertNotEqual(tokenizer.model_max_length , 4_2 )
# Now let's start the test
lowercase_ = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(f'''{tokenizer.__class__.__name__}''' ):
# Isolate this from the other tests because we save additional tokens/etc
lowercase_ = tempfile.mkdtemp()
lowercase_ = ''' He is very happy, UNwant\u00E9d,running'''
lowercase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ )
tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ )
lowercase_ = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE_ )
lowercase_ = after_tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ )
self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
shutil.rmtree(SCREAMING_SNAKE_CASE_ )
lowercase_ = self.get_tokenizers(model_max_length=4_2 )
for tokenizer in tokenizers:
with self.subTest(f'''{tokenizer.__class__.__name__}''' ):
# Isolate this from the other tests because we save additional tokens/etc
lowercase_ = tempfile.mkdtemp()
lowercase_ = ''' He is very happy, UNwant\u00E9d,running'''
tokenizer.add_tokens(['''bim''', '''bambam'''] )
lowercase_ = tokenizer.additional_special_tokens
additional_special_tokens.append('''new_additional_special_token''' )
tokenizer.add_special_tokens({'''additional_special_tokens''': additional_special_tokens} )
lowercase_ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ )
tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ )
lowercase_ = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE_ )
lowercase_ = after_tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ )
self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertIn('''new_additional_special_token''' , after_tokenizer.additional_special_tokens )
self.assertEqual(after_tokenizer.model_max_length , 4_2 )
lowercase_ = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE_ , model_max_length=4_3 )
self.assertEqual(tokenizer.model_max_length , 4_3 )
shutil.rmtree(SCREAMING_SNAKE_CASE_ )
def _lowercase ( self : List[Any] ) -> Optional[int]:
lowercase_ = []
if self.test_slow_tokenizer:
tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) )
if self.test_rust_tokenizer:
tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) )
for tokenizer_class, tokenizer_utils in tokenizer_list:
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer_utils.save_pretrained(SCREAMING_SNAKE_CASE_ )
with open(os.path.join(SCREAMING_SNAKE_CASE_ , '''special_tokens_map.json''' ) , encoding='''utf-8''' ) as json_file:
lowercase_ = json.load(SCREAMING_SNAKE_CASE_ )
with open(os.path.join(SCREAMING_SNAKE_CASE_ , '''tokenizer_config.json''' ) , encoding='''utf-8''' ) as json_file:
lowercase_ = json.load(SCREAMING_SNAKE_CASE_ )
lowercase_ = [f'''<extra_id_{i}>''' for i in range(1_2_5 )]
lowercase_ = added_tokens_extra_ids + [
'''an_additional_special_token'''
]
lowercase_ = added_tokens_extra_ids + [
'''an_additional_special_token'''
]
with open(os.path.join(SCREAMING_SNAKE_CASE_ , '''special_tokens_map.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile:
json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
with open(os.path.join(SCREAMING_SNAKE_CASE_ , '''tokenizer_config.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile:
json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
# into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
# "special_tokens_map.json" files
lowercase_ = tokenizer_class.from_pretrained(
SCREAMING_SNAKE_CASE_ , )
self.assertIn(
'''an_additional_special_token''' , tokenizer_without_change_in_init.additional_special_tokens )
# self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab
self.assertEqual(
['''an_additional_special_token'''] , tokenizer_without_change_in_init.convert_ids_to_tokens(
tokenizer_without_change_in_init.convert_tokens_to_ids(['''an_additional_special_token'''] ) ) , )
# Now we test that we can change the value of additional_special_tokens in the from_pretrained
lowercase_ = added_tokens_extra_ids + [AddedToken('''a_new_additional_special_token''' , lstrip=SCREAMING_SNAKE_CASE_ )]
lowercase_ = tokenizer_class.from_pretrained(
SCREAMING_SNAKE_CASE_ , additional_special_tokens=SCREAMING_SNAKE_CASE_ , )
self.assertIn('''a_new_additional_special_token''' , tokenizer.additional_special_tokens )
self.assertEqual(
['''a_new_additional_special_token'''] , tokenizer.convert_ids_to_tokens(
tokenizer.convert_tokens_to_ids(['''a_new_additional_special_token'''] ) ) , )
def _lowercase ( self : Union[str, Any] ) -> Optional[Any]:
lowercase_ = []
if self.test_slow_tokenizer:
tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) )
if self.test_rust_tokenizer:
tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) )
for tokenizer_class, tokenizer_utils in tokenizer_list:
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer_utils.save_pretrained(SCREAMING_SNAKE_CASE_ )
lowercase_ = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertTrue(tokenizer.decode([2_5_5] ) == '''''' )
def _lowercase ( self : List[Any] ) -> Dict:
pass
def _lowercase ( self : Union[str, Any] ) -> Any:
pass
def _lowercase ( self : Optional[Any] ) -> str:
pass
def _lowercase ( self : Optional[int] ) -> Any:
pass
def _lowercase ( self : str ) -> str:
# The default common tokenizer tests uses invalid tokens for ByT5 that can only accept one-character strings
# and special added tokens as tokens
lowercase_ = self.get_tokenizers(fast=SCREAMING_SNAKE_CASE_ , do_lower_case=SCREAMING_SNAKE_CASE_ )
for tokenizer in tokenizers:
with self.subTest(f'''{tokenizer.__class__.__name__}''' ):
lowercase_ = ['''t''', '''h''', '''i''', '''s''', ''' ''', '''i''', '''s''', ''' ''', '''a''', ''' ''', '''t''', '''e''', '''x''', '''t''', '''</s>''']
lowercase_ = tokenizer.convert_tokens_to_string(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
def _lowercase ( self : str ) -> Dict:
lowercase_ = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(f'''{tokenizer.__class__.__name__}''' ):
lowercase_ = [
'''bos_token''',
'''eos_token''',
'''unk_token''',
'''sep_token''',
'''pad_token''',
'''cls_token''',
'''mask_token''',
]
lowercase_ = 0
lowercase_ = tokenizer.convert_ids_to_tokens(
SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ )
for attr in attributes_list:
setattr(SCREAMING_SNAKE_CASE_ , attr + '''_id''' , SCREAMING_SNAKE_CASE_ )
self.assertEqual(getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ )
self.assertEqual(getattr(SCREAMING_SNAKE_CASE_ , attr + '''_id''' ) , SCREAMING_SNAKE_CASE_ )
setattr(SCREAMING_SNAKE_CASE_ , attr + '''_id''' , SCREAMING_SNAKE_CASE_ )
self.assertEqual(getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ )
self.assertEqual(getattr(SCREAMING_SNAKE_CASE_ , attr + '''_id''' ) , SCREAMING_SNAKE_CASE_ )
setattr(SCREAMING_SNAKE_CASE_ , '''additional_special_tokens_ids''' , [] )
self.assertListEqual(getattr(SCREAMING_SNAKE_CASE_ , '''additional_special_tokens''' ) , [] )
self.assertListEqual(getattr(SCREAMING_SNAKE_CASE_ , '''additional_special_tokens_ids''' ) , [] )
setattr(SCREAMING_SNAKE_CASE_ , '''additional_special_tokens_ids''' , [token_id_to_test_setters] )
self.assertListEqual(getattr(SCREAMING_SNAKE_CASE_ , '''additional_special_tokens''' ) , [token_to_test_setters] )
self.assertListEqual(getattr(SCREAMING_SNAKE_CASE_ , '''additional_special_tokens_ids''' ) , [token_id_to_test_setters] )
| 97 |
"""simple docstring"""
import os
import pytest
import yaml
from datasets.features.features import Features, Value
from datasets.info import DatasetInfo, DatasetInfosDict
@pytest.mark.parametrize(
'''files''' , [
['''full:README.md''', '''dataset_infos.json'''],
['''empty:README.md''', '''dataset_infos.json'''],
['''dataset_infos.json'''],
['''full:README.md'''],
] , )
def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' )
if "full:README.md" in files:
with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f:
f.write('''---\ndataset_info:\n dataset_size: 42\n---''' )
if "empty:README.md" in files:
with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f:
f.write('''''' )
# we want to support dataset_infos.json for backward compatibility
if "dataset_infos.json" in files:
with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f:
f.write('''{"default": {"dataset_size": 42}}''' )
__SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ )
assert dataset_infos
assert dataset_infos["default"].dataset_size == 42
@pytest.mark.parametrize(
'''dataset_info''' , [
DatasetInfo(),
DatasetInfo(
description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ),
] , )
def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ )
dataset_info.write_to_directory(lowercase_ )
__SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ )
assert dataset_info == reloaded
assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) )
def lowerCAmelCase_ ( ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Tuple = DatasetInfo(
description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , )
__SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict()
assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML )
for key in DatasetInfo._INCLUDED_INFO_IN_YAML:
assert key in dataset_info_yaml_dict
assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) )
__SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ )
__SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ )
assert dataset_info_yaml_dict == reloaded
def lowerCAmelCase_ ( ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo()
__SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict()
assert dataset_info_yaml_dict == {}
@pytest.mark.parametrize(
'''dataset_infos_dict''' , [
DatasetInfosDict(),
DatasetInfosDict({'''default''': DatasetInfo()} ),
DatasetInfosDict({'''my_config_name''': DatasetInfo()} ),
DatasetInfosDict(
{
'''default''': DatasetInfo(
description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , )
} ),
DatasetInfosDict(
{
'''v1''': DatasetInfo(dataset_size=42 ),
'''v2''': DatasetInfo(dataset_size=1337 ),
} ),
] , )
def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ )
dataset_infos_dict.write_to_directory(lowercase_ )
__SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ )
# the config_name of the dataset_infos_dict take over the attribute
for config_name, dataset_info in dataset_infos_dict.items():
__SCREAMING_SNAKE_CASE : Optional[int] = config_name
# the yaml representation doesn't include fields like description or citation
# so we just test that we can recover what we can from the yaml
__SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() )
assert dataset_infos_dict == reloaded
if dataset_infos_dict:
assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
| 674 | 0 |
'''simple docstring'''
def a__ ( lowercase : int = 10**12 ) -> int:
"""simple docstring"""
_UpperCamelCase = 1
_UpperCamelCase = 0
_UpperCamelCase = 1
_UpperCamelCase = 1
while numerator <= 2 * min_total - 1:
prev_numerator += 2 * numerator
numerator += 2 * prev_numerator
prev_denominator += 2 * denominator
denominator += 2 * prev_denominator
return (denominator + 1) // 2
if __name__ == "__main__":
print(F"""{solution() = }""")
| 98 |
"""simple docstring"""
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 snake_case ( __UpperCAmelCase , __UpperCAmelCase ):
@register_to_config
def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ):
super().__init__()
__SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) )
__SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) )
def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ):
__SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) )
__SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) )
return self
def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ):
__SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std
return embeds
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ):
__SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean
return embeds
| 674 | 0 |
import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import (
SwiftFormerConfig,
SwiftFormerForImageClassification,
ViTImageProcessor,
)
from transformers.utils import logging
logging.set_verbosity_info()
SCREAMING_SNAKE_CASE = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE = torch.device('cpu')
def a ():
__a = """http://images.cocodataset.org/val2017/000000039769.jpg"""
__a = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw )
return im
def a (lowerCAmelCase__ ):
if swiftformer_name == "swiftformer_xs":
return torch.tensor([-2.1_7_0_3E0_0, 2.1_1_0_7E0_0, -2.0_8_1_1E0_0, 8.8_6_8_5E-0_1, 2.4_3_6_0E-0_1] )
elif swiftformer_name == "swiftformer_s":
return torch.tensor([3.9_6_3_6E-0_1, 2.3_4_7_8E-0_1, -1.6_9_6_3E0_0, -1.7_3_8_1E0_0, -8.6_3_3_7E-0_1] )
elif swiftformer_name == "swiftformer_l1":
return torch.tensor([-4.2_7_6_8E-0_1, -4.7_4_2_9E-0_1, -1.0_8_9_7E0_0, -1.0_2_4_8E0_0, 3.5_5_2_3E-0_2] )
elif swiftformer_name == "swiftformer_l3":
return torch.tensor([-2.5_3_3_0E-0_1, 2.4_2_1_1E-0_1, -6.0_1_8_5E-0_1, -8.2_7_8_9E-0_1, -6.0_4_4_6E-0_2] )
def a (lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ):
__a = dct.pop(lowerCAmelCase__ )
__a = val
def a (lowerCAmelCase__ ):
__a = []
for k in state_dict.keys():
__a = k
if ".pwconv" in k:
__a = k_new.replace(""".pwconv""" , """.point_wise_conv""" )
if ".dwconv" in k:
__a = k_new.replace(""".dwconv""" , """.depth_wise_conv""" )
if ".Proj." in k:
__a = k_new.replace(""".Proj.""" , """.proj.""" )
if "patch_embed" in k_new:
__a = k_new.replace("""patch_embed""" , """swiftformer.patch_embed.patch_embedding""" )
if "network" in k_new:
__a = k_new.split(""".""" )
if ls[2].isdigit():
__a = """swiftformer.encoder.network.""" + ls[1] + """.blocks.""" + ls[2] + """.""" + """.""".join(ls[3:] )
else:
__a = k_new.replace("""network""" , """swiftformer.encoder.network""" )
rename_keys.append((k, k_new) )
return rename_keys
@torch.no_grad()
def a (lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ):
__a = SwiftFormerConfig()
# dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size
__a = 1_000
__a = """huggingface/label-files"""
__a = """imagenet-1k-id2label.json"""
__a = json.load(open(hf_hub_download(lowerCAmelCase__ , lowerCAmelCase__ , repo_type="""dataset""" ) , """r""" ) )
__a = {int(lowerCAmelCase__ ): v for k, v in idalabel.items()}
__a = idalabel
__a = {v: k for k, v in idalabel.items()}
# size of the architecture
if swiftformer_name == "swiftformer_xs":
__a = [3, 3, 6, 4]
__a = [48, 56, 112, 220]
elif swiftformer_name == "swiftformer_s":
__a = [3, 3, 9, 6]
__a = [48, 64, 168, 224]
elif swiftformer_name == "swiftformer_l1":
__a = [4, 3, 10, 5]
__a = [48, 96, 192, 384]
elif swiftformer_name == "swiftformer_l3":
__a = [4, 4, 12, 6]
__a = [64, 128, 320, 512]
# load state_dict of original model, remove and rename some keys
if original_ckpt:
if original_ckpt.startswith("""https""" ):
__a = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location="""cpu""" , check_hash=lowerCAmelCase__ )
else:
__a = torch.load(lowerCAmelCase__ , map_location="""cpu""" )
__a = checkpoint
__a = create_rename_keys(lowerCAmelCase__ )
for rename_key_src, rename_key_dest in rename_keys:
rename_key(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
# load HuggingFace model
__a = SwiftFormerForImageClassification(lowerCAmelCase__ ).eval()
hf_model.load_state_dict(lowerCAmelCase__ )
# prepare test inputs
__a = prepare_img()
__a = ViTImageProcessor.from_pretrained("""preprocessor_config""" )
__a = processor(images=lowerCAmelCase__ , return_tensors="""pt""" )
# compare outputs from both models
__a = get_expected_output(lowerCAmelCase__ )
__a = hf_model(inputs["""pixel_values"""] ).logits
assert hf_logits.shape == torch.Size([1, 1_000] )
assert torch.allclose(hf_logits[0, 0:5] , lowerCAmelCase__ , atol=1E-3 )
Path(lowerCAmelCase__ ).mkdir(exist_ok=lowerCAmelCase__ )
print(f'''Saving model {swiftformer_name} to {pytorch_dump_folder_path}''' )
hf_model.save_pretrained(lowerCAmelCase__ )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--swiftformer_name',
default='swiftformer_xs',
choices=['swiftformer_xs', 'swiftformer_s', 'swiftformer_l1', 'swiftformer_l3'],
type=str,
help='Name of the SwiftFormer model you\'d like to convert.',
)
parser.add_argument(
'--pytorch_dump_folder_path',
default='./converted_outputs/',
type=str,
help='Path to the output PyTorch model directory.',
)
parser.add_argument('--original_ckpt', default=None, type=str, help='Path to the original model checkpoint.')
SCREAMING_SNAKE_CASE = parser.parse_args()
convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
| 99 |
"""simple docstring"""
import argparse
import torch
from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert
from transformers.utils import logging
logging.set_verbosity_info()
def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ )
print(F'''Building PyTorch model from configuration: {config}''' )
__SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ )
# Load weights from tf checkpoint
load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ )
# Save pytorch-model
print(F'''Save PyTorch model to {pytorch_dump_path}''' )
torch.save(model.state_dict() , lowercase_ )
if __name__ == "__main__":
_lowerCamelCase = 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(
'''--bert_config_file''',
default=None,
type=str,
required=True,
help=(
'''The config json file corresponding to the pre-trained BERT model. \n'''
'''This specifies the model architecture.'''
),
)
parser.add_argument(
'''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
)
_lowerCamelCase = parser.parse_args()
convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
| 674 | 0 |
# Copyright 2021 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 packaging import version
from .. import __version__
from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD
from .doc import (
add_code_sample_docstrings,
add_end_docstrings,
add_start_docstrings,
add_start_docstrings_to_model_forward,
copy_func,
replace_return_docstrings,
)
from .generic import (
ContextManagers,
ExplicitEnum,
ModelOutput,
PaddingStrategy,
TensorType,
add_model_info_to_auto_map,
cached_property,
can_return_loss,
expand_dims,
find_labels,
flatten_dict,
infer_framework,
is_jax_tensor,
is_numpy_array,
is_tensor,
is_tf_symbolic_tensor,
is_tf_tensor,
is_torch_device,
is_torch_dtype,
is_torch_tensor,
reshape,
squeeze,
strtobool,
tensor_size,
to_numpy,
to_py_obj,
transpose,
working_or_temp_dir,
)
from .hub import (
CLOUDFRONT_DISTRIB_PREFIX,
DISABLE_TELEMETRY,
HF_MODULES_CACHE,
HUGGINGFACE_CO_PREFIX,
HUGGINGFACE_CO_RESOLVE_ENDPOINT,
PYTORCH_PRETRAINED_BERT_CACHE,
PYTORCH_TRANSFORMERS_CACHE,
S3_BUCKET_PREFIX,
TRANSFORMERS_CACHE,
TRANSFORMERS_DYNAMIC_MODULE_NAME,
EntryNotFoundError,
PushToHubMixin,
RepositoryNotFoundError,
RevisionNotFoundError,
cached_file,
default_cache_path,
define_sagemaker_information,
download_url,
extract_commit_hash,
get_cached_models,
get_file_from_repo,
get_full_repo_name,
has_file,
http_user_agent,
is_offline_mode,
is_remote_url,
move_cache,
send_example_telemetry,
try_to_load_from_cache,
)
from .import_utils import (
ENV_VARS_TRUE_AND_AUTO_VALUES,
ENV_VARS_TRUE_VALUES,
TORCH_FX_REQUIRED_VERSION,
USE_JAX,
USE_TF,
USE_TORCH,
DummyObject,
OptionalDependencyNotAvailable,
_LazyModule,
ccl_version,
direct_transformers_import,
get_torch_version,
is_accelerate_available,
is_apex_available,
is_bitsandbytes_available,
is_bsa_available,
is_coloredlogs_available,
is_cython_available,
is_datasets_available,
is_decord_available,
is_detectrona_available,
is_faiss_available,
is_flax_available,
is_ftfy_available,
is_in_notebook,
is_ipex_available,
is_jieba_available,
is_jumanpp_available,
is_kenlm_available,
is_keras_nlp_available,
is_librosa_available,
is_natten_available,
is_ninja_available,
is_onnx_available,
is_openai_available,
is_optimum_available,
is_pandas_available,
is_peft_available,
is_phonemizer_available,
is_protobuf_available,
is_psutil_available,
is_pyanvml_available,
is_pyctcdecode_available,
is_pytesseract_available,
is_pytest_available,
is_pytorch_quantization_available,
is_rjieba_available,
is_sacremoses_available,
is_safetensors_available,
is_sagemaker_dp_enabled,
is_sagemaker_mp_enabled,
is_scipy_available,
is_sentencepiece_available,
is_seqio_available,
is_sklearn_available,
is_soundfile_availble,
is_spacy_available,
is_speech_available,
is_sudachi_available,
is_tensorflow_probability_available,
is_tensorflow_text_available,
is_tfaonnx_available,
is_tf_available,
is_timm_available,
is_tokenizers_available,
is_torch_available,
is_torch_bfaa_available,
is_torch_bfaa_cpu_available,
is_torch_bfaa_gpu_available,
is_torch_compile_available,
is_torch_cuda_available,
is_torch_fx_available,
is_torch_fx_proxy,
is_torch_mps_available,
is_torch_neuroncore_available,
is_torch_tensorrt_fx_available,
is_torch_tfaa_available,
is_torch_tpu_available,
is_torchaudio_available,
is_torchdistx_available,
is_torchdynamo_available,
is_torchvision_available,
is_training_run_on_sagemaker,
is_vision_available,
requires_backends,
torch_only_method,
)
_A : Union[str, Any] = """pytorch_model.bin"""
_A : Optional[int] = """pytorch_model.bin.index.json"""
_A : str = """adapter_config.json"""
_A : Any = """adapter_model.bin"""
_A : Tuple = """adapter_model.safetensors"""
_A : List[Any] = """tf_model.h5"""
_A : Dict = """tf_model.h5.index.json"""
_A : List[Any] = """model.ckpt"""
_A : Optional[Any] = """flax_model.msgpack"""
_A : int = """flax_model.msgpack.index.json"""
_A : Optional[Any] = """model.safetensors"""
_A : str = """model.safetensors.index.json"""
_A : Dict = """config.json"""
_A : int = """preprocessor_config.json"""
_A : Dict = FEATURE_EXTRACTOR_NAME
_A : Union[str, Any] = """generation_config.json"""
_A : Optional[Any] = """modelcard.json"""
_A : List[str] = """▁"""
_A : Any = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility
_A : List[Any] = [
[[0, 1, 0, 1], [1, 0, 0, 1]]
] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too.
_A : Union[str, Any] = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]
_A : str = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]]
def __snake_case ( lowerCAmelCase_ ) -> List[str]:
if version.parse(lowerCAmelCase_ ) < version.parse(lowerCAmelCase_ ):
if "dev" in min_version:
SCREAMING_SNAKE_CASE__ = (
'''This example requires a source install from HuggingFace Transformers (see '''
'''`https://huggingface.co/docs/transformers/installation#install-from-source`),'''
)
else:
SCREAMING_SNAKE_CASE__ = f'''This example requires a minimum version of {min_version},'''
error_message += f''' but the version found is {__version__}.\n'''
raise ImportError(
error_message
+ '''Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other '''
'''versions of HuggingFace Transformers.''' )
| 100 |
"""simple docstring"""
# 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 numpy as np
import torch
from ..models.clipseg import CLIPSegForImageSegmentation
from ..utils import is_vision_available, requires_backends
from .base import PipelineTool
if is_vision_available():
from PIL import Image
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = (
'''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.'''
'''It takes two arguments named `image` which should be the original image, and `label` which should be a text '''
'''describing the elements what should be identified in the segmentation mask. The tool returns the mask.'''
)
lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined'''
lowerCamelCase__ = '''image_segmenter'''
lowerCamelCase__ = CLIPSegForImageSegmentation
lowerCamelCase__ = ['''image''', '''text''']
lowerCamelCase__ = ['''image''']
def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ):
requires_backends(self , ['''vision'''] )
super().__init__(*_lowerCamelCase , **_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ):
return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ):
with torch.no_grad():
__SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits
return logits
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ):
__SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy()
__SCREAMING_SNAKE_CASE : str = 0
__SCREAMING_SNAKE_CASE : str = 1
return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
| 674 | 0 |
import random
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
UNetaDConditionModel,
VideoToVideoSDPipeline,
)
from diffusers.utils import floats_tensor, is_xformers_available, skip_mps
from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device
from ..pipeline_params import (
TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
@skip_mps
class __lowercase (__SCREAMING_SNAKE_CASE , unittest.TestCase ):
"""simple docstring"""
_UpperCAmelCase = VideoToVideoSDPipeline
_UpperCAmelCase = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"""video"""} ) - {"""image""", """width""", """height"""}
_UpperCAmelCase = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"""video"""} ) - {"""image"""}
_UpperCAmelCase = PipelineTesterMixin.required_optional_params - {"""latents"""}
_UpperCAmelCase = False
# No `output_type`.
_UpperCAmelCase = frozenset(
[
"""num_inference_steps""",
"""generator""",
"""latents""",
"""return_dict""",
"""callback""",
"""callback_steps""",
] )
def UpperCamelCase__ ( self ):
"""simple docstring"""
torch.manual_seed(0 )
SCREAMING_SNAKE_CASE_ : Optional[Any] = UNetaDConditionModel(
block_out_channels=(3_2, 6_4, 6_4, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'DownBlock3D') , up_block_types=('UpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D') , cross_attention_dim=3_2 , attention_head_dim=4 , )
SCREAMING_SNAKE_CASE_ : Any = DDIMScheduler(
beta_start=0.00_085 , beta_end=0.012 , beta_schedule='scaled_linear' , clip_sample=lowerCAmelCase__ , set_alpha_to_one=lowerCAmelCase__ , )
torch.manual_seed(0 )
SCREAMING_SNAKE_CASE_ : List[str] = AutoencoderKL(
block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=1_2_8 , )
torch.manual_seed(0 )
SCREAMING_SNAKE_CASE_ : Any = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='gelu' , projection_dim=5_1_2 , )
SCREAMING_SNAKE_CASE_ : List[str] = CLIPTextModel(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : Union[str, Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )
SCREAMING_SNAKE_CASE_ : int = {
'unet': unet,
'scheduler': scheduler,
'vae': vae,
'text_encoder': text_encoder,
'tokenizer': tokenizer,
}
return components
def UpperCamelCase__ ( self , lowerCAmelCase__ , lowerCAmelCase__=0 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : int = floats_tensor((1, 3, 3, 3_2, 3_2) , rng=random.Random(lowerCAmelCase__ ) ).to(lowerCAmelCase__ )
if str(lowerCAmelCase__ ).startswith('mps' ):
SCREAMING_SNAKE_CASE_ : int = torch.manual_seed(lowerCAmelCase__ )
else:
SCREAMING_SNAKE_CASE_ : Any = torch.Generator(device=lowerCAmelCase__ ).manual_seed(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : str = {
'prompt': 'A painting of a squirrel eating a burger',
'video': video,
'generator': generator,
'num_inference_steps': 2,
'guidance_scale': 6.0,
'output_type': 'pt',
}
return inputs
def UpperCamelCase__ ( self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator
SCREAMING_SNAKE_CASE_ : Tuple = self.get_dummy_components()
SCREAMING_SNAKE_CASE_ : Dict = VideoToVideoSDPipeline(**lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : Dict = sd_pipe.to(lowerCAmelCase__ )
sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : Optional[Any] = self.get_dummy_inputs(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : str = 'np'
SCREAMING_SNAKE_CASE_ : Any = sd_pipe(**lowerCAmelCase__ ).frames
SCREAMING_SNAKE_CASE_ : Optional[int] = frames[0][-3:, -3:, -1]
assert frames[0].shape == (3_2, 3_2, 3)
SCREAMING_SNAKE_CASE_ : str = np.array([1_0_6, 1_1_7, 1_1_3, 1_7_4, 1_3_7, 1_1_2, 1_4_8, 1_5_1, 1_3_1] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
@unittest.skipIf(
torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , )
def UpperCamelCase__ ( self ):
"""simple docstring"""
self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=lowerCAmelCase__ , expected_max_diff=5E-3 )
@unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.' )
def UpperCamelCase__ ( self ):
"""simple docstring"""
pass
@unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.' )
def UpperCamelCase__ ( self ):
"""simple docstring"""
pass
@unittest.skip(reason='`num_images_per_prompt` argument is not supported for this pipeline.' )
def UpperCamelCase__ ( self ):
"""simple docstring"""
pass
def UpperCamelCase__ ( self ):
"""simple docstring"""
return super().test_progress_bar()
@slow
@skip_mps
class __lowercase (unittest.TestCase ):
"""simple docstring"""
def UpperCamelCase__ ( self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : List[str] = VideoToVideoSDPipeline.from_pretrained('cerspense/zeroscope_v2_XL' , torch_dtype=torch.floataa )
pipe.enable_model_cpu_offload()
# 10 frames
SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.Generator(device='cpu' ).manual_seed(0 )
SCREAMING_SNAKE_CASE_ : List[str] = torch.randn((1, 1_0, 3, 1_0_2_4, 5_7_6) , generator=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : Dict = video.to('cuda' )
SCREAMING_SNAKE_CASE_ : List[Any] = 'Spiderman is surfing'
SCREAMING_SNAKE_CASE_ : Optional[Any] = pipe(lowerCAmelCase__ , video=lowerCAmelCase__ , generator=lowerCAmelCase__ , num_inference_steps=3 , output_type='pt' ).frames
SCREAMING_SNAKE_CASE_ : str = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] )
assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1E-2
| 101 |
"""simple docstring"""
import json
import os
import shutil
import tempfile
import unittest
import numpy as np
from transformers import BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer
from transformers.testing_utils import require_tokenizers, require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available
if is_vision_available():
from PIL import Image
from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor
@require_tokenizers
@require_vision
class snake_case ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp()
# fmt: off
__SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''']
# fmt: on
__SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer:
vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) )
__SCREAMING_SNAKE_CASE : Optional[int] = {
'''do_resize''': True,
'''size''': {'''height''': 1_8, '''width''': 1_8},
'''do_normalize''': True,
'''image_mean''': [0.5, 0.5, 0.5],
'''image_std''': [0.5, 0.5, 0.5],
}
__SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase )
with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp:
json.dump(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ):
return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ):
return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
shutil.rmtree(self.tmpdirname )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )]
__SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def SCREAMING_SNAKE_CASE_ ( self :int ):
__SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor()
__SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
processor.save_pretrained(self.tmpdirname )
__SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() )
self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) )
self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() )
self.assertIsInstance(processor.image_processor , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
__SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor(
tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
__SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' )
__SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 )
__SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(
self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :int ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor()
__SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs()
__SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' )
__SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''np''' )
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
__SCREAMING_SNAKE_CASE : Any = self.get_image_processor()
__SCREAMING_SNAKE_CASE : Any = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer'''
__SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE : str = self.get_image_processor()
__SCREAMING_SNAKE_CASE : int = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = '''lower newer'''
__SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs()
__SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase )
self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] )
# test if it raises when no input is passed
with self.assertRaises(_lowerCamelCase ):
processor()
def SCREAMING_SNAKE_CASE_ ( self :Any ):
__SCREAMING_SNAKE_CASE : Dict = self.get_image_processor()
__SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
__SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase )
self.assertListEqual(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
__SCREAMING_SNAKE_CASE : str = self.get_image_processor()
__SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = '''lower newer'''
__SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs()
__SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase )
self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
| 674 | 0 |
"""simple docstring"""
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import ViTImageProcessor
class lowercase__ ( unittest.TestCase ):
"""simple docstring"""
def __init__( self , _A , _A=1_3 , _A=3 , _A=2_2_4 , _A=3_0 , _A=4_0_0 , _A=True , _A=None , _A=True , _A=[0.5, 0.5, 0.5] , _A=[0.5, 0.5, 0.5] , ):
'''simple docstring'''
UpperCamelCase : int = size if size is not None else {"""height""": 1_8, """width""": 1_8}
UpperCamelCase : int = parent
UpperCamelCase : Any = batch_size
UpperCamelCase : List[str] = num_channels
UpperCamelCase : List[str] = image_size
UpperCamelCase : Optional[int] = min_resolution
UpperCamelCase : List[str] = max_resolution
UpperCamelCase : List[Any] = do_resize
UpperCamelCase : int = size
UpperCamelCase : Optional[Any] = do_normalize
UpperCamelCase : int = image_mean
UpperCamelCase : int = image_std
def _a ( self ):
'''simple docstring'''
return {
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_normalize": self.do_normalize,
"do_resize": self.do_resize,
"size": self.size,
}
@require_torch
@require_vision
class lowercase__ ( __SCREAMING_SNAKE_CASE , unittest.TestCase ):
"""simple docstring"""
__lowerCAmelCase : str = ViTImageProcessor if is_vision_available() else None
def _a ( self ):
'''simple docstring'''
UpperCamelCase : Dict = EfficientFormerImageProcessorTester(self )
@property
def _a ( self ):
'''simple docstring'''
return self.image_proc_tester.prepare_image_processor_dict()
def _a ( self ):
'''simple docstring'''
UpperCamelCase : List[Any] = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(_A , """image_mean""" ) )
self.assertTrue(hasattr(_A , """image_std""" ) )
self.assertTrue(hasattr(_A , """do_normalize""" ) )
self.assertTrue(hasattr(_A , """do_resize""" ) )
self.assertTrue(hasattr(_A , """size""" ) )
def _a ( self ):
'''simple docstring'''
pass
def _a ( self ):
'''simple docstring'''
UpperCamelCase : Union[str, Any] = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
UpperCamelCase : Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=_A )
for image in image_inputs:
self.assertIsInstance(_A , Image.Image )
# Test not batched input
UpperCamelCase : Optional[int] = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_proc_tester.num_channels,
self.image_proc_tester.size["""height"""],
self.image_proc_tester.size["""width"""],
) , )
# Test batched
UpperCamelCase : Union[str, Any] = image_processor(_A , return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_proc_tester.batch_size,
self.image_proc_tester.num_channels,
self.image_proc_tester.size["""height"""],
self.image_proc_tester.size["""width"""],
) , )
def _a ( self ):
'''simple docstring'''
UpperCamelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
UpperCamelCase : List[Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=_A , numpify=_A )
for image in image_inputs:
self.assertIsInstance(_A , np.ndarray )
# Test not batched input
UpperCamelCase : Any = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_proc_tester.num_channels,
self.image_proc_tester.size["""height"""],
self.image_proc_tester.size["""width"""],
) , )
# Test batched
UpperCamelCase : Tuple = image_processor(_A , return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_proc_tester.batch_size,
self.image_proc_tester.num_channels,
self.image_proc_tester.size["""height"""],
self.image_proc_tester.size["""width"""],
) , )
def _a ( self ):
'''simple docstring'''
UpperCamelCase : Union[str, Any] = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
UpperCamelCase : Union[str, Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=_A , torchify=_A )
for image in image_inputs:
self.assertIsInstance(_A , torch.Tensor )
# Test not batched input
UpperCamelCase : Any = image_processor(image_inputs[0] , return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_proc_tester.num_channels,
self.image_proc_tester.size["""height"""],
self.image_proc_tester.size["""width"""],
) , )
# Test batched
UpperCamelCase : Any = image_processor(_A , return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_proc_tester.batch_size,
self.image_proc_tester.num_channels,
self.image_proc_tester.size["""height"""],
self.image_proc_tester.size["""width"""],
) , )
| 102 |
"""simple docstring"""
import inspect
import unittest
import numpy as np
from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel
if is_vision_available():
from transformers import MaskFormerImageProcessor
if is_vision_available():
from PIL import Image
class snake_case :
def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ):
__SCREAMING_SNAKE_CASE : List[str] = parent
__SCREAMING_SNAKE_CASE : Tuple = batch_size
__SCREAMING_SNAKE_CASE : Optional[Any] = is_training
__SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss
__SCREAMING_SNAKE_CASE : List[str] = num_queries
__SCREAMING_SNAKE_CASE : Optional[int] = num_channels
__SCREAMING_SNAKE_CASE : List[Any] = min_size
__SCREAMING_SNAKE_CASE : int = max_size
__SCREAMING_SNAKE_CASE : Any = num_labels
__SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size
def SCREAMING_SNAKE_CASE_ ( self :Any ):
__SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to(
_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = (
torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5
).float()
__SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long()
__SCREAMING_SNAKE_CASE : str = self.get_config()
return config, pixel_values, pixel_mask, mask_labels, class_labels
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
return MaskFormerConfig.from_backbone_and_decoder_configs(
backbone_config=SwinConfig(
depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig(
decoder_ffn_dim=1_2_8 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , )
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs()
__SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
return config, inputs_dict
def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states
__SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states
__SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states
self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers )
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ):
with torch.no_grad():
__SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
__SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase )
# the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
# encoder and pixel decoder
self.parent.assertEqual(
output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , )
# let's ensure the other two hidden state exists
self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(output.encoder_last_hidden_state is not None )
if output_hidden_states:
self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ):
__SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
def comm_check_on_output(_lowerCamelCase :Optional[Any] ):
# let's still check that all the required stuff is there
self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.encoder_last_hidden_state is not None )
# okay, now we need to check the logits shape
# due to the encoder compression, masks have a //4 spatial size
self.parent.assertEqual(
result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , )
# + 1 for null class
self.parent.assertEqual(
result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) )
with torch.no_grad():
__SCREAMING_SNAKE_CASE : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase )
comm_check_on_output(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Dict = model(
pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase )
comm_check_on_output(_lowerCamelCase )
self.parent.assertTrue(result.loss is not None )
self.parent.assertEqual(result.loss.shape , torch.Size([1] ) )
@require_torch
class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ):
lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
lowerCamelCase__ = (
{'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation}
if is_torch_available()
else {}
)
lowerCamelCase__ = False
lowerCamelCase__ = False
lowerCamelCase__ = False
lowerCamelCase__ = False
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
__SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self )
__SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
self.config_tester.run_common_tests()
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
__SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase )
@unittest.skip(reason='''MaskFormer does not use inputs_embeds''' )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
pass
@unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' )
def SCREAMING_SNAKE_CASE_ ( self :int ):
pass
@unittest.skip(reason='''MaskFormer is not a generative model''' )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
pass
@unittest.skip(reason='''MaskFormer does not use token embeddings''' )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
pass
@require_torch_multi_gpu
@unittest.skip(
reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
pass
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
pass
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__SCREAMING_SNAKE_CASE : Tuple = model_class(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()]
__SCREAMING_SNAKE_CASE : Optional[Any] = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
for model_name in ["facebook/maskformer-swin-small-coco"]:
__SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2
__SCREAMING_SNAKE_CASE : Dict = {
'''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ),
'''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ),
'''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(),
}
__SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase )
self.assertTrue(outputs.loss is not None )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__SCREAMING_SNAKE_CASE : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase )
self.assertTrue(outputs.attentions is not None )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
if not self.model_tester.is_training:
return
# only MaskFormerForInstanceSegmentation has the loss
__SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1]
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs()
__SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase )
model.to(_lowerCamelCase )
model.train()
__SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss
loss.backward()
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# only MaskFormerForInstanceSegmentation has the loss
__SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1]
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs()
__SCREAMING_SNAKE_CASE : Tuple = True
__SCREAMING_SNAKE_CASE : List[str] = True
__SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase )
model.to(_lowerCamelCase )
model.train()
__SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = outputs.encoder_hidden_states[0]
encoder_hidden_states.retain_grad()
__SCREAMING_SNAKE_CASE : str = outputs.pixel_decoder_hidden_states[0]
pixel_decoder_hidden_states.retain_grad()
# we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
__SCREAMING_SNAKE_CASE : Optional[int] = outputs.transformer_decoder_hidden_states[0]
transformer_decoder_hidden_states.retain_grad()
__SCREAMING_SNAKE_CASE : int = outputs.attentions[0]
attentions.retain_grad()
outputs.loss.backward(retain_graph=_lowerCamelCase )
self.assertIsNotNone(encoder_hidden_states.grad )
self.assertIsNotNone(pixel_decoder_hidden_states.grad )
self.assertIsNotNone(transformer_decoder_hidden_states.grad )
self.assertIsNotNone(attentions.grad )
_lowerCamelCase = 1e-4
def lowerCAmelCase_ ( ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_vision
@slow
class snake_case ( unittest.TestCase ):
@cached_property
def SCREAMING_SNAKE_CASE_ ( self :str ):
return (
MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' )
if is_vision_available()
else None
)
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = self.default_image_processor
__SCREAMING_SNAKE_CASE : Tuple = prepare_img()
__SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 )
# check size
self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) )
with torch.no_grad():
__SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor(
[[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase )
self.assertTrue(
torch.allclose(
outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
__SCREAMING_SNAKE_CASE : Any = torch.tensor(
[[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase )
self.assertTrue(
torch.allclose(
outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
__SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(
[[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase )
self.assertTrue(
torch.allclose(
outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
__SCREAMING_SNAKE_CASE : Tuple = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
.to(_lowerCamelCase )
.eval()
)
__SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor
__SCREAMING_SNAKE_CASE : Tuple = prepare_img()
__SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 )
# check size
self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) )
with torch.no_grad():
__SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase )
# masks_queries_logits
__SCREAMING_SNAKE_CASE : Any = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
__SCREAMING_SNAKE_CASE : List[Any] = [
[-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3],
[-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5],
[-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2],
]
__SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
# class_queries_logits
__SCREAMING_SNAKE_CASE : List[Any] = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
__SCREAMING_SNAKE_CASE : List[str] = torch.tensor(
[
[1.65_12e00, -5.25_72e00, -3.35_19e00],
[3.61_69e-02, -5.90_25e00, -2.93_13e00],
[1.07_66e-04, -7.76_30e00, -5.12_63e00],
] ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
def SCREAMING_SNAKE_CASE_ ( self :Any ):
__SCREAMING_SNAKE_CASE : Tuple = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' )
.to(_lowerCamelCase )
.eval()
)
__SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor
__SCREAMING_SNAKE_CASE : str = prepare_img()
__SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 )
# check size
self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) )
with torch.no_grad():
__SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase )
# masks_queries_logits
__SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
__SCREAMING_SNAKE_CASE : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]]
__SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
# class_queries_logits
__SCREAMING_SNAKE_CASE : int = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
__SCREAMING_SNAKE_CASE : List[str] = torch.tensor(
[[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
def SCREAMING_SNAKE_CASE_ ( self :int ):
__SCREAMING_SNAKE_CASE : int = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
.to(_lowerCamelCase )
.eval()
)
__SCREAMING_SNAKE_CASE : Any = self.default_image_processor
__SCREAMING_SNAKE_CASE : int = image_processor(
[np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , )
__SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']]
__SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']]
with torch.no_grad():
__SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase )
self.assertTrue(outputs.loss is not None )
| 674 | 0 |
"""simple docstring"""
import unittest
from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available
from transformers.pipelines import pipeline
from transformers.pipelines.document_question_answering import apply_tesseract
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_detectrona,
require_pytesseract,
require_tf,
require_torch,
require_vision,
slow,
)
from .test_pipelines_common import ANY
if is_vision_available():
from PIL import Image
from transformers.image_utils import load_image
else:
class UpperCAmelCase :
@staticmethod
def __UpperCAmelCase ( *__lowerCamelCase : List[str] , **__lowerCamelCase : Any ):
"""simple docstring"""
pass
def snake_case ( lowerCAmelCase_ ) -> Dict:
return None
# This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace,
# so we can expect it to be available.
snake_case = (
'''https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png'''
)
@is_pipeline_test
@require_torch
@require_vision
class UpperCAmelCase ( unittest.TestCase ):
A__ : Dict = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING
@require_pytesseract
@require_vision
def __UpperCAmelCase ( self : Tuple , __lowerCamelCase : Dict , __lowerCamelCase : List[Any] , __lowerCamelCase : List[Any] ):
"""simple docstring"""
_snake_case = pipeline(
'''document-question-answering''' , model=__lowerCamelCase , tokenizer=__lowerCamelCase , image_processor=__lowerCamelCase )
_snake_case = INVOICE_URL
_snake_case = list(zip(*apply_tesseract(load_image(__lowerCamelCase ) , __lowerCamelCase , '''''' ) ) )
_snake_case = '''What is the placebo?'''
_snake_case = [
{
'''image''': load_image(__lowerCamelCase ),
'''question''': question,
},
{
'''image''': image,
'''question''': question,
},
{
'''image''': image,
'''question''': question,
'''word_boxes''': word_boxes,
},
]
return dqa_pipeline, examples
def __UpperCAmelCase ( self : Union[str, Any] , __lowerCamelCase : Any , __lowerCamelCase : Optional[Any] ):
"""simple docstring"""
_snake_case = dqa_pipeline(__lowerCamelCase , top_k=2 )
self.assertEqual(
__lowerCamelCase , [
[
{'''score''': ANY(__lowerCamelCase ), '''answer''': ANY(__lowerCamelCase ), '''start''': ANY(__lowerCamelCase ), '''end''': ANY(__lowerCamelCase )},
{'''score''': ANY(__lowerCamelCase ), '''answer''': ANY(__lowerCamelCase ), '''start''': ANY(__lowerCamelCase ), '''end''': ANY(__lowerCamelCase )},
]
]
* 3 , )
@require_torch
@require_detectrona
@require_pytesseract
def __UpperCAmelCase ( self : Union[str, Any] ):
"""simple docstring"""
_snake_case = pipeline('''document-question-answering''' , model='''hf-internal-testing/tiny-random-layoutlmv2''' )
_snake_case = INVOICE_URL
_snake_case = '''How many cats are there?'''
_snake_case = [
{'''score''': 0.0_0_0_1, '''answer''': '''oy 2312/2019''', '''start''': 3_8, '''end''': 3_9},
{'''score''': 0.0_0_0_1, '''answer''': '''oy 2312/2019 DUE''', '''start''': 3_8, '''end''': 4_0},
]
_snake_case = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 )
self.assertEqual(nested_simplify(__lowerCamelCase , decimals=4 ) , __lowerCamelCase )
_snake_case = dqa_pipeline({'''image''': image, '''question''': question} , top_k=2 )
self.assertEqual(nested_simplify(__lowerCamelCase , decimals=4 ) , __lowerCamelCase )
# This image does not detect ANY text in it, meaning layoutlmv2 should fail.
# Empty answer probably
_snake_case = '''./tests/fixtures/tests_samples/COCO/000000039769.png'''
_snake_case = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 )
self.assertEqual(__lowerCamelCase , [] )
# We can optionnally pass directly the words and bounding boxes
_snake_case = '''./tests/fixtures/tests_samples/COCO/000000039769.png'''
_snake_case = []
_snake_case = []
_snake_case = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , words=__lowerCamelCase , boxes=__lowerCamelCase , top_k=2 )
self.assertEqual(__lowerCamelCase , [] )
@slow
@require_torch
@require_detectrona
@require_pytesseract
def __UpperCAmelCase ( self : List[str] ):
"""simple docstring"""
_snake_case = pipeline(
'''document-question-answering''' , model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa''' , revision='''9977165''' , )
_snake_case = INVOICE_URL
_snake_case = '''What is the invoice number?'''
_snake_case = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase , decimals=4 ) , [
{'''score''': 0.9_9_4_4, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
{'''score''': 0.0_0_0_9, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
] , )
_snake_case = dqa_pipeline({'''image''': image, '''question''': question} , top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase , decimals=4 ) , [
{'''score''': 0.9_9_4_4, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
{'''score''': 0.0_0_0_9, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
] , )
_snake_case = dqa_pipeline(
[{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}] , top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase , decimals=4 ) , [
[
{'''score''': 0.9_9_4_4, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
{'''score''': 0.0_0_0_9, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
],
]
* 2 , )
@slow
@require_torch
@require_detectrona
@require_pytesseract
def __UpperCAmelCase ( self : str ):
"""simple docstring"""
_snake_case = pipeline(
'''document-question-answering''' , model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa''' , revision='''9977165''' , max_seq_len=5_0 , )
_snake_case = INVOICE_URL
_snake_case = '''What is the invoice number?'''
_snake_case = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase , decimals=4 ) , [
{'''score''': 0.9_9_7_4, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3},
{'''score''': 0.9_9_4_8, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
] , )
_snake_case = dqa_pipeline({'''image''': image, '''question''': question} , top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase , decimals=4 ) , [
{'''score''': 0.9_9_7_4, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3},
{'''score''': 0.9_9_4_8, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
] , )
_snake_case = dqa_pipeline(
[{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}] , top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase , decimals=4 ) , [
[
{'''score''': 0.9_9_7_4, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3},
{'''score''': 0.9_9_4_8, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
]
]
* 2 , )
@slow
@require_torch
@require_pytesseract
@require_vision
def __UpperCAmelCase ( self : int ):
"""simple docstring"""
_snake_case = AutoTokenizer.from_pretrained(
'''impira/layoutlm-document-qa''' , revision='''3dc6de3''' , add_prefix_space=__lowerCamelCase )
_snake_case = pipeline(
'''document-question-answering''' , model='''impira/layoutlm-document-qa''' , tokenizer=__lowerCamelCase , revision='''3dc6de3''' , )
_snake_case = INVOICE_URL
_snake_case = '''What is the invoice number?'''
_snake_case = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase , decimals=4 ) , [
{'''score''': 0.4_2_5_1, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
{'''score''': 0.0_8_1_9, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3},
] , )
_snake_case = dqa_pipeline({'''image''': image, '''question''': question} , top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase , decimals=4 ) , [
{'''score''': 0.4_2_5_1, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
{'''score''': 0.0_8_1_9, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3},
] , )
_snake_case = dqa_pipeline(
[{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}] , top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase , decimals=4 ) , [
[
{'''score''': 0.4_2_5_1, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
{'''score''': 0.0_8_1_9, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3},
]
]
* 2 , )
_snake_case = list(zip(*apply_tesseract(load_image(__lowerCamelCase ) , __lowerCamelCase , '''''' ) ) )
# This model should also work if `image` is set to None
_snake_case = dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question} , top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase , decimals=4 ) , [
{'''score''': 0.4_2_5_1, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
{'''score''': 0.0_8_1_9, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3},
] , )
@slow
@require_torch
@require_pytesseract
@require_vision
def __UpperCAmelCase ( self : List[Any] ):
"""simple docstring"""
_snake_case = AutoTokenizer.from_pretrained(
'''impira/layoutlm-document-qa''' , revision='''3dc6de3''' , add_prefix_space=__lowerCamelCase )
_snake_case = pipeline(
'''document-question-answering''' , model='''impira/layoutlm-document-qa''' , tokenizer=__lowerCamelCase , revision='''3dc6de3''' , max_seq_len=5_0 , )
_snake_case = INVOICE_URL
_snake_case = '''What is the invoice number?'''
_snake_case = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase , decimals=4 ) , [
{'''score''': 0.9_9_9_9, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
{'''score''': 0.9_9_9_8, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
] , )
_snake_case = dqa_pipeline(
[{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}] , top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase , decimals=4 ) , [
[
{'''score''': 0.9_9_9_9, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
{'''score''': 0.9_9_9_8, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
]
]
* 2 , )
_snake_case = list(zip(*apply_tesseract(load_image(__lowerCamelCase ) , __lowerCamelCase , '''''' ) ) )
# This model should also work if `image` is set to None
_snake_case = dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question} , top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase , decimals=4 ) , [
{'''score''': 0.9_9_9_9, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
{'''score''': 0.9_9_9_8, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
] , )
@slow
@require_torch
def __UpperCAmelCase ( self : Union[str, Any] ):
"""simple docstring"""
_snake_case = pipeline(
'''document-question-answering''' , model='''naver-clova-ix/donut-base-finetuned-docvqa''' , tokenizer=AutoTokenizer.from_pretrained('''naver-clova-ix/donut-base-finetuned-docvqa''' ) , feature_extractor='''naver-clova-ix/donut-base-finetuned-docvqa''' , )
_snake_case = INVOICE_URL
_snake_case = '''What is the invoice number?'''
_snake_case = dqa_pipeline(image=__lowerCamelCase , question=__lowerCamelCase , top_k=2 )
self.assertEqual(nested_simplify(__lowerCamelCase , decimals=4 ) , [{'''answer''': '''us-001'''}] )
@require_tf
@unittest.skip('''Document question answering not implemented in TF''' )
def __UpperCAmelCase ( self : List[Any] ):
"""simple docstring"""
pass
| 103 |
"""simple docstring"""
import contextlib
import importlib
import io
import unittest
import transformers
# Try to import everything from transformers to ensure every object can be loaded.
from transformers import * # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available
if is_torch_available():
from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification
if is_tf_available():
from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification
if is_flax_available():
from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification
_lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co
_lowerCamelCase = '''main'''
# Default branch name
_lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'''
# One particular commit (not the top of `main`)
_lowerCamelCase = '''aaaaaaa'''
# This commit does not exist, so we should 404.
_lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684'''
# Sha-1 of config.json on the top of `main`, for checking purposes
_lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'''
@contextlib.contextmanager
def lowerCAmelCase_ ( ):
'''simple docstring'''
print('''Welcome!''' )
yield
print('''Bye!''' )
@contextlib.contextmanager
def lowerCAmelCase_ ( ):
'''simple docstring'''
print('''Bonjour!''' )
yield
print('''Au revoir!''' )
class snake_case ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
# If the spec is missing, importlib would not be able to import the module dynamically.
assert transformers.__spec__ is not None
assert importlib.util.find_spec('''transformers''' ) is not None
class snake_case ( unittest.TestCase ):
@unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO )
def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ):
with ContextManagers([] ):
print('''Transformers are awesome!''' )
# The print statement adds a new line at the end of the output
self.assertEqual(mock_stdout.getvalue() , '''Transformers are awesome!\n''' )
@unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO )
def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ):
with ContextManagers([context_en()] ):
print('''Transformers are awesome!''' )
# The output should be wrapped with an English welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , '''Welcome!\nTransformers are awesome!\nBye!\n''' )
@unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO )
def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ):
with ContextManagers([context_fr(), context_en()] ):
print('''Transformers are awesome!''' )
# The output should be wrapped with an English and French welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , '''Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n''' )
@require_torch
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] )
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] )
self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] )
class snake_case ( __UpperCAmelCase ):
pass
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] )
@require_tf
def SCREAMING_SNAKE_CASE_ ( self :int ):
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] )
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] )
self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] )
class snake_case ( __UpperCAmelCase ):
pass
self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] )
@require_flax
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
# Flax models don't have labels
self.assertEqual(find_labels(_lowerCamelCase ) , [] )
self.assertEqual(find_labels(_lowerCamelCase ) , [] )
self.assertEqual(find_labels(_lowerCamelCase ) , [] )
class snake_case ( __UpperCAmelCase ):
pass
self.assertEqual(find_labels(_lowerCamelCase ) , [] )
| 674 | 0 |
"""simple docstring"""
import io
import math
from typing import Dict, Optional, Union
import numpy as np
from huggingface_hub import hf_hub_download
from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image
from ...image_utils import (
ChannelDimension,
ImageInput,
get_image_size,
infer_channel_dimension_format,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_torch_available, is_vision_available, logging
from ...utils.import_utils import requires_backends
if is_vision_available():
import textwrap
from PIL import Image, ImageDraw, ImageFont
if is_torch_available():
import torch
from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
UpperCamelCase = False
UpperCamelCase = logging.get_logger(__name__)
UpperCamelCase = """ybelkada/fonts"""
def _lowerCamelCase ( ) -> int:
"""simple docstring"""
if is_torch_available() and not is_torch_greater_or_equal_than_1_11:
raise ImportError(
F"""You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use """
"Pix2StructImageProcessor. Please upgrade torch." )
def _lowerCamelCase ( UpperCAmelCase_ : str, UpperCAmelCase_ : Any, UpperCAmelCase_ : Dict ) -> Optional[int]:
"""simple docstring"""
requires_backends(UpperCAmelCase_, ["torch"] )
_check_torch_version()
A__ = image_tensor.unsqueeze(0 )
A__ = torch.nn.functional.unfold(UpperCAmelCase_, (patch_height, patch_width), stride=(patch_height, patch_width) )
A__ = patches.reshape(image_tensor.size(0 ), image_tensor.size(1 ), UpperCAmelCase_, UpperCAmelCase_, -1 )
A__ = patches.permute(0, 4, 2, 3, 1 ).reshape(
image_tensor.size(2 ) // patch_height, image_tensor.size(3 ) // patch_width, image_tensor.size(1 ) * patch_height * patch_width, )
return patches.unsqueeze(0 )
def _lowerCamelCase ( UpperCAmelCase_ : str, UpperCAmelCase_ : int = 36, UpperCAmelCase_ : str = "black", UpperCAmelCase_ : str = "white", UpperCAmelCase_ : int = 5, UpperCAmelCase_ : int = 5, UpperCAmelCase_ : int = 5, UpperCAmelCase_ : int = 5, UpperCAmelCase_ : Optional[bytes] = None, UpperCAmelCase_ : Optional[str] = None, ) -> Image.Image:
"""simple docstring"""
requires_backends(UpperCAmelCase_, "vision" )
# Add new lines so that each line is no more than 80 characters.
A__ = textwrap.TextWrapper(width=80 )
A__ = wrapper.wrap(text=UpperCAmelCase_ )
A__ = "\n".join(UpperCAmelCase_ )
if font_bytes is not None and font_path is None:
A__ = io.BytesIO(UpperCAmelCase_ )
elif font_path is not None:
A__ = font_path
else:
A__ = hf_hub_download(UpperCAmelCase_, "Arial.TTF" )
A__ = ImageFont.truetype(UpperCAmelCase_, encoding="UTF-8", size=UpperCAmelCase_ )
# Use a temporary canvas to determine the width and height in pixels when
# rendering the text.
A__ = ImageDraw.Draw(Image.new("RGB", (1, 1), UpperCAmelCase_ ) )
A__ , A__ , A__ , A__ = temp_draw.textbbox((0, 0), UpperCAmelCase_, UpperCAmelCase_ )
# Create the actual image with a bit of padding around the text.
A__ = text_width + left_padding + right_padding
A__ = text_height + top_padding + bottom_padding
A__ = Image.new("RGB", (image_width, image_height), UpperCAmelCase_ )
A__ = ImageDraw.Draw(UpperCAmelCase_ )
draw.text(xy=(left_padding, top_padding), text=UpperCAmelCase_, fill=UpperCAmelCase_, font=UpperCAmelCase_ )
return image
def _lowerCamelCase ( UpperCAmelCase_ : np.ndarray, UpperCAmelCase_ : str, **UpperCAmelCase_ : Dict ) -> Optional[Any]:
"""simple docstring"""
requires_backends(UpperCAmelCase_, "vision" )
# Convert to PIL image if necessary
A__ = to_pil_image(UpperCAmelCase_ )
A__ = render_text(UpperCAmelCase_, **UpperCAmelCase_ )
A__ = max(header_image.width, image.width )
A__ = int(image.height * (new_width / image.width) )
A__ = int(header_image.height * (new_width / header_image.width) )
A__ = Image.new("RGB", (new_width, new_height + new_header_height), "white" )
new_image.paste(header_image.resize((new_width, new_header_height) ), (0, 0) )
new_image.paste(image.resize((new_width, new_height) ), (0, new_header_height) )
# Convert back to the original framework if necessary
A__ = to_numpy_array(UpperCAmelCase_ )
if infer_channel_dimension_format(UpperCAmelCase_ ) == ChannelDimension.LAST:
A__ = to_channel_dimension_format(UpperCAmelCase_, ChannelDimension.LAST )
return new_image
class UpperCamelCase__ ( _lowerCAmelCase ):
"""simple docstring"""
A__ : int = ["flattened_patches"]
def __init__( self , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 2048 , SCREAMING_SNAKE_CASE__ = False , **SCREAMING_SNAKE_CASE__ , ) -> None:
super().__init__(**SCREAMING_SNAKE_CASE__ )
A__ = patch_size if patch_size is not None else {"height": 16, "width": 16}
A__ = do_normalize
A__ = do_convert_rgb
A__ = max_patches
A__ = is_vqa
def snake_case__ ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> np.ndarray:
requires_backends(self.extract_flattened_patches , "torch" )
_check_torch_version()
# convert to torch
A__ = to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , ChannelDimension.FIRST )
A__ = torch.from_numpy(SCREAMING_SNAKE_CASE__ )
A__ , A__ = patch_size["height"], patch_size["width"]
A__ , A__ = get_image_size(SCREAMING_SNAKE_CASE__ )
# maximize scale s.t.
A__ = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) )
A__ = max(min(math.floor(scale * image_height / patch_height ) , SCREAMING_SNAKE_CASE__ ) , 1 )
A__ = max(min(math.floor(scale * image_width / patch_width ) , SCREAMING_SNAKE_CASE__ ) , 1 )
A__ = max(num_feasible_rows * patch_height , 1 )
A__ = max(num_feasible_cols * patch_width , 1 )
A__ = torch.nn.functional.interpolate(
image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode="bilinear" , align_corners=SCREAMING_SNAKE_CASE__ , antialias=SCREAMING_SNAKE_CASE__ , ).squeeze(0 )
# [1, rows, columns, patch_height * patch_width * image_channels]
A__ = torch_extract_patches(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
A__ = patches.shape
A__ = patches_shape[1]
A__ = patches_shape[2]
A__ = patches_shape[3]
# [rows * columns, patch_height * patch_width * image_channels]
A__ = patches.reshape([rows * columns, depth] )
# [rows * columns, 1]
A__ = torch.arange(SCREAMING_SNAKE_CASE__ ).reshape([rows, 1] ).repeat(1 , SCREAMING_SNAKE_CASE__ ).reshape([rows * columns, 1] )
A__ = torch.arange(SCREAMING_SNAKE_CASE__ ).reshape([1, columns] ).repeat(SCREAMING_SNAKE_CASE__ , 1 ).reshape([rows * columns, 1] )
# Offset by 1 so the ids do not contain zeros, which represent padding.
row_ids += 1
col_ids += 1
# Prepare additional patch features.
# [rows * columns, 1]
A__ = row_ids.to(torch.floataa )
A__ = col_ids.to(torch.floataa )
# [rows * columns, 2 + patch_height * patch_width * image_channels]
A__ = torch.cat([row_ids, col_ids, patches] , -1 )
# [max_patches, 2 + patch_height * patch_width * image_channels]
A__ = torch.nn.functional.pad(SCREAMING_SNAKE_CASE__ , [0, 0, 0, max_patches - (rows * columns)] ).float()
A__ = to_numpy_array(SCREAMING_SNAKE_CASE__ )
return result
def snake_case__ ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ ) -> np.ndarray:
if image.dtype == np.uinta:
A__ = image.astype(np.floataa )
# take mean across the whole `image`
A__ = np.mean(SCREAMING_SNAKE_CASE__ )
A__ = np.std(SCREAMING_SNAKE_CASE__ )
A__ = max(SCREAMING_SNAKE_CASE__ , 1.0 / math.sqrt(np.prod(image.shape ) ) )
return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
def snake_case__ ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ , ) -> ImageInput:
A__ = do_normalize if do_normalize is not None else self.do_normalize
A__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
A__ = patch_size if patch_size is not None else self.patch_size
A__ = max_patches if max_patches is not None else self.max_patches
A__ = self.is_vqa
if kwargs.get("data_format" , SCREAMING_SNAKE_CASE__ ) is not None:
raise ValueError("data_format is not an accepted input as the outputs are " )
A__ = make_list_of_images(SCREAMING_SNAKE_CASE__ )
if not valid_images(SCREAMING_SNAKE_CASE__ ):
raise ValueError(
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
"torch.Tensor, tf.Tensor or jax.ndarray." )
# PIL RGBA images are converted to RGB
if do_convert_rgb:
A__ = [convert_to_rgb(SCREAMING_SNAKE_CASE__ ) for image in images]
# All transformations expect numpy arrays.
A__ = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images]
if is_vqa:
if header_text is None:
raise ValueError("A header text must be provided for VQA models." )
A__ = kwargs.pop("font_bytes" , SCREAMING_SNAKE_CASE__ )
A__ = kwargs.pop("font_path" , SCREAMING_SNAKE_CASE__ )
if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
A__ = [header_text] * len(SCREAMING_SNAKE_CASE__ )
A__ = [
render_header(SCREAMING_SNAKE_CASE__ , header_text[i] , font_bytes=SCREAMING_SNAKE_CASE__ , font_path=SCREAMING_SNAKE_CASE__ )
for i, image in enumerate(SCREAMING_SNAKE_CASE__ )
]
if do_normalize:
A__ = [self.normalize(image=SCREAMING_SNAKE_CASE__ ) for image in images]
# convert to torch tensor and permute
A__ = [
self.extract_flattened_patches(image=SCREAMING_SNAKE_CASE__ , max_patches=SCREAMING_SNAKE_CASE__ , patch_size=SCREAMING_SNAKE_CASE__ )
for image in images
]
# create attention mask in numpy
A__ = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images]
A__ = BatchFeature(
data={"flattened_patches": images, "attention_mask": attention_masks} , tensor_type=SCREAMING_SNAKE_CASE__ )
return encoded_outputs
| 104 |
"""simple docstring"""
import json
import pathlib
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import YolosImageProcessor
class snake_case ( unittest.TestCase ):
def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ):
# by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
__SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3}
__SCREAMING_SNAKE_CASE : List[str] = parent
__SCREAMING_SNAKE_CASE : Dict = batch_size
__SCREAMING_SNAKE_CASE : str = num_channels
__SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution
__SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution
__SCREAMING_SNAKE_CASE : Tuple = do_resize
__SCREAMING_SNAKE_CASE : Union[str, Any] = size
__SCREAMING_SNAKE_CASE : int = do_normalize
__SCREAMING_SNAKE_CASE : List[Any] = image_mean
__SCREAMING_SNAKE_CASE : Tuple = image_std
__SCREAMING_SNAKE_CASE : Dict = do_rescale
__SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor
__SCREAMING_SNAKE_CASE : List[Any] = do_pad
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
return {
"do_resize": self.do_resize,
"size": self.size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_rescale": self.do_rescale,
"rescale_factor": self.rescale_factor,
"do_pad": self.do_pad,
}
def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ):
if not batched:
__SCREAMING_SNAKE_CASE : str = image_inputs[0]
if isinstance(_lowerCamelCase , Image.Image ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size
else:
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2]
if w < h:
__SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w )
__SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge''']
elif w > h:
__SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge''']
__SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h )
else:
__SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge''']
__SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge''']
else:
__SCREAMING_SNAKE_CASE : Optional[Any] = []
for image in image_inputs:
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] )
expected_values.append((expected_height, expected_width) )
__SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0]
__SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1]
return expected_height, expected_width
@require_torch
@require_vision
class snake_case ( __UpperCAmelCase , unittest.TestCase ):
lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
__SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self )
@property
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
return self.image_processor_tester.prepare_image_processor_dict()
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
__SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) )
self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) )
self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) )
self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) )
self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} )
self.assertEqual(image_processor.do_pad , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict(
self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase )
self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} )
self.assertEqual(image_processor.do_pad , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
pass
def SCREAMING_SNAKE_CASE_ ( self :int ):
# Initialize image_processing
__SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
__SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , Image.Image )
# Test not batched input
__SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# Initialize image_processing
__SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
__SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , np.ndarray )
# Test not batched input
__SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def SCREAMING_SNAKE_CASE_ ( self :Any ):
# Initialize image_processing
__SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
__SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , torch.Tensor )
# Test not batched input
__SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
# Initialize image_processings
__SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict )
__SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase )
# create random PyTorch tensors
__SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCamelCase , torch.Tensor )
# Test whether the method "pad" and calling the image processor return the same tensors
__SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' )
__SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' )
self.assertTrue(
torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) )
@slow
def SCREAMING_SNAKE_CASE_ ( self :int ):
# prepare image and target
__SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f:
__SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() )
__SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target}
# encode them
__SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' )
__SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' )
# verify pixel values
__SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] )
self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] )
self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) )
# verify area
__SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) )
# verify boxes
__SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] )
self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) )
# verify image_id
__SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) )
# verify is_crowd
__SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) )
# verify class_labels
__SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) )
# verify orig_size
__SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) )
# verify size
__SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# prepare image, target and masks_path
__SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f:
__SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() )
__SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target}
__SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' )
# encode them
__SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' )
__SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' )
# verify pixel values
__SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] )
self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] )
self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) )
# verify area
__SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) )
# verify boxes
__SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] )
self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) )
# verify image_id
__SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) )
# verify is_crowd
__SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) )
# verify class_labels
__SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) )
# verify masks
__SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3
self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase )
# verify orig_size
__SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) )
# verify size
__SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
| 674 | 0 |
import json
from typing import List, Optional, Tuple
from tokenizers import pre_tokenizers, processors
from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_mvp import MvpTokenizer
UpperCamelCase__ : str = logging.get_logger(__name__)
UpperCamelCase__ : Optional[Any] = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''}
# See all MVP models at https://huggingface.co/models?filter=mvp
UpperCamelCase__ : Optional[int] = {
'''vocab_file''': {
'''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json''',
},
'''added_tokens.json''': {
'''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json''',
},
'''merges_file''': {
'''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt''',
},
'''tokenizer_file''': {
'''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/tokenizer.json''',
},
}
UpperCamelCase__ : Tuple = {
'''RUCAIBox/mvp''': 10_24,
}
class lowerCAmelCase_ ( lowerCamelCase_ ):
__a : Optional[int] = VOCAB_FILES_NAMES
__a : Tuple = PRETRAINED_VOCAB_FILES_MAP
__a : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__a : List[Any] = ["input_ids", "attention_mask"]
__a : Dict = MvpTokenizer
def __init__( self ,snake_case__=None ,snake_case__=None ,snake_case__=None ,snake_case__="replace" ,snake_case__="<s>" ,snake_case__="</s>" ,snake_case__="</s>" ,snake_case__="<s>" ,snake_case__="<unk>" ,snake_case__="<pad>" ,snake_case__="<mask>" ,snake_case__=False ,snake_case__=True ,**snake_case__ ,):
super().__init__(
snake_case__ ,snake_case__ ,tokenizer_file=snake_case__ ,errors=snake_case__ ,bos_token=snake_case__ ,eos_token=snake_case__ ,sep_token=snake_case__ ,cls_token=snake_case__ ,unk_token=snake_case__ ,pad_token=snake_case__ ,mask_token=snake_case__ ,add_prefix_space=snake_case__ ,trim_offsets=snake_case__ ,**snake_case__ ,)
SCREAMING_SNAKE_CASE_ : str = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
if pre_tok_state.get('add_prefix_space' ,snake_case__ ) != add_prefix_space:
SCREAMING_SNAKE_CASE_ : Tuple = getattr(snake_case__ ,pre_tok_state.pop('type' ) )
SCREAMING_SNAKE_CASE_ : Tuple = add_prefix_space
SCREAMING_SNAKE_CASE_ : Union[str, Any] = pre_tok_class(**snake_case__ )
SCREAMING_SNAKE_CASE_ : int = add_prefix_space
# the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
SCREAMING_SNAKE_CASE_ : Optional[int] = 'post_processor'
SCREAMING_SNAKE_CASE_ : str = getattr(self.backend_tokenizer ,snake_case__ ,snake_case__ )
if tokenizer_component_instance:
SCREAMING_SNAKE_CASE_ : Tuple = json.loads(tokenizer_component_instance.__getstate__() )
# The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
if "sep" in state:
SCREAMING_SNAKE_CASE_ : List[str] = tuple(state['sep'] )
if "cls" in state:
SCREAMING_SNAKE_CASE_ : Optional[int] = tuple(state['cls'] )
SCREAMING_SNAKE_CASE_ : List[Any] = False
if state.get('add_prefix_space' ,snake_case__ ) != add_prefix_space:
SCREAMING_SNAKE_CASE_ : Any = add_prefix_space
SCREAMING_SNAKE_CASE_ : str = True
if state.get('trim_offsets' ,snake_case__ ) != trim_offsets:
SCREAMING_SNAKE_CASE_ : Optional[int] = trim_offsets
SCREAMING_SNAKE_CASE_ : str = True
if changes_to_apply:
SCREAMING_SNAKE_CASE_ : Union[str, Any] = getattr(snake_case__ ,state.pop('type' ) )
SCREAMING_SNAKE_CASE_ : Optional[int] = component_class(**snake_case__ )
setattr(self.backend_tokenizer ,snake_case__ ,snake_case__ )
@property
def snake_case ( self ):
if self._mask_token is None:
if self.verbose:
logger.error('Using mask_token, but it is not set yet.' )
return None
return str(self._mask_token )
@mask_token.setter
def snake_case ( self ,snake_case__ ):
SCREAMING_SNAKE_CASE_ : Optional[int] = AddedToken(snake_case__ ,lstrip=snake_case__ ,rstrip=snake_case__ ) if isinstance(snake_case__ ,snake_case__ ) else value
SCREAMING_SNAKE_CASE_ : Tuple = value
def snake_case ( self ,*snake_case__ ,**snake_case__ ):
SCREAMING_SNAKE_CASE_ : Optional[Any] = kwargs.get('is_split_into_words' ,snake_case__ )
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True '
'to use it with pretokenized inputs.' )
return super()._batch_encode_plus(*snake_case__ ,**snake_case__ )
def snake_case ( self ,*snake_case__ ,**snake_case__ ):
SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get('is_split_into_words' ,snake_case__ )
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True '
'to use it with pretokenized inputs.' )
return super()._encode_plus(*snake_case__ ,**snake_case__ )
def snake_case ( self ,snake_case__ ,snake_case__ = None ):
SCREAMING_SNAKE_CASE_ : Optional[Any] = self._tokenizer.model.save(snake_case__ ,name=snake_case__ )
return tuple(snake_case__ )
def snake_case ( self ,snake_case__ ,snake_case__=None ):
SCREAMING_SNAKE_CASE_ : int = [self.bos_token_id] + token_ids_a + [self.eos_token_id]
if token_ids_a is None:
return output
return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]
def snake_case ( self ,snake_case__ ,snake_case__ = None ):
SCREAMING_SNAKE_CASE_ : str = [self.sep_token_id]
SCREAMING_SNAKE_CASE_ : Any = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
| 105 |
"""simple docstring"""
from __future__ import annotations
def lowerCAmelCase_ ( lowercase_ : int ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ )
return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' )
def lowerCAmelCase_ ( ):
'''simple docstring'''
for base_num in range(9999 , 4999 , -1 ):
__SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num
if is_9_pandigital(lowercase_ ):
return candidate
for base_num in range(333 , 99 , -1 ):
__SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num
if is_9_pandigital(lowercase_ ):
return candidate
return None
if __name__ == "__main__":
print(f'{solution() = }')
| 674 | 0 |
import re
import string
from collections import Counter
import sacrebleu
import sacremoses
from packaging import version
import datasets
__snake_case :Optional[Any] ='\n@inproceedings{xu-etal-2016-optimizing,\n title = {Optimizing Statistical Machine Translation for Text Simplification},\n authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris},\n journal = {Transactions of the Association for Computational Linguistics},\n volume = {4},\n year={2016},\n url = {https://www.aclweb.org/anthology/Q16-1029},\n pages = {401--415\n},\n@inproceedings{post-2018-call,\n title = "A Call for Clarity in Reporting {BLEU} Scores",\n author = "Post, Matt",\n booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",\n month = oct,\n year = "2018",\n address = "Belgium, Brussels",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W18-6319",\n pages = "186--191",\n}\n'
__snake_case :str ='\\nWIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU\nIt can be used to evaluate the quality of machine-generated texts.\n'
__snake_case :List[str] ='\nCalculates sari score (between 0 and 100) given a list of source and predicted\nsentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score.\nArgs:\n sources: list of source sentences where each sentence should be a string.\n predictions: list of predicted sentences where each sentence should be a string.\n references: list of lists of reference sentences where each sentence should be a string.\nReturns:\n sari: sari score\n sacrebleu: sacrebleu score\n exact: exact score\n\nExamples:\n >>> sources=["About 95 species are currently accepted ."]\n >>> predictions=["About 95 you now get in ."]\n >>> references=[["About 95 species are currently known ."]]\n >>> wiki_split = datasets.load_metric("wiki_split")\n >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references)\n >>> print(results)\n {\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0}\n'
def lowerCamelCase_ ( lowerCAmelCase__ : Any ) -> Optional[Any]:
'''simple docstring'''
def remove_articles(lowerCAmelCase__ : Union[str, Any] ):
A = re.compile(r'\b(a|an|the)\b' , re.UNICODE )
return re.sub(lowerCAmelCase__ , ' ' , lowerCAmelCase__ )
def white_space_fix(lowerCAmelCase__ : str ):
return " ".join(text.split() )
def remove_punc(lowerCAmelCase__ : List[str] ):
A = set(string.punctuation )
return "".join(ch for ch in text if ch not in exclude )
def lower(lowerCAmelCase__ : Any ):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(lowerCAmelCase__ ) ) ) )
def lowerCamelCase_ ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[Any] ) -> List[str]:
'''simple docstring'''
return int(normalize_answer(lowerCAmelCase__ ) == normalize_answer(lowerCAmelCase__ ) )
def lowerCamelCase_ ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : List[str] ) -> Tuple:
'''simple docstring'''
A = [any(compute_exact(lowerCAmelCase__ , lowerCAmelCase__ ) for ref in refs ) for pred, refs in zip(lowerCAmelCase__ , lowerCAmelCase__ )]
return (sum(lowerCAmelCase__ ) / len(lowerCAmelCase__ )) * 100
def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[Any] ) -> Any:
'''simple docstring'''
A = [rgram for rgrams in rgramslist for rgram in rgrams]
A = Counter(lowerCAmelCase__ )
A = Counter(lowerCAmelCase__ )
A = Counter()
for sgram, scount in sgramcounter.items():
A = scount * numref
A = Counter(lowerCAmelCase__ )
A = Counter()
for cgram, ccount in cgramcounter.items():
A = ccount * numref
# KEEP
A = sgramcounter_rep & cgramcounter_rep
A = keepgramcounter_rep & rgramcounter
A = sgramcounter_rep & rgramcounter
A = 0
A = 0
for keepgram in keepgramcountergood_rep:
keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram]
# Fix an alleged bug [2] in the keep score computation.
# keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram]
keeptmpscorea += keepgramcountergood_rep[keepgram]
# Define 0/0=1 instead of 0 to give higher scores for predictions that match
# a target exactly.
A = 1
A = 1
if len(lowerCAmelCase__ ) > 0:
A = keeptmpscorea / len(lowerCAmelCase__ )
if len(lowerCAmelCase__ ) > 0:
# Fix an alleged bug [2] in the keep score computation.
# keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep)
A = keeptmpscorea / sum(keepgramcounterall_rep.values() )
A = 0
if keepscore_precision > 0 or keepscore_recall > 0:
A = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall)
# DELETION
A = sgramcounter_rep - cgramcounter_rep
A = delgramcounter_rep - rgramcounter
A = sgramcounter_rep - rgramcounter
A = 0
A = 0
for delgram in delgramcountergood_rep:
deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram]
deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram]
# Define 0/0=1 instead of 0 to give higher scores for predictions that match
# a target exactly.
A = 1
if len(lowerCAmelCase__ ) > 0:
A = deltmpscorea / len(lowerCAmelCase__ )
# ADDITION
A = set(lowerCAmelCase__ ) - set(lowerCAmelCase__ )
A = set(lowerCAmelCase__ ) & set(lowerCAmelCase__ )
A = set(lowerCAmelCase__ ) - set(lowerCAmelCase__ )
A = 0
for addgram in addgramcountergood:
addtmpscore += 1
# Define 0/0=1 instead of 0 to give higher scores for predictions that match
# a target exactly.
A = 1
A = 1
if len(lowerCAmelCase__ ) > 0:
A = addtmpscore / len(lowerCAmelCase__ )
if len(lowerCAmelCase__ ) > 0:
A = addtmpscore / len(lowerCAmelCase__ )
A = 0
if addscore_precision > 0 or addscore_recall > 0:
A = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall)
return (keepscore, delscore_precision, addscore)
def lowerCamelCase_ ( lowerCAmelCase__ : Any , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : List[Any] ) -> Tuple:
'''simple docstring'''
A = len(lowerCAmelCase__ )
A = ssent.split(' ' )
A = csent.split(' ' )
A = []
A = []
A = []
A = []
A = []
A = []
A = []
A = []
A = []
A = []
for rsent in rsents:
A = rsent.split(' ' )
A = []
A = []
A = []
ragramslist.append(lowerCAmelCase__ )
for i in range(0 , len(lowerCAmelCase__ ) - 1 ):
if i < len(lowerCAmelCase__ ) - 1:
A = ragrams[i] + ' ' + ragrams[i + 1]
ragrams.append(lowerCAmelCase__ )
if i < len(lowerCAmelCase__ ) - 2:
A = ragrams[i] + ' ' + ragrams[i + 1] + ' ' + ragrams[i + 2]
ragrams.append(lowerCAmelCase__ )
if i < len(lowerCAmelCase__ ) - 3:
A = ragrams[i] + ' ' + ragrams[i + 1] + ' ' + ragrams[i + 2] + ' ' + ragrams[i + 3]
ragrams.append(lowerCAmelCase__ )
ragramslist.append(lowerCAmelCase__ )
ragramslist.append(lowerCAmelCase__ )
ragramslist.append(lowerCAmelCase__ )
for i in range(0 , len(lowerCAmelCase__ ) - 1 ):
if i < len(lowerCAmelCase__ ) - 1:
A = sagrams[i] + ' ' + sagrams[i + 1]
sagrams.append(lowerCAmelCase__ )
if i < len(lowerCAmelCase__ ) - 2:
A = sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2]
sagrams.append(lowerCAmelCase__ )
if i < len(lowerCAmelCase__ ) - 3:
A = sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2] + ' ' + sagrams[i + 3]
sagrams.append(lowerCAmelCase__ )
for i in range(0 , len(lowerCAmelCase__ ) - 1 ):
if i < len(lowerCAmelCase__ ) - 1:
A = cagrams[i] + ' ' + cagrams[i + 1]
cagrams.append(lowerCAmelCase__ )
if i < len(lowerCAmelCase__ ) - 2:
A = cagrams[i] + ' ' + cagrams[i + 1] + ' ' + cagrams[i + 2]
cagrams.append(lowerCAmelCase__ )
if i < len(lowerCAmelCase__ ) - 3:
A = cagrams[i] + ' ' + cagrams[i + 1] + ' ' + cagrams[i + 2] + ' ' + cagrams[i + 3]
cagrams.append(lowerCAmelCase__ )
((A) , (A) , (A)) = SARIngram(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
((A) , (A) , (A)) = SARIngram(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
((A) , (A) , (A)) = SARIngram(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
((A) , (A) , (A)) = SARIngram(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
A = sum([keepascore, keepascore, keepascore, keepascore] ) / 4
A = sum([delascore, delascore, delascore, delascore] ) / 4
A = sum([addascore, addascore, addascore, addascore] ) / 4
A = (avgkeepscore + avgdelscore + avgaddscore) / 3
return finalscore
def lowerCamelCase_ ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : bool = True , lowerCAmelCase__ : str = "13a" , lowerCAmelCase__ : bool = True ) -> Optional[int]:
'''simple docstring'''
if lowercase:
A = sentence.lower()
if tokenizer in ["13a", "intl"]:
if version.parse(sacrebleu.__version__ ).major >= 2:
A = sacrebleu.metrics.bleu._get_tokenizer(lowerCAmelCase__ )()(lowerCAmelCase__ )
else:
A = sacrebleu.TOKENIZERS[tokenizer]()(lowerCAmelCase__ )
elif tokenizer == "moses":
A = sacremoses.MosesTokenizer().tokenize(lowerCAmelCase__ , return_str=lowerCAmelCase__ , escape=lowerCAmelCase__ )
elif tokenizer == "penn":
A = sacremoses.MosesTokenizer().penn_tokenize(lowerCAmelCase__ , return_str=lowerCAmelCase__ )
else:
A = sentence
if not return_str:
A = normalized_sent.split()
return normalized_sent
def lowerCamelCase_ ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[str] ) -> List[Any]:
'''simple docstring'''
if not (len(lowerCAmelCase__ ) == len(lowerCAmelCase__ ) == len(lowerCAmelCase__ )):
raise ValueError('Sources length must match predictions and references lengths.' )
A = 0
for src, pred, refs in zip(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ):
sari_score += SARIsent(normalize(lowerCAmelCase__ ) , normalize(lowerCAmelCase__ ) , [normalize(lowerCAmelCase__ ) for sent in refs] )
A = sari_score / len(lowerCAmelCase__ )
return 100 * sari_score
def lowerCamelCase_ ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : int , lowerCAmelCase__ : str="exp" , lowerCAmelCase__ : Union[str, Any]=None , lowerCAmelCase__ : List[str]=False , lowerCAmelCase__ : Any=False , lowerCAmelCase__ : Dict=False , ) -> str:
'''simple docstring'''
A = len(references[0] )
if any(len(lowerCAmelCase__ ) != references_per_prediction for refs in references ):
raise ValueError('Sacrebleu requires the same number of references for each prediction' )
A = [[refs[i] for refs in references] for i in range(lowerCAmelCase__ )]
A = sacrebleu.corpus_bleu(
lowerCAmelCase__ , lowerCAmelCase__ , smooth_method=lowerCAmelCase__ , smooth_value=lowerCAmelCase__ , force=lowerCAmelCase__ , lowercase=lowerCAmelCase__ , use_effective_order=lowerCAmelCase__ , )
return output.score
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class lowerCAmelCase__ ( datasets.Metric ):
def __UpperCamelCase ( self : int ) -> List[str]:
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'predictions': datasets.Value('string' , id='sequence' ),
'references': datasets.Sequence(datasets.Value('string' , id='sequence' ) , id='references' ),
} ) , codebase_urls=[
'https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py',
'https://github.com/cocoxu/simplification/blob/master/SARI.py',
'https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py',
'https://github.com/mjpost/sacreBLEU',
] , reference_urls=[
'https://www.aclweb.org/anthology/Q16-1029.pdf',
'https://github.com/mjpost/sacreBLEU',
'https://en.wikipedia.org/wiki/BLEU',
'https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213',
] , )
def __UpperCamelCase ( self : Optional[Any] , __UpperCamelCase : Tuple , __UpperCamelCase : Tuple , __UpperCamelCase : Any ) -> str:
A = {}
result.update({'sari': compute_sari(sources=__UpperCamelCase , predictions=__UpperCamelCase , references=__UpperCamelCase )} )
result.update({'sacrebleu': compute_sacrebleu(predictions=__UpperCamelCase , references=__UpperCamelCase )} )
result.update({'exact': compute_em(predictions=__UpperCamelCase , references=__UpperCamelCase )} )
return result | 106 |
"""simple docstring"""
import json
import sys
import tempfile
import unittest
from pathlib import Path
import transformers
from transformers import (
CONFIG_MAPPING,
IMAGE_PROCESSOR_MAPPING,
AutoConfig,
AutoImageProcessor,
CLIPConfig,
CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER
sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils'''))
from test_module.custom_configuration import CustomConfig # noqa E402
from test_module.custom_image_processing import CustomImageProcessor # noqa E402
class snake_case ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE_ ( self :int ):
__SCREAMING_SNAKE_CASE : Tuple = 0
def SCREAMING_SNAKE_CASE_ ( self :Any ):
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :int ):
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json'''
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) )
__SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# Ensure we can load the image processor from the feature extractor config
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json'''
__SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json'''
json.dump(
{'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) )
__SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :int ):
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : str = CLIPConfig()
# Create a dummy config file with image_proceesor_type
__SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json'''
__SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) )
# remove image_processor_type to make sure config.json alone is enough to load image processor locally
__SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict()
config_dict.pop('''image_processor_type''' )
__SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase )
# save in new folder
model_config.save_pretrained(_lowerCamelCase )
config.save_pretrained(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase )
# make sure private variable is not incorrectly saved
__SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() )
self.assertTrue('''_processor_class''' not in dict_as_saved )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , )
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
with self.assertRaisesRegex(
_lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ):
__SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
with self.assertRaisesRegex(
_lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ):
__SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
with self.assertRaisesRegex(
_lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ):
__SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
# If remote code is not set, we will time out when asking whether to load the model.
with self.assertRaises(_lowerCamelCase ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' )
# If remote code is disabled, we can't load this config.
with self.assertRaises(_lowerCamelCase ):
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
# Test image processor can be reloaded.
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase )
self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
try:
AutoConfig.register('''custom''' , _lowerCamelCase )
AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase )
# Trying to register something existing in the Transformers library will raise an error
with self.assertRaises(_lowerCamelCase ):
AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase )
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json'''
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json'''
json.dump(
{'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) )
__SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase )
# Now that the config is registered, it can be used as any other config with the auto-API
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = True
try:
AutoConfig.register('''custom''' , _lowerCamelCase )
AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase )
# If remote code is not set, the default is to use local
__SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
self.assertTrue(image_processor.is_local )
# If remote code is disabled, we load the local one.
__SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
self.assertTrue(image_processor.is_local )
# If remote is enabled, we load from the Hub
__SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
self.assertTrue(not hasattr(_lowerCamelCase , '''is_local''' ) )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
| 674 | 0 |
'''simple docstring'''
import torch
import torch.nn as nn
from transformers.modeling_utils import ModuleUtilsMixin
from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm
from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin
class lowercase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ):
"""simple docstring"""
@register_to_config
def __init__( self : List[str], UpperCamelCase__ : int, UpperCamelCase__ : int, UpperCamelCase__ : int, UpperCamelCase__ : float, UpperCamelCase__ : int, UpperCamelCase__ : int, UpperCamelCase__ : int, UpperCamelCase__ : int, UpperCamelCase__ : str, UpperCamelCase__ : bool = False, ) -> str:
super().__init__()
_A = nn.Embedding(UpperCamelCase__, UpperCamelCase__ )
_A = nn.Embedding(UpperCamelCase__, UpperCamelCase__ )
_A = False
_A = nn.Dropout(p=UpperCamelCase__ )
_A = TaConfig(
vocab_size=UpperCamelCase__, d_model=UpperCamelCase__, num_heads=UpperCamelCase__, d_kv=UpperCamelCase__, d_ff=UpperCamelCase__, dropout_rate=UpperCamelCase__, feed_forward_proj=UpperCamelCase__, is_decoder=UpperCamelCase__, is_encoder_decoder=UpperCamelCase__, )
_A = nn.ModuleList()
for lyr_num in range(UpperCamelCase__ ):
_A = TaBlock(UpperCamelCase__ )
self.encoders.append(UpperCamelCase__ )
_A = TaLayerNorm(UpperCamelCase__ )
_A = nn.Dropout(p=UpperCamelCase__ )
def __UpperCAmelCase ( self : str, UpperCamelCase__ : str, UpperCamelCase__ : List[str] ) -> Dict:
_A = self.token_embedder(UpperCamelCase__ )
_A = encoder_input_tokens.shape[1]
_A = torch.arange(UpperCamelCase__, device=encoder_input_tokens.device )
x += self.position_encoding(UpperCamelCase__ )
_A = self.dropout_pre(UpperCamelCase__ )
# inverted the attention mask
_A = encoder_input_tokens.size()
_A = self.get_extended_attention_mask(UpperCamelCase__, UpperCamelCase__ )
for lyr in self.encoders:
_A = lyr(UpperCamelCase__, UpperCamelCase__ )[0]
_A = self.layer_norm(UpperCamelCase__ )
return self.dropout_post(UpperCamelCase__ ), encoder_inputs_mask
| 107 |
"""simple docstring"""
from __future__ import annotations
from typing import Any
class snake_case ( __UpperCAmelCase ):
pass
class snake_case :
def __init__( self :List[Any] , _lowerCamelCase :Any ):
__SCREAMING_SNAKE_CASE : Any = data
__SCREAMING_SNAKE_CASE : Node | None = None
def __iter__( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : List[str] = self
__SCREAMING_SNAKE_CASE : List[str] = []
while node:
if node in visited:
raise ContainsLoopError
visited.append(_lowerCamelCase )
yield node.data
__SCREAMING_SNAKE_CASE : List[str] = node.next_node
@property
def SCREAMING_SNAKE_CASE_ ( self :Any ):
try:
list(self )
return False
except ContainsLoopError:
return True
if __name__ == "__main__":
_lowerCamelCase = Node(1)
_lowerCamelCase = Node(2)
_lowerCamelCase = Node(3)
_lowerCamelCase = Node(4)
print(root_node.has_loop) # False
_lowerCamelCase = root_node.next_node
print(root_node.has_loop) # True
_lowerCamelCase = Node(5)
_lowerCamelCase = Node(6)
_lowerCamelCase = Node(5)
_lowerCamelCase = Node(6)
print(root_node.has_loop) # False
_lowerCamelCase = Node(1)
print(root_node.has_loop) # False
| 674 | 0 |
from __future__ import annotations
import math
from collections import Counter
from string import ascii_lowercase
def _SCREAMING_SNAKE_CASE ( __snake_case ) -> None:
_UpperCAmelCase , _UpperCAmelCase = analyze_text(__snake_case )
_UpperCAmelCase = list(""" """ + ascii_lowercase )
# what is our total sum of probabilities.
_UpperCAmelCase = sum(single_char_strings.values() )
# one length string
_UpperCAmelCase = 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:
_UpperCAmelCase = single_char_strings[ch]
_UpperCAmelCase = my_str / all_sum
my_fir_sum += prob * math.loga(__snake_case ) # entropy formula.
# print entropy
print(f"""{round(-1 * my_fir_sum ):.1f}""" )
# two len string
_UpperCAmelCase = sum(two_char_strings.values() )
_UpperCAmelCase = 0
# for each alpha (two in size) calculate entropy.
for cha in my_alphas:
for cha in my_alphas:
_UpperCAmelCase = cha + cha
if sequence in two_char_strings:
_UpperCAmelCase = two_char_strings[sequence]
_UpperCAmelCase = int(__snake_case ) / all_sum
my_sec_sum += prob * math.loga(__snake_case )
# 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 _SCREAMING_SNAKE_CASE ( __snake_case ) -> tuple[dict, dict]:
_UpperCAmelCase = Counter() # type: ignore
_UpperCAmelCase = 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(__snake_case ) - 1 ):
single_char_strings[text[i]] += 1
two_char_strings[text[i : i + 2]] += 1
return single_char_strings, two_char_strings
def _SCREAMING_SNAKE_CASE ( ) -> str:
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() | 108 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_lowerCamelCase = logging.get_logger(__name__)
_lowerCamelCase = {
'''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''',
}
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = '''roc_bert'''
def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ):
__SCREAMING_SNAKE_CASE : List[str] = vocab_size
__SCREAMING_SNAKE_CASE : int = max_position_embeddings
__SCREAMING_SNAKE_CASE : List[str] = hidden_size
__SCREAMING_SNAKE_CASE : str = num_hidden_layers
__SCREAMING_SNAKE_CASE : int = num_attention_heads
__SCREAMING_SNAKE_CASE : Any = intermediate_size
__SCREAMING_SNAKE_CASE : Optional[int] = hidden_act
__SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob
__SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob
__SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range
__SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size
__SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps
__SCREAMING_SNAKE_CASE : Optional[int] = use_cache
__SCREAMING_SNAKE_CASE : str = enable_pronunciation
__SCREAMING_SNAKE_CASE : List[str] = enable_shape
__SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim
__SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size
__SCREAMING_SNAKE_CASE : str = shape_embed_dim
__SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size
__SCREAMING_SNAKE_CASE : Tuple = concat_input
__SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type
__SCREAMING_SNAKE_CASE : str = classifier_dropout
super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
| 674 | 0 |
'''simple docstring'''
from .imports import is_tqdm_available
if is_tqdm_available():
from tqdm.auto import tqdm as _tqdm
from ..state import PartialState
def __magic_name__ ( __UpperCAmelCase = True , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict:
'''simple docstring'''
if not is_tqdm_available():
raise ImportError("""Accelerate's `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`.""" )
__SCREAMING_SNAKE_CASE = False
if main_process_only:
__SCREAMING_SNAKE_CASE = PartialState().local_process_index == 0
return _tqdm(*__UpperCAmelCase , **__UpperCAmelCase , disable=__UpperCAmelCase )
| 109 |
"""simple docstring"""
import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List
import git
import torch
from torch.utils.data import Dataset
from transformers import BartTokenizer, RagTokenizer, TaTokenizer
def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {}
__SCREAMING_SNAKE_CASE : Optional[int] = padding_side
return tokenizer(
[line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , )
def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 )
if attention_mask is None:
return input_ids[:, keep_column_mask]
else:
return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])
class snake_case ( __UpperCAmelCase ):
def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ):
super().__init__()
__SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' )
__SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' )
__SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file )
__SCREAMING_SNAKE_CASE : List[str] = max_source_length
__SCREAMING_SNAKE_CASE : Dict = max_target_length
assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}'''
__SCREAMING_SNAKE_CASE : Dict = tokenizer
__SCREAMING_SNAKE_CASE : Union[str, Any] = prefix
if n_obs is not None:
__SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs]
__SCREAMING_SNAKE_CASE : List[str] = src_lang
__SCREAMING_SNAKE_CASE : str = tgt_lang
def __len__( self :int ):
return len(self.src_lens )
def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ):
__SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1
__SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' )
__SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' )
assert source_line, f'''empty source line for index {index}'''
assert tgt_line, f'''empty tgt line for index {index}'''
# Need to add eos token manually for T5
if isinstance(self.tokenizer , _lowerCamelCase ):
source_line += self.tokenizer.eos_token
tgt_line += self.tokenizer.eos_token
# Pad source and target to the right
__SCREAMING_SNAKE_CASE : Dict = (
self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer
)
__SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer
__SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' )
__SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' )
__SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze()
__SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze()
__SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze()
return {
"input_ids": source_ids,
"attention_mask": src_mask,
"decoder_input_ids": target_ids,
}
@staticmethod
def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ):
return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()]
def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ):
__SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] )
__SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] )
__SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] )
__SCREAMING_SNAKE_CASE : str = (
self.tokenizer.generator.pad_token_id
if isinstance(self.tokenizer , _lowerCamelCase )
else self.tokenizer.pad_token_id
)
__SCREAMING_SNAKE_CASE : Union[str, Any] = (
self.tokenizer.question_encoder.pad_token_id
if isinstance(self.tokenizer , _lowerCamelCase )
else self.tokenizer.pad_token_id
)
__SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Dict = {
'''input_ids''': source_ids,
'''attention_mask''': source_mask,
'''decoder_input_ids''': y,
}
return batch
_lowerCamelCase = getLogger(__name__)
def lowerCAmelCase_ ( lowercase_ : List[List] ):
'''simple docstring'''
return list(itertools.chain.from_iterable(lowercase_ ) )
def lowerCAmelCase_ ( lowercase_ : str ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = get_git_info()
save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) )
def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ):
'''simple docstring'''
with open(lowercase_ , '''w''' ) as f:
json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ )
def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ):
'''simple docstring'''
with open(lowercase_ ) as f:
return json.load(lowercase_ )
def lowerCAmelCase_ ( ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ )
__SCREAMING_SNAKE_CASE : List[str] = {
'''repo_id''': str(lowercase_ ),
'''repo_sha''': str(repo.head.object.hexsha ),
'''repo_branch''': str(repo.active_branch ),
'''hostname''': str(socket.gethostname() ),
}
return repo_infos
def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ):
'''simple docstring'''
return list(map(lowercase_ , lowercase_ ) )
def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ):
'''simple docstring'''
with open(lowercase_ , '''wb''' ) as f:
return pickle.dump(lowercase_ , lowercase_ )
def lowerCAmelCase_ ( lowercase_ : Any ):
'''simple docstring'''
def remove_articles(lowercase_ : Dict ):
return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ )
def white_space_fix(lowercase_ : Optional[int] ):
return " ".join(text.split() )
def remove_punc(lowercase_ : Any ):
__SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation )
return "".join(ch for ch in text if ch not in exclude )
def lower(lowercase_ : int ):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) )
def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split()
__SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split()
__SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ )
__SCREAMING_SNAKE_CASE : Tuple = sum(common.values() )
if num_same == 0:
return 0
__SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ )
__SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ )
__SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall)
return fa
def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ):
'''simple docstring'''
return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ )
def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ):
'''simple docstring'''
assert len(lowercase_ ) == len(lowercase_ )
__SCREAMING_SNAKE_CASE : Union[str, Any] = 0
for hypo, pred in zip(lowercase_ , lowercase_ ):
em += exact_match_score(lowercase_ , lowercase_ )
if len(lowercase_ ) > 0:
em /= len(lowercase_ )
return {"em": em}
def lowerCAmelCase_ ( lowercase_ : str ):
'''simple docstring'''
return model_prefix.startswith('''rag''' )
def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params}
# T5 models don't have `dropout` param, they have `dropout_rate` instead
__SCREAMING_SNAKE_CASE : Any = '''dropout_rate'''
for p in extra_params:
if getattr(lowercase_ , lowercase_ , lowercase_ ):
if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ):
logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) )
delattr(lowercase_ , lowercase_ )
continue
__SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p]
setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) )
delattr(lowercase_ , lowercase_ )
return hparams, config
| 674 | 0 |
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
__lowerCAmelCase = data_utils.TransfoXLTokenizer
__lowerCAmelCase = data_utils.TransfoXLCorpus
__lowerCAmelCase = data_utils
__lowerCAmelCase = data_utils
def a ( a , a , a , a ) ->List[Any]:
'''simple docstring'''
if transfo_xl_dataset_file:
# Convert a pre-processed corpus (see original TensorFlow repo)
with open(lowercase_ , '''rb''' ) as fp:
SCREAMING_SNAKE_CASE = pickle.load(lowercase_ , encoding='''latin1''' )
# Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term)
SCREAMING_SNAKE_CASE = pytorch_dump_folder_path + '''/''' + VOCAB_FILES_NAMES['''pretrained_vocab_file''']
print(F"""Save vocabulary to {pytorch_vocab_dump_path}""" )
SCREAMING_SNAKE_CASE = corpus.vocab.__dict__
torch.save(lowercase_ , lowercase_ )
SCREAMING_SNAKE_CASE = corpus.__dict__
corpus_dict_no_vocab.pop('''vocab''' , lowercase_ )
SCREAMING_SNAKE_CASE = pytorch_dump_folder_path + '''/''' + CORPUS_NAME
print(F"""Save dataset to {pytorch_dataset_dump_path}""" )
torch.save(lowercase_ , lowercase_ )
if tf_checkpoint_path:
# Convert a pre-trained TensorFlow model
SCREAMING_SNAKE_CASE = os.path.abspath(lowercase_ )
SCREAMING_SNAKE_CASE = os.path.abspath(lowercase_ )
print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" )
# Initialise PyTorch model
if transfo_xl_config_file == "":
SCREAMING_SNAKE_CASE = TransfoXLConfig()
else:
SCREAMING_SNAKE_CASE = TransfoXLConfig.from_json_file(lowercase_ )
print(F"""Building PyTorch model from configuration: {config}""" )
SCREAMING_SNAKE_CASE = TransfoXLLMHeadModel(lowercase_ )
SCREAMING_SNAKE_CASE = load_tf_weights_in_transfo_xl(lowercase_ , lowercase_ , lowercase_ )
# Save pytorch-model
SCREAMING_SNAKE_CASE = os.path.join(lowercase_ , lowercase_ )
SCREAMING_SNAKE_CASE = os.path.join(lowercase_ , lowercase_ )
print(F"""Save PyTorch model to {os.path.abspath(lowercase_ )}""" )
torch.save(model.state_dict() , lowercase_ )
print(F"""Save configuration file to {os.path.abspath(lowercase_ )}""" )
with open(lowercase_ , '''w''' , encoding='''utf-8''' ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
__lowerCAmelCase = 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.',
)
__lowerCAmelCase = 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,
) | 201 |
"""simple docstring"""
from collections.abc import Callable
import numpy as np
def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) )
__SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) )
__SCREAMING_SNAKE_CASE : List[Any] = ya
__SCREAMING_SNAKE_CASE : Dict = xa
for k in range(lowercase_ ):
__SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] )
__SCREAMING_SNAKE_CASE : int = y[k] + (
(step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ ))
)
x += step_size
return y
if __name__ == "__main__":
import doctest
doctest.testmod()
| 674 | 0 |
"""simple docstring"""
from typing import Callable, Optional, Union
from ...configuration_utils import PretrainedConfig
from ...utils import logging
a : int = logging.get_logger(__name__)
a : str = {
"""microsoft/xprophetnet-large-wiki100-cased""": (
"""https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json"""
),
}
class __UpperCAmelCase( __UpperCAmelCase ):
"""simple docstring"""
__lowerCamelCase = "xlm-prophetnet"
__lowerCamelCase = ["past_key_values"]
__lowerCamelCase = {
"num_attention_heads": "num_encoder_attention_heads",
}
def __init__( self , snake_case__ = 0.1 , snake_case__ = "gelu" , snake_case__ = 30522 , snake_case__ = 1024 , snake_case__ = 4096 , snake_case__ = 12 , snake_case__ = 16 , snake_case__ = 4096 , snake_case__ = 12 , snake_case__ = 16 , snake_case__ = 0.1 , snake_case__ = 0.1 , snake_case__ = 512 , snake_case__ = 0.02 , snake_case__ = True , snake_case__ = True , snake_case__ = 0 , snake_case__ = 2 , snake_case__ = 32 , snake_case__ = 128 , snake_case__ = False , snake_case__ = 0.0 , snake_case__ = True , snake_case__ = 0 , snake_case__ = 1 , snake_case__ = 2 , **snake_case__ , ):
'''simple docstring'''
lowercase__ : Union[str, Any]= vocab_size
lowercase__ : Optional[int]= hidden_size
lowercase__ : List[Any]= encoder_ffn_dim
lowercase__ : str= num_encoder_layers
lowercase__ : Optional[Any]= num_encoder_attention_heads
lowercase__ : str= decoder_ffn_dim
lowercase__ : List[Any]= num_decoder_layers
lowercase__ : List[str]= num_decoder_attention_heads
lowercase__ : Dict= max_position_embeddings
lowercase__ : Any= init_std # Normal(0, this parameter)
lowercase__ : Any= activation_function
# parameters for xlmprophetnet
lowercase__ : List[Any]= ngram
lowercase__ : int= num_buckets
lowercase__ : List[str]= relative_max_distance
lowercase__ : str= disable_ngram_loss
lowercase__ : Optional[int]= eps
# 3 Types of Dropout
lowercase__ : int= attention_dropout
lowercase__ : Optional[Any]= activation_dropout
lowercase__ : Dict= dropout
lowercase__ : Any= use_cache
super().__init__(
pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , )
@property
def UpperCAmelCase_ ( self ):
'''simple docstring'''
return self.num_encoder_layers + self.num_decoder_layers
@num_hidden_layers.setter
def UpperCAmelCase_ ( self , snake_case__ ):
'''simple docstring'''
raise NotImplementedError(
"This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and"
" `num_decoder_layers`." )
| 218 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...file_utils import _LazyModule, is_torch_available
from ...utils import OptionalDependencyNotAvailable
_lowerCamelCase = {
'''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''],
'''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase = [
'''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''GPTNeoXJapaneseForCausalLM''',
'''GPTNeoXJapaneseLayer''',
'''GPTNeoXJapaneseModel''',
'''GPTNeoXJapanesePreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig
from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_gpt_neox_japanese import (
GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST,
GPTNeoXJapaneseForCausalLM,
GPTNeoXJapaneseLayer,
GPTNeoXJapaneseModel,
GPTNeoXJapanesePreTrainedModel,
)
else:
import sys
_lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 674 | 0 |
import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock
import torch
from ..state import AcceleratorState, PartialState
from ..utils import (
gather,
is_bnb_available,
is_comet_ml_available,
is_datasets_available,
is_deepspeed_available,
is_mps_available,
is_safetensors_available,
is_tensorboard_available,
is_torch_version,
is_tpu_available,
is_transformers_available,
is_wandb_available,
is_xpu_available,
)
def __snake_case ( _UpperCamelCase , _UpperCamelCase=False ) -> int:
try:
_a = os.environ[key]
except KeyError:
# KEY isn't set, default to `default`.
_a = default
else:
# KEY is set, convert it to True or False.
try:
_a = strtobool(lowercase_ )
except ValueError:
# More values are supported, but let's keep the message simple.
raise ValueError(f"If set, {key} must be yes or no." )
return _value
lowerCamelCase :Optional[int] = parse_flag_from_env('RUN_SLOW', default=False)
def __snake_case ( _UpperCamelCase ) -> List[Any]:
return unittest.skip('''Test was skipped''' )(lowercase_ )
def __snake_case ( _UpperCamelCase ) -> List[Any]:
return unittest.skipUnless(_run_slow_tests , '''test is slow''' )(lowercase_ )
def __snake_case ( _UpperCamelCase ) -> int:
return unittest.skipUnless(not torch.cuda.is_available() , '''test requires only a CPU''' )(lowercase_ )
def __snake_case ( _UpperCamelCase ) -> List[Any]:
return unittest.skipUnless(torch.cuda.is_available() , '''test requires a GPU''' )(lowercase_ )
def __snake_case ( _UpperCamelCase ) -> str:
return unittest.skipUnless(is_xpu_available() , '''test requires a XPU''' )(lowercase_ )
def __snake_case ( _UpperCamelCase ) -> Optional[Any]:
return unittest.skipUnless(is_mps_available() , '''test requires a `mps` backend support in `torch`''' )(lowercase_ )
def __snake_case ( _UpperCamelCase ) -> Optional[Any]:
return unittest.skipUnless(
is_transformers_available() and is_datasets_available() , '''test requires the Hugging Face suite''' )(lowercase_ )
def __snake_case ( _UpperCamelCase ) -> Optional[Any]:
return unittest.skipUnless(is_bnb_available() , '''test requires the bitsandbytes library''' )(lowercase_ )
def __snake_case ( _UpperCamelCase ) -> List[Any]:
return unittest.skipUnless(is_tpu_available() , '''test requires TPU''' )(lowercase_ )
def __snake_case ( _UpperCamelCase ) -> Any:
return unittest.skipUnless(torch.cuda.device_count() == 1 , '''test requires a GPU''' )(lowercase_ )
def __snake_case ( _UpperCamelCase ) -> str:
return unittest.skipUnless(torch.xpu.device_count() == 1 , '''test requires a XPU''' )(lowercase_ )
def __snake_case ( _UpperCamelCase ) -> str:
return unittest.skipUnless(torch.cuda.device_count() > 1 , '''test requires multiple GPUs''' )(lowercase_ )
def __snake_case ( _UpperCamelCase ) -> Dict:
return unittest.skipUnless(torch.xpu.device_count() > 1 , '''test requires multiple XPUs''' )(lowercase_ )
def __snake_case ( _UpperCamelCase ) -> Union[str, Any]:
return unittest.skipUnless(is_safetensors_available() , '''test requires safetensors''' )(lowercase_ )
def __snake_case ( _UpperCamelCase ) -> List[Any]:
return unittest.skipUnless(is_deepspeed_available() , '''test requires DeepSpeed''' )(lowercase_ )
def __snake_case ( _UpperCamelCase ) -> List[Any]:
return unittest.skipUnless(is_torch_version('''>=''' , '''1.12.0''' ) , '''test requires torch version >= 1.12.0''' )(lowercase_ )
def __snake_case ( _UpperCamelCase=None , _UpperCamelCase=None ) -> Union[str, Any]:
if test_case is None:
return partial(lowercase_ , version=lowercase_ )
return unittest.skipUnless(is_torch_version('''>=''' , lowercase_ ) , f"test requires torch version >= {version}" )(lowercase_ )
def __snake_case ( _UpperCamelCase ) -> Tuple:
return unittest.skipUnless(is_tensorboard_available() , '''test requires Tensorboard''' )(lowercase_ )
def __snake_case ( _UpperCamelCase ) -> List[str]:
return unittest.skipUnless(is_wandb_available() , '''test requires wandb''' )(lowercase_ )
def __snake_case ( _UpperCamelCase ) -> Any:
return unittest.skipUnless(is_comet_ml_available() , '''test requires comet_ml''' )(lowercase_ )
lowerCamelCase :Optional[Any] = (
any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)
def __snake_case ( _UpperCamelCase ) -> List[Any]:
return unittest.skipUnless(
_atleast_one_tracker_available , '''test requires at least one tracker to be available and for `comet_ml` to not be installed''' , )(lowercase_ )
class UpperCAmelCase ( unittest.TestCase ):
a: Union[str, Any] = True
@classmethod
def _A ( cls: Optional[int] ):
_a = tempfile.mkdtemp()
@classmethod
def _A ( cls: str ):
if os.path.exists(cls.tmpdir ):
shutil.rmtree(cls.tmpdir )
def _A ( self: Union[str, Any] ):
if self.clear_on_setup:
for path in Path(self.tmpdir ).glob('''**/*''' ):
if path.is_file():
path.unlink()
elif path.is_dir():
shutil.rmtree(_lowerCamelCase )
class UpperCAmelCase ( unittest.TestCase ):
def _A ( self: Optional[int] ):
super().tearDown()
# Reset the state of the AcceleratorState singleton.
AcceleratorState._reset_state()
PartialState._reset_state()
class UpperCAmelCase ( unittest.TestCase ):
def _A ( self: int , __UpperCamelCase: Union[mock.Mock, List[mock.Mock]] ):
_a = mocks if isinstance(_lowerCamelCase , (tuple, list) ) else [mocks]
for m in self.mocks:
m.start()
self.addCleanup(m.stop )
def __snake_case ( _UpperCamelCase ) -> List[Any]:
_a = AcceleratorState()
_a = tensor[None].clone().to(state.device )
_a = gather(lowercase_ ).cpu()
_a = tensor[0].cpu()
for i in range(tensors.shape[0] ):
if not torch.equal(tensors[i] , lowercase_ ):
return False
return True
class UpperCAmelCase :
def __init__( self: str , __UpperCamelCase: Any , __UpperCamelCase: Union[str, Any] , __UpperCamelCase: Optional[Any] ):
_a = returncode
_a = stdout
_a = stderr
async def __snake_case ( _UpperCamelCase , _UpperCamelCase ) -> Optional[int]:
while True:
_a = await stream.readline()
if line:
callback(lowercase_ )
else:
break
async def __snake_case ( _UpperCamelCase , _UpperCamelCase=None , _UpperCamelCase=None , _UpperCamelCase=None , _UpperCamelCase=False , _UpperCamelCase=False ) -> int:
if echo:
print('''\nRunning: ''' , ''' '''.join(lowercase_ ) )
_a = await asyncio.create_subprocess_exec(
cmd[0] , *cmd[1:] , stdin=lowercase_ , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=lowercase_ , )
# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
#
# If it starts hanging, will need to switch to the following code. The problem is that no data
# will be seen until it's done and if it hangs for example there will be no debug info.
# out, err = await p.communicate()
# return _RunOutput(p.returncode, out, err)
_a = []
_a = []
def tee(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase="" ):
_a = line.decode('''utf-8''' ).rstrip()
sink.append(lowercase_ )
if not quiet:
print(lowercase_ , lowercase_ , file=lowercase_ )
# XXX: the timeout doesn't seem to make any difference here
await asyncio.wait(
[
asyncio.create_task(_read_stream(p.stdout , lambda _UpperCamelCase : tee(lowercase_ , lowercase_ , sys.stdout , label='''stdout:''' ) ) ),
asyncio.create_task(_read_stream(p.stderr , lambda _UpperCamelCase : tee(lowercase_ , lowercase_ , sys.stderr , label='''stderr:''' ) ) ),
] , timeout=lowercase_ , )
return _RunOutput(await p.wait() , lowercase_ , lowercase_ )
def __snake_case ( _UpperCamelCase , _UpperCamelCase=None , _UpperCamelCase=None , _UpperCamelCase=1_80 , _UpperCamelCase=False , _UpperCamelCase=True ) -> Optional[Any]:
_a = asyncio.get_event_loop()
_a = loop.run_until_complete(
_stream_subprocess(lowercase_ , env=lowercase_ , stdin=lowercase_ , timeout=lowercase_ , quiet=lowercase_ , echo=lowercase_ ) )
_a = ''' '''.join(lowercase_ )
if result.returncode > 0:
_a = '''\n'''.join(result.stderr )
raise RuntimeError(
f"\'{cmd_str}\' failed with returncode {result.returncode}\n\n"
f"The combined stderr from workers follows:\n{stderr}" )
return result
class UpperCAmelCase ( __UpperCAmelCase ):
pass
def __snake_case ( _UpperCamelCase , _UpperCamelCase=False ) -> List[str]:
try:
_a = subprocess.check_output(lowercase_ , stderr=subprocess.STDOUT )
if return_stdout:
if hasattr(lowercase_ , '''decode''' ):
_a = output.decode('''utf-8''' )
return output
except subprocess.CalledProcessError as e:
raise SubprocessCallException(
f"Command `{' '.join(lowercase_ )}` failed with the following error:\n\n{e.output.decode()}" ) from e
| 487 |
"""simple docstring"""
from __future__ import annotations
from typing import Any
class snake_case :
def __init__( self :Optional[Any] , _lowerCamelCase :int ):
__SCREAMING_SNAKE_CASE : int = num_of_nodes
__SCREAMING_SNAKE_CASE : list[list[int]] = []
__SCREAMING_SNAKE_CASE : dict[int, int] = {}
def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ):
self.m_edges.append([u_node, v_node, weight] )
def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ):
if self.m_component[u_node] == u_node:
return u_node
return self.find_component(self.m_component[u_node] )
def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ):
if self.m_component[u_node] != u_node:
for k in self.m_component:
__SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ):
if component_size[u_node] <= component_size[v_node]:
__SCREAMING_SNAKE_CASE : List[Any] = v_node
component_size[v_node] += component_size[u_node]
self.set_component(_lowerCamelCase )
elif component_size[u_node] >= component_size[v_node]:
__SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase )
component_size[u_node] += component_size[v_node]
self.set_component(_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
__SCREAMING_SNAKE_CASE : Optional[int] = []
__SCREAMING_SNAKE_CASE : str = 0
__SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes
# A list of components (initialized to all of the nodes)
for node in range(self.m_num_of_nodes ):
self.m_component.update({node: node} )
component_size.append(1 )
__SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes
while num_of_components > 1:
for edge in self.m_edges:
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge
__SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u]
__SCREAMING_SNAKE_CASE : int = self.m_component[v]
if u_component != v_component:
for component in (u_component, v_component):
if (
minimum_weight_edge[component] == -1
or minimum_weight_edge[component][2] > w
):
__SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w]
for edge in minimum_weight_edge:
if isinstance(_lowerCamelCase , _lowerCamelCase ):
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge
__SCREAMING_SNAKE_CASE : Tuple = self.m_component[u]
__SCREAMING_SNAKE_CASE : int = self.m_component[v]
if u_component != v_component:
mst_weight += w
self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' )
num_of_components -= 1
__SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes
print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' )
def lowerCAmelCase_ ( ):
'''simple docstring'''
if __name__ == "__main__":
import doctest
doctest.testmod()
| 674 | 0 |
"""simple docstring"""
from ..utils import (
OptionalDependencyNotAvailable,
is_flax_available,
is_scipy_available,
is_torch_available,
is_torchsde_available,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ..utils.dummy_pt_objects import * # noqa F403
else:
from .scheduling_consistency_models import CMStochasticIterativeScheduler
from .scheduling_ddim import DDIMScheduler
from .scheduling_ddim_inverse import DDIMInverseScheduler
from .scheduling_ddim_parallel import DDIMParallelScheduler
from .scheduling_ddpm import DDPMScheduler
from .scheduling_ddpm_parallel import DDPMParallelScheduler
from .scheduling_deis_multistep import DEISMultistepScheduler
from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler
from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler
from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler
from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler
from .scheduling_euler_discrete import EulerDiscreteScheduler
from .scheduling_heun_discrete import HeunDiscreteScheduler
from .scheduling_ipndm import IPNDMScheduler
from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler
from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler
from .scheduling_karras_ve import KarrasVeScheduler
from .scheduling_pndm import PNDMScheduler
from .scheduling_repaint import RePaintScheduler
from .scheduling_sde_ve import ScoreSdeVeScheduler
from .scheduling_sde_vp import ScoreSdeVpScheduler
from .scheduling_unclip import UnCLIPScheduler
from .scheduling_unipc_multistep import UniPCMultistepScheduler
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin
from .scheduling_vq_diffusion import VQDiffusionScheduler
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ..utils.dummy_flax_objects import * # noqa F403
else:
from .scheduling_ddim_flax import FlaxDDIMScheduler
from .scheduling_ddpm_flax import FlaxDDPMScheduler
from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler
from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler
from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler
from .scheduling_pndm_flax import FlaxPNDMScheduler
from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler
from .scheduling_utils_flax import (
FlaxKarrasDiffusionSchedulers,
FlaxSchedulerMixin,
FlaxSchedulerOutput,
broadcast_to_shape_from_left,
)
try:
if not (is_torch_available() and is_scipy_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ..utils.dummy_torch_and_scipy_objects import * # noqa F403
else:
from .scheduling_lms_discrete import LMSDiscreteScheduler
try:
if not (is_torch_available() and is_torchsde_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ..utils.dummy_torch_and_torchsde_objects import * # noqa F403
else:
from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler
| 76 |
"""simple docstring"""
import argparse
import pickle
import numpy as np
import torch
from torch import nn
from transformers import ReformerConfig, ReformerModelWithLMHead
from transformers.utils import logging
logging.set_verbosity_info()
def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ):
'''simple docstring'''
assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match'''
__SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ )
if bias is not None:
assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match'''
__SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ )
def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] )
__SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] )
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] )
set_param(
torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , )
def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] )
__SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] )
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] )
__SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] )
set_param(
torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , )
set_param(
torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , )
def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = weights[0][0][0]
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] )
__SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] )
set_param(
torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , )
# lsh weights + output
__SCREAMING_SNAKE_CASE : Tuple = weights[0][1]
if len(lowercase_ ) < 4:
set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ )
else:
set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ )
# intermediate weighs
__SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2]
# Chunked Feed Forward
if len(lowercase_ ) == 4:
__SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2]
# layernorm 2
__SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] )
__SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] )
set_param(
torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , )
# intermediate dense
__SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] )
set_param(
torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , )
# intermediate out
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] )
__SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] )
set_param(
torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , )
def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Dict = torch_model.reformer
# word embeds
__SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] )
set_param(
torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , )
if isinstance(weights[3] , lowercase_ ):
__SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings
for emb_idx in range(len(position_embeddings.weights ) ):
__SCREAMING_SNAKE_CASE : Dict = np.asarray(weights[3][emb_idx][0] )
assert (
position_embeddings.weights[emb_idx].shape == emb_weights.shape
), F'''{position_embeddings[emb_idx]} emb does not match'''
__SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) )
__SCREAMING_SNAKE_CASE : List[Any] = weights[5]
assert len(torch_model_reformer.encoder.layers ) * 4 == len(
lowercase_ ), "HF and trax model do not have the same number of layers"
for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)]
set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ )
# output layer norm
__SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] )
set_param(
torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , )
# output embeddings
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] )
__SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] )
set_param(
torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , )
def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ )
print(F'''Building PyTorch model from configuration: {config}''' )
__SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ )
with open(lowercase_ , '''rb''' ) as f:
__SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights''']
set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size )
# Save pytorch-model
print(F'''Save PyTorch model to {pytorch_dump_path}''' )
torch.save(model.state_dict() , lowercase_ )
if __name__ == "__main__":
_lowerCamelCase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--trax_model_pkl_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.'''
)
parser.add_argument(
'''--config_file''',
default=None,
type=str,
required=True,
help=(
'''The config json file corresponding to the pre-trained Reformer model. \n'''
'''This specifies the model architecture.'''
),
)
parser.add_argument(
'''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
)
_lowerCamelCase = parser.parse_args()
convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
| 674 | 0 |
import inspect
import unittest
import numpy as np
from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel
if is_vision_available():
from transformers import MaskFormerImageProcessor
if is_vision_available():
from PIL import Image
class _lowerCamelCase :
def __init__( self , lowerCAmelCase , lowerCAmelCase=2 , lowerCAmelCase=True , lowerCAmelCase=False , lowerCAmelCase=10 , lowerCAmelCase=3 , lowerCAmelCase=32 * 4 , lowerCAmelCase=32 * 6 , lowerCAmelCase=4 , lowerCAmelCase=32 , ) -> List[Any]:
SCREAMING_SNAKE_CASE__: List[str]= parent
SCREAMING_SNAKE_CASE__: Tuple= batch_size
SCREAMING_SNAKE_CASE__: Optional[Any]= is_training
SCREAMING_SNAKE_CASE__: Dict= use_auxiliary_loss
SCREAMING_SNAKE_CASE__: List[str]= num_queries
SCREAMING_SNAKE_CASE__: Optional[int]= num_channels
SCREAMING_SNAKE_CASE__: List[Any]= min_size
SCREAMING_SNAKE_CASE__: int= max_size
SCREAMING_SNAKE_CASE__: Any= num_labels
SCREAMING_SNAKE_CASE__: Union[str, Any]= mask_feature_size
def UpperCamelCase_ ( self ) -> str:
SCREAMING_SNAKE_CASE__: str= floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to(
_lowerCamelCase )
SCREAMING_SNAKE_CASE__: Any= torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase )
SCREAMING_SNAKE_CASE__: Any= (
torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5
).float()
SCREAMING_SNAKE_CASE__: Dict= (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long()
SCREAMING_SNAKE_CASE__: str= self.get_config()
return config, pixel_values, pixel_mask, mask_labels, class_labels
def UpperCamelCase_ ( self ) -> Dict:
return MaskFormerConfig.from_backbone_and_decoder_configs(
backbone_config=SwinConfig(
depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig(
decoder_ffn_dim=128 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , )
def UpperCamelCase_ ( self ) -> Optional[int]:
SCREAMING_SNAKE_CASE__: Optional[Any]= self.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE__: Any= {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
return config, inputs_dict
def UpperCamelCase_ ( self , lowerCAmelCase , lowerCAmelCase ) -> Any:
SCREAMING_SNAKE_CASE__: Union[str, Any]= output.encoder_hidden_states
SCREAMING_SNAKE_CASE__: int= output.pixel_decoder_hidden_states
SCREAMING_SNAKE_CASE__: Optional[int]= output.transformer_decoder_hidden_states
self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers )
def UpperCamelCase_ ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase=False ) -> Optional[int]:
with torch.no_grad():
SCREAMING_SNAKE_CASE__: List[str]= MaskFormerModel(config=_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
SCREAMING_SNAKE_CASE__: str= model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase )
SCREAMING_SNAKE_CASE__: Any= model(_lowerCamelCase , output_hidden_states=_lowerCamelCase )
# the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
# encoder and pixel decoder
self.parent.assertEqual(
output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , )
# let's ensure the other two hidden state exists
self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(output.encoder_last_hidden_state is not None )
if output_hidden_states:
self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase )
def UpperCamelCase_ ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) -> str:
SCREAMING_SNAKE_CASE__: Optional[Any]= MaskFormerForInstanceSegmentation(config=_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
def comm_check_on_output(lowerCAmelCase ):
# let's still check that all the required stuff is there
self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.encoder_last_hidden_state is not None )
# okay, now we need to check the logits shape
# due to the encoder compression, masks have a //4 spatial size
self.parent.assertEqual(
result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , )
# + 1 for null class
self.parent.assertEqual(
result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) )
with torch.no_grad():
SCREAMING_SNAKE_CASE__: List[str]= model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase )
SCREAMING_SNAKE_CASE__: int= model(_lowerCamelCase )
comm_check_on_output(_lowerCamelCase )
SCREAMING_SNAKE_CASE__: Dict= model(
pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase )
comm_check_on_output(_lowerCamelCase )
self.parent.assertTrue(result.loss is not None )
self.parent.assertEqual(result.loss.shape , torch.Size([1] ) )
@require_torch
class _lowerCamelCase ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ):
__a = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
__a = (
{"feature-extraction": MaskFormerModel, "image-segmentation": MaskFormerForInstanceSegmentation}
if is_torch_available()
else {}
)
__a = False
__a = False
__a = False
__a = False
def UpperCamelCase_ ( self ) -> Tuple:
SCREAMING_SNAKE_CASE__: Optional[Any]= MaskFormerModelTester(self )
SCREAMING_SNAKE_CASE__: str= ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase )
def UpperCamelCase_ ( self ) -> str:
self.config_tester.run_common_tests()
def UpperCamelCase_ ( self ) -> int:
SCREAMING_SNAKE_CASE__: Any= self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase )
def UpperCamelCase_ ( self ) -> str:
SCREAMING_SNAKE_CASE__: Dict= self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase )
@unittest.skip(reason='''MaskFormer does not use inputs_embeds''' )
def UpperCamelCase_ ( self ) -> str:
pass
@unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' )
def UpperCamelCase_ ( self ) -> Any:
pass
@unittest.skip(reason='''MaskFormer is not a generative model''' )
def UpperCamelCase_ ( self ) -> Any:
pass
@unittest.skip(reason='''MaskFormer does not use token embeddings''' )
def UpperCamelCase_ ( self ) -> List[Any]:
pass
@require_torch_multi_gpu
@unittest.skip(
reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' )
def UpperCamelCase_ ( self ) -> int:
pass
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def UpperCamelCase_ ( self ) -> Any:
pass
def UpperCamelCase_ ( self ) -> int:
SCREAMING_SNAKE_CASE__: Any= self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
SCREAMING_SNAKE_CASE__: Tuple= model_class(_lowerCamelCase )
SCREAMING_SNAKE_CASE__: Optional[int]= inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
SCREAMING_SNAKE_CASE__: List[str]= [*signature.parameters.keys()]
SCREAMING_SNAKE_CASE__: Optional[Any]= ['''pixel_values''']
self.assertListEqual(arg_names[:1] , _lowerCamelCase )
@slow
def UpperCamelCase_ ( self ) -> str:
for model_name in ["facebook/maskformer-swin-small-coco"]:
SCREAMING_SNAKE_CASE__: Tuple= MaskFormerModel.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
def UpperCamelCase_ ( self ) -> List[Any]:
SCREAMING_SNAKE_CASE__: Dict= (self.model_tester.min_size,) * 2
SCREAMING_SNAKE_CASE__: Dict= {
'''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ),
'''mask_labels''': torch.randn((2, 10, *size) , device=_lowerCamelCase ),
'''class_labels''': torch.zeros(2 , 10 , device=_lowerCamelCase ).long(),
}
SCREAMING_SNAKE_CASE__: Dict= MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase )
SCREAMING_SNAKE_CASE__: Optional[Any]= model(**_lowerCamelCase )
self.assertTrue(outputs.loss is not None )
def UpperCamelCase_ ( self ) -> Any:
SCREAMING_SNAKE_CASE__: Tuple= self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase )
def UpperCamelCase_ ( self ) -> Optional[Any]:
SCREAMING_SNAKE_CASE__: Tuple= self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
SCREAMING_SNAKE_CASE__: Dict= model_class(_lowerCamelCase ).to(_lowerCamelCase )
SCREAMING_SNAKE_CASE__: Optional[int]= model(**_lowerCamelCase , output_attentions=_lowerCamelCase )
self.assertTrue(outputs.attentions is not None )
def UpperCamelCase_ ( self ) -> Tuple:
if not self.model_tester.is_training:
return
# only MaskFormerForInstanceSegmentation has the loss
SCREAMING_SNAKE_CASE__: List[Any]= self.all_model_classes[1]
SCREAMING_SNAKE_CASE__: Dict= self.model_tester.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE__: int= model_class(_lowerCamelCase )
model.to(_lowerCamelCase )
model.train()
SCREAMING_SNAKE_CASE__: Any= model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss
loss.backward()
def UpperCamelCase_ ( self ) -> Dict:
# only MaskFormerForInstanceSegmentation has the loss
SCREAMING_SNAKE_CASE__: Tuple= self.all_model_classes[1]
SCREAMING_SNAKE_CASE__: Tuple= self.model_tester.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE__: Tuple= True
SCREAMING_SNAKE_CASE__: List[str]= True
SCREAMING_SNAKE_CASE__: Any= model_class(_lowerCamelCase )
model.to(_lowerCamelCase )
model.train()
SCREAMING_SNAKE_CASE__: Optional[int]= model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase )
SCREAMING_SNAKE_CASE__: List[str]= outputs.encoder_hidden_states[0]
encoder_hidden_states.retain_grad()
SCREAMING_SNAKE_CASE__: str= outputs.pixel_decoder_hidden_states[0]
pixel_decoder_hidden_states.retain_grad()
# we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
SCREAMING_SNAKE_CASE__: Optional[int]= outputs.transformer_decoder_hidden_states[0]
transformer_decoder_hidden_states.retain_grad()
SCREAMING_SNAKE_CASE__: int= outputs.attentions[0]
attentions.retain_grad()
outputs.loss.backward(retain_graph=_lowerCamelCase )
self.assertIsNotNone(encoder_hidden_states.grad )
self.assertIsNotNone(pixel_decoder_hidden_states.grad )
self.assertIsNotNone(transformer_decoder_hidden_states.grad )
self.assertIsNotNone(attentions.grad )
lowercase_ : int = 1E-4
def A__ ( ):
SCREAMING_SNAKE_CASE__: List[Any]= Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_vision
@slow
class _lowerCamelCase ( unittest.TestCase ):
@cached_property
def UpperCamelCase_ ( self ) -> int:
return (
MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' )
if is_vision_available()
else None
)
def UpperCamelCase_ ( self ) -> List[Any]:
SCREAMING_SNAKE_CASE__: Union[str, Any]= MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase )
SCREAMING_SNAKE_CASE__: int= self.default_image_processor
SCREAMING_SNAKE_CASE__: Tuple= prepare_img()
SCREAMING_SNAKE_CASE__: List[Any]= image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase )
SCREAMING_SNAKE_CASE__: int= inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(_lowerCamelCase , (1, 3, 800, 1088) )
with torch.no_grad():
SCREAMING_SNAKE_CASE__: Tuple= model(**_lowerCamelCase )
SCREAMING_SNAKE_CASE__: Union[str, Any]= torch.tensor(
[[-0.0482, 0.9228, 0.4951], [-0.2547, 0.8017, 0.8527], [-0.0069, 0.3385, -0.0089]] ).to(_lowerCamelCase )
self.assertTrue(
torch.allclose(
outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
SCREAMING_SNAKE_CASE__: Any= torch.tensor(
[[-0.8422, -0.8434, -0.9718], [-1.0144, -0.5565, -0.4195], [-1.0038, -0.4484, -0.1961]] ).to(_lowerCamelCase )
self.assertTrue(
torch.allclose(
outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
SCREAMING_SNAKE_CASE__: Optional[int]= torch.tensor(
[[0.2852, -0.0159, 0.9735], [0.6254, 0.1858, 0.8529], [-0.0680, -0.4116, 1.8413]] ).to(_lowerCamelCase )
self.assertTrue(
torch.allclose(
outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
def UpperCamelCase_ ( self ) -> Dict:
SCREAMING_SNAKE_CASE__: Tuple= (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
.to(_lowerCamelCase )
.eval()
)
SCREAMING_SNAKE_CASE__: Union[str, Any]= self.default_image_processor
SCREAMING_SNAKE_CASE__: Tuple= prepare_img()
SCREAMING_SNAKE_CASE__: str= image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase )
SCREAMING_SNAKE_CASE__: List[str]= inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(_lowerCamelCase , (1, 3, 800, 1088) )
with torch.no_grad():
SCREAMING_SNAKE_CASE__: str= model(**_lowerCamelCase )
# masks_queries_logits
SCREAMING_SNAKE_CASE__: Any= outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
SCREAMING_SNAKE_CASE__: List[Any]= [
[-1.3737124, -1.7724937, -1.9364233],
[-1.5977281, -1.9867939, -2.1523695],
[-1.5795398, -1.9269832, -2.093942],
]
SCREAMING_SNAKE_CASE__: Any= torch.tensor(_lowerCamelCase ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
# class_queries_logits
SCREAMING_SNAKE_CASE__: List[Any]= outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
SCREAMING_SNAKE_CASE__: List[str]= torch.tensor(
[
[1.6512e00, -5.2572e00, -3.3519e00],
[3.6169e-02, -5.9025e00, -2.9313e00],
[1.0766e-04, -7.7630e00, -5.1263e00],
] ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
def UpperCamelCase_ ( self ) -> Tuple:
SCREAMING_SNAKE_CASE__: Tuple= (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' )
.to(_lowerCamelCase )
.eval()
)
SCREAMING_SNAKE_CASE__: Tuple= self.default_image_processor
SCREAMING_SNAKE_CASE__: str= prepare_img()
SCREAMING_SNAKE_CASE__: List[Any]= image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase )
SCREAMING_SNAKE_CASE__: List[Any]= inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(_lowerCamelCase , (1, 3, 800, 1088) )
with torch.no_grad():
SCREAMING_SNAKE_CASE__: List[Any]= model(**_lowerCamelCase )
# masks_queries_logits
SCREAMING_SNAKE_CASE__: Union[str, Any]= outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
SCREAMING_SNAKE_CASE__: List[str]= [[-0.9046, -2.6366, -4.6062], [-3.4179, -5.7890, -8.8057], [-4.9179, -7.6560, -10.7711]]
SCREAMING_SNAKE_CASE__: Any= torch.tensor(_lowerCamelCase ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
# class_queries_logits
SCREAMING_SNAKE_CASE__: int= outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
SCREAMING_SNAKE_CASE__: List[str]= torch.tensor(
[[4.7188, -3.2585, -2.8857], [6.6871, -2.9181, -1.2487], [7.2449, -2.2764, -2.1874]] ).to(_lowerCamelCase )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) )
def UpperCamelCase_ ( self ) -> List[str]:
SCREAMING_SNAKE_CASE__: int= (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
.to(_lowerCamelCase )
.eval()
)
SCREAMING_SNAKE_CASE__: Any= self.default_image_processor
SCREAMING_SNAKE_CASE__: int= image_processor(
[np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors='''pt''' , )
SCREAMING_SNAKE_CASE__: Dict= inputs['''pixel_values'''].to(_lowerCamelCase )
SCREAMING_SNAKE_CASE__: Dict= [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']]
SCREAMING_SNAKE_CASE__: str= [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']]
with torch.no_grad():
SCREAMING_SNAKE_CASE__: int= model(**_lowerCamelCase )
self.assertTrue(outputs.loss is not None )
| 64 |
"""simple docstring"""
from typing import Callable, Optional, Union
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_lowerCamelCase = logging.get_logger(__name__)
_lowerCamelCase = {
'''microsoft/xprophetnet-large-wiki100-cased''': (
'''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json'''
),
}
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = '''xlm-prophetnet'''
lowerCamelCase__ = ['''past_key_values''']
lowerCamelCase__ = {
'''num_attention_heads''': '''num_encoder_attention_heads''',
}
def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size
__SCREAMING_SNAKE_CASE : Optional[int] = hidden_size
__SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim
__SCREAMING_SNAKE_CASE : str = num_encoder_layers
__SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads
__SCREAMING_SNAKE_CASE : str = decoder_ffn_dim
__SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers
__SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads
__SCREAMING_SNAKE_CASE : Dict = max_position_embeddings
__SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter)
__SCREAMING_SNAKE_CASE : Any = activation_function
# parameters for xlmprophetnet
__SCREAMING_SNAKE_CASE : List[Any] = ngram
__SCREAMING_SNAKE_CASE : int = num_buckets
__SCREAMING_SNAKE_CASE : List[str] = relative_max_distance
__SCREAMING_SNAKE_CASE : str = disable_ngram_loss
__SCREAMING_SNAKE_CASE : Optional[int] = eps
# 3 Types of Dropout
__SCREAMING_SNAKE_CASE : int = attention_dropout
__SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout
__SCREAMING_SNAKE_CASE : Dict = dropout
__SCREAMING_SNAKE_CASE : Any = use_cache
super().__init__(
pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , )
@property
def SCREAMING_SNAKE_CASE_ ( self :int ):
return self.num_encoder_layers + self.num_decoder_layers
@num_hidden_layers.setter
def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ):
raise NotImplementedError(
'''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and'''
''' `num_decoder_layers`.''' )
| 674 | 0 |
def lowercase_ ( _UpperCamelCase = 4_00_00_00 ):
'''simple docstring'''
__lowercase = []
__lowercase = 0, 1
while b <= n:
if b % 2 == 0:
even_fibs.append(lowercase_ )
__lowercase = b, a + b
return sum(lowercase_ )
if __name__ == "__main__":
print(f'''{solution() = }''')
| 639 |
"""simple docstring"""
import ast
import os
import re
import shutil
import tempfile
import unittest
from unittest import mock
import torch
from accelerate.test_utils.examples import compare_against_test
from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow
from accelerate.utils import write_basic_config
# DataLoaders built from `test_samples/MRPC` for quick testing
# Should mock `{script_name}.get_dataloaders` via:
# @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders)
_lowerCamelCase = [
'''cross_validation.py''',
'''gradient_accumulation.py''',
'''local_sgd.py''',
'''multi_process_metrics.py''',
'''memory.py''',
'''automatic_gradient_accumulation.py''',
'''fsdp_with_peak_mem_tracking.py''',
'''deepspeed_with_config_support.py''',
'''megatron_lm_gpt_pretraining.py''',
]
class snake_case ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ):
__SCREAMING_SNAKE_CASE : List[str] = None
__SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) )
__SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' )
for item in os.listdir(_lowerCamelCase ):
if item not in EXCLUDE_EXAMPLES:
__SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase )
if os.path.isfile(_lowerCamelCase ) and ".py" in item_path:
with self.subTest(
tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ):
__SCREAMING_SNAKE_CASE : Tuple = compare_against_test(
os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase )
if special_strings is not None:
for string in special_strings:
__SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' )
self.assertEqual(_lowerCamelCase , '''''' )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase )
self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) )
__SCREAMING_SNAKE_CASE : Optional[int] = [
''' ''' * 1_6 + '''{\n\n''',
''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''',
''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''',
''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''',
''' ''' * 2_0 + '''"epoch": epoch,\n\n''',
''' ''' * 1_6 + '''},\n\n''',
''' ''' * 1_6 + '''step=epoch,\n''',
''' ''' * 1_2,
''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''',
]
self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
@mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} )
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = False
@classmethod
def SCREAMING_SNAKE_CASE_ ( cls :Dict ):
super().setUpClass()
__SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp()
__SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' )
write_basic_config(save_location=cls.configPath )
__SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath]
@classmethod
def SCREAMING_SNAKE_CASE_ ( cls :Dict ):
super().tearDownClass()
shutil.rmtree(cls._tmpdir )
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
__SCREAMING_SNAKE_CASE : str = f'''
examples/by_feature/checkpointing.py
--checkpointing_steps epoch
--output_dir {self.tmpdir}
'''.split()
run_command(self._launch_args + testargs )
self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
__SCREAMING_SNAKE_CASE : Optional[Any] = f'''
examples/by_feature/checkpointing.py
--checkpointing_steps 1
--output_dir {self.tmpdir}
'''.split()
__SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs )
self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
__SCREAMING_SNAKE_CASE : Optional[int] = f'''
examples/by_feature/checkpointing.py
--resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )}
'''.split()
__SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase )
self.assertNotIn('''epoch 0:''' , _lowerCamelCase )
self.assertIn('''epoch 1:''' , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Optional[int] = f'''
examples/by_feature/checkpointing.py
--resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )}
'''.split()
__SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase )
if torch.cuda.is_available():
__SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count()
else:
__SCREAMING_SNAKE_CASE : Optional[int] = 1
if num_processes > 1:
self.assertNotIn('''epoch 0:''' , _lowerCamelCase )
self.assertIn('''epoch 1:''' , _lowerCamelCase )
else:
self.assertIn('''epoch 0:''' , _lowerCamelCase )
self.assertIn('''epoch 1:''' , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE : Optional[Any] = '''
examples/by_feature/cross_validation.py
--num_folds 2
'''.split()
with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1]
__SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase )
self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 )
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py''']
run_command(self._launch_args + testargs )
@require_trackers
@mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} )
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
with tempfile.TemporaryDirectory() as tmpdir:
__SCREAMING_SNAKE_CASE : int = f'''
examples/by_feature/tracking.py
--with_tracking
--project_dir {tmpdir}
'''.split()
run_command(self._launch_args + testargs )
self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py''']
run_command(self._launch_args + testargs )
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
__SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py''']
run_command(self._launch_args + testargs )
| 674 | 0 |
import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch
import numpy as np
import pytest
from absl.testing import parameterized
import datasets
from datasets import load_metric
from .utils import for_all_test_methods, local, slow
# mark all tests as integration
UpperCAmelCase_ = pytest.mark.integration
UpperCAmelCase_ = {'''comet'''}
UpperCAmelCase_ = importlib.util.find_spec('''fairseq''') is not None
UpperCAmelCase_ = {'''code_eval'''}
UpperCAmelCase_ = os.name == '''nt'''
UpperCAmelCase_ = {'''bertscore''', '''frugalscore''', '''perplexity'''}
UpperCAmelCase_ = importlib.util.find_spec('''transformers''') is not None
def lowerCAmelCase_ ( lowercase: Tuple ) -> Dict:
'''simple docstring'''
@wraps(lowercase_ )
def wrapper(self: Optional[Any] , lowercase: Dict ):
if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
self.skipTest('''"test requires Fairseq"''' )
else:
test_case(self , lowercase_ )
return wrapper
def lowerCAmelCase_ ( lowercase: int ) -> Tuple:
'''simple docstring'''
@wraps(lowercase_ )
def wrapper(self: List[Any] , lowercase: str ):
if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
self.skipTest('''"test requires transformers"''' )
else:
test_case(self , lowercase_ )
return wrapper
def lowerCAmelCase_ ( lowercase: Any ) -> str:
'''simple docstring'''
@wraps(lowercase_ )
def wrapper(self: List[str] , lowercase: Union[str, Any] ):
if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
self.skipTest('''"test not supported on Windows"''' )
else:
test_case(self , lowercase_ )
return wrapper
def lowerCAmelCase_ ( ) -> Any:
'''simple docstring'''
_UpperCamelCase: Any = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob('''./metrics/*/''' )]
return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished
@parameterized.named_parameters(get_local_metric_names() )
@for_all_test_methods(
__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
@local
class __magic_name__ ( parameterized.TestCase ):
"""simple docstring"""
lowerCAmelCase : Tuple = {}
lowerCAmelCase : List[str] = None
@pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning''' )
@pytest.mark.filterwarnings('''ignore:load_metric is deprecated:FutureWarning''' )
def lowerCAmelCase ( self : Tuple , _lowercase : Optional[int] ):
"""simple docstring"""
_UpperCamelCase: Dict = '''[...]'''
_UpperCamelCase: Optional[int] = importlib.import_module(
datasets.load.metric_module_factory(os.path.join('''metrics''' , _lowerCamelCase ) ).module_path )
_UpperCamelCase: List[str] = datasets.load.import_main_class(metric_module.__name__ , dataset=_lowerCamelCase )
# check parameters
_UpperCamelCase: int = inspect.signature(metric._compute ).parameters
self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs
# run doctest
with self.patch_intensive_calls(_lowerCamelCase , metric_module.__name__ ):
with self.use_local_metrics():
try:
_UpperCamelCase: Tuple = doctest.testmod(_lowerCamelCase , verbose=_lowerCamelCase , raise_on_error=_lowerCamelCase )
except doctest.UnexpectedException as e:
raise e.exc_info[1] # raise the exception that doctest caught
self.assertEqual(results.failed , 0 )
self.assertGreater(results.attempted , 1 )
@slow
def lowerCAmelCase ( self : str , _lowercase : Union[str, Any] ):
"""simple docstring"""
_UpperCamelCase: List[Any] = '''[...]'''
_UpperCamelCase: List[Any] = importlib.import_module(
datasets.load.metric_module_factory(os.path.join('''metrics''' , _lowerCamelCase ) ).module_path )
# run doctest
with self.use_local_metrics():
_UpperCamelCase: Any = doctest.testmod(_lowerCamelCase , verbose=_lowerCamelCase , raise_on_error=_lowerCamelCase )
self.assertEqual(results.failed , 0 )
self.assertGreater(results.attempted , 1 )
@contextmanager
def lowerCAmelCase ( self : List[Any] , _lowercase : str , _lowercase : Optional[Any] ):
"""simple docstring"""
if metric_name in self.INTENSIVE_CALLS_PATCHER:
with self.INTENSIVE_CALLS_PATCHER[metric_name](_lowerCamelCase ):
yield
else:
yield
@contextmanager
def lowerCAmelCase ( self : Any ):
"""simple docstring"""
def load_local_metric(_lowercase : Optional[Any] , *_lowercase : Dict , **_lowercase : Optional[Any] ):
return load_metric(os.path.join('''metrics''' , _lowerCamelCase ) , *_lowerCamelCase , **_lowerCamelCase )
with patch('''datasets.load_metric''' ) as mock_load_metric:
_UpperCamelCase: Optional[Any] = load_local_metric
yield
@classmethod
def lowerCAmelCase ( cls : List[str] , _lowercase : Tuple ):
"""simple docstring"""
def wrapper(_lowercase : Union[str, Any] ):
_UpperCamelCase: Tuple = contextmanager(_lowerCamelCase )
_UpperCamelCase: List[str] = patcher
return patcher
return wrapper
@LocalMetricTest.register_intensive_calls_patcher('''bleurt''' )
def lowerCAmelCase_ ( lowercase: List[str] ) -> int:
'''simple docstring'''
import tensorflow.compat.va as tf
from bleurt.score import Predictor
tf.flags.DEFINE_string('''sv''' , '''''' , '''''' ) # handle pytest cli flags
class __magic_name__ ( __UpperCAmelCase ):
"""simple docstring"""
def lowerCAmelCase ( self : Optional[Any] , _lowercase : Optional[int] ):
"""simple docstring"""
assert len(input_dict['''input_ids'''] ) == 2
return np.array([1.03, 1.04] )
# mock predict_fn which is supposed to do a forward pass with a bleurt model
with patch('''bleurt.score._create_predictor''' ) as mock_create_predictor:
_UpperCamelCase: Dict = MockedPredictor()
yield
@LocalMetricTest.register_intensive_calls_patcher('''bertscore''' )
def lowerCAmelCase_ ( lowercase: Optional[int] ) -> List[str]:
'''simple docstring'''
import torch
def bert_cos_score_idf(lowercase: Optional[Any] , lowercase: Any , *lowercase: int , **lowercase: List[str] ):
return torch.tensor([[1.0, 1.0, 1.0]] * len(lowercase_ ) )
# mock get_model which is supposed to do download a bert model
# mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
with patch('''bert_score.scorer.get_model''' ), patch(
'''bert_score.scorer.bert_cos_score_idf''' ) as mock_bert_cos_score_idf:
_UpperCamelCase: List[str] = bert_cos_score_idf
yield
@LocalMetricTest.register_intensive_calls_patcher('''comet''' )
def lowerCAmelCase_ ( lowercase: Optional[int] ) -> Optional[Any]:
'''simple docstring'''
def load_from_checkpoint(lowercase: Tuple ):
class __magic_name__ :
"""simple docstring"""
def lowerCAmelCase ( self : Optional[Any] , _lowercase : int , *_lowercase : List[str] , **_lowercase : List[str] ):
"""simple docstring"""
assert len(_lowerCamelCase ) == 2
_UpperCamelCase: int = [0.19, 0.92]
return scores, sum(_lowerCamelCase ) / len(_lowerCamelCase )
return Model()
# mock load_from_checkpoint which is supposed to do download a bert model
# mock load_from_checkpoint which is supposed to do download a bert model
with patch('''comet.download_model''' ) as mock_download_model:
_UpperCamelCase: str = None
with patch('''comet.load_from_checkpoint''' ) as mock_load_from_checkpoint:
_UpperCamelCase: Tuple = load_from_checkpoint
yield
def lowerCAmelCase_ ( ) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase: int = load_metric(os.path.join('''metrics''' , '''seqeval''' ) )
_UpperCamelCase: List[str] = '''ERROR'''
_UpperCamelCase: Union[str, Any] = F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}"""
with pytest.raises(lowercase_ , match=re.escape(lowercase_ ) ):
metric.compute(predictions=[] , references=[] , scheme=lowercase_ ) | 271 |
"""simple docstring"""
import argparse
import logging
import os
import time
import timeit
import datasets
import numpy as np
import pycuda.autoinit # noqa: F401
import pycuda.driver as cuda
import tensorrt as trt
import torch
from absl import logging as absl_logging
from accelerate import Accelerator
from datasets import load_dataset, load_metric
from torch.utils.data import DataLoader
from utils_qa import postprocess_qa_predictions
import transformers
from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed
from transformers.trainer_pt_utils import nested_concat, nested_truncate
_lowerCamelCase = trt.Logger(trt.Logger.WARNING)
_lowerCamelCase = absl_logging.get_absl_logger()
absl_logger.setLevel(logging.WARNING)
_lowerCamelCase = logging.getLogger(__name__)
_lowerCamelCase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--onnx_model_path''',
default=None,
type=str,
required=True,
help='''Path to ONNX model: ''',
)
parser.add_argument(
'''--output_dir''',
default=None,
type=str,
required=True,
help='''The output directory where the model checkpoints and predictions will be written.''',
)
# Other parameters
parser.add_argument(
'''--tokenizer_name''',
default='''''',
type=str,
required=True,
help='''Pretrained tokenizer name or path if not the same as model_name''',
)
parser.add_argument(
'''--version_2_with_negative''',
action='''store_true''',
help='''If true, the SQuAD examples contain some that do not have an answer.''',
)
parser.add_argument(
'''--null_score_diff_threshold''',
type=float,
default=0.0,
help='''If null_score - best_non_null is greater than the threshold predict null.''',
)
parser.add_argument(
'''--max_seq_length''',
default=3_84,
type=int,
help=(
'''The maximum total input sequence length after WordPiece tokenization. Sequences '''
'''longer than this will be truncated, and sequences shorter than this will be padded.'''
),
)
parser.add_argument(
'''--doc_stride''',
default=1_28,
type=int,
help='''When splitting up a long document into chunks, how much stride to take between chunks.''',
)
parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''')
parser.add_argument(
'''--n_best_size''',
default=20,
type=int,
help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''',
)
parser.add_argument(
'''--max_answer_length''',
default=30,
type=int,
help=(
'''The maximum length of an answer that can be generated. This is needed because the start '''
'''and end predictions are not conditioned on one another.'''
),
)
parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''')
parser.add_argument(
'''--dataset_name''',
type=str,
default=None,
required=True,
help='''The name of the dataset to use (via the datasets library).''',
)
parser.add_argument(
'''--dataset_config_name''',
type=str,
default=None,
help='''The configuration name of the dataset to use (via the datasets library).''',
)
parser.add_argument(
'''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.'''
)
parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''')
parser.add_argument(
'''--fp16''',
action='''store_true''',
help='''Whether to use 16-bit (mixed) precision instead of 32-bit''',
)
parser.add_argument(
'''--int8''',
action='''store_true''',
help='''Whether to use INT8''',
)
_lowerCamelCase = parser.parse_args()
if args.tokenizer_name:
_lowerCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True)
else:
raise ValueError(
'''You are instantiating a new tokenizer from scratch. This is not supported by this script.'''
'''You can do it from another script, save it, and load it from here, using --tokenizer_name.'''
)
logger.info('''Training/evaluation parameters %s''', args)
_lowerCamelCase = args.per_device_eval_batch_size
_lowerCamelCase = (args.eval_batch_size, args.max_seq_length)
# TRT Engine properties
_lowerCamelCase = True
_lowerCamelCase = '''temp_engine/bert-fp32.engine'''
if args.fpaa:
_lowerCamelCase = '''temp_engine/bert-fp16.engine'''
if args.inta:
_lowerCamelCase = '''temp_engine/bert-int8.engine'''
# import ONNX file
if not os.path.exists('''temp_engine'''):
os.makedirs('''temp_engine''')
_lowerCamelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser(
network, TRT_LOGGER
) as parser:
with open(args.onnx_model_path, '''rb''') as model:
if not parser.parse(model.read()):
for error in range(parser.num_errors):
print(parser.get_error(error))
# Query input names and shapes from parsed TensorRT network
_lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)]
_lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"]
with builder.create_builder_config() as config:
_lowerCamelCase = 1 << 50
if STRICT_TYPES:
config.set_flag(trt.BuilderFlag.STRICT_TYPES)
if args.fpaa:
config.set_flag(trt.BuilderFlag.FPaa)
if args.inta:
config.set_flag(trt.BuilderFlag.INTa)
_lowerCamelCase = builder.create_optimization_profile()
config.add_optimization_profile(profile)
for i in range(len(input_names)):
profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE)
_lowerCamelCase = builder.build_engine(network, config)
# serialize_engine and store in file (can be directly loaded and deserialized):
with open(engine_name, '''wb''') as f:
f.write(engine.serialize())
def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa )
__SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa )
# Copy inputs
cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase_ )
cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase_ )
cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase_ )
# start time
__SCREAMING_SNAKE_CASE : Tuple = time.time()
# Run inference
context.execute_async(
bindings=[int(lowercase_ ) for d_inp in d_inputs] + [int(lowercase_ ), int(lowercase_ )] , stream_handle=stream.handle )
# Transfer predictions back from GPU
cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ )
cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ )
# Synchronize the stream and take time
stream.synchronize()
# end time
__SCREAMING_SNAKE_CASE : List[str] = time.time()
__SCREAMING_SNAKE_CASE : int = end_time - start_time
__SCREAMING_SNAKE_CASE : int = (h_outputa, h_outputa)
# print(outputs)
return outputs, infer_time
# Initialize the accelerator. We will let the accelerator handle device placement for us in this example.
_lowerCamelCase = Accelerator()
# Make one log on every process with the configuration for debugging.
logging.basicConfig(
format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''',
datefmt='''%m/%d/%Y %H:%M:%S''',
level=logging.INFO,
)
# Setup logging, we only want one process per machine to log things on the screen.
# accelerator.is_local_main_process is only True for one process per machine.
logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR)
if accelerator.is_local_main_process:
datasets.utils.logging.set_verbosity_warning()
transformers.utils.logging.set_verbosity_info()
else:
datasets.utils.logging.set_verbosity_error()
transformers.utils.logging.set_verbosity_error()
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
# (the dataset will be downloaded automatically from the datasets Hub).
#
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
# 'text' is found. You can easily tweak this behavior (see below).
if args.dataset_name is not None:
# Downloading and loading a dataset from the hub.
_lowerCamelCase = load_dataset(args.dataset_name, args.dataset_config_name)
else:
raise ValueError('''Evaluation requires a dataset name''')
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
# Preprocessing the datasets.
# Preprocessing is slighlty different for training and evaluation.
_lowerCamelCase = raw_datasets['''validation'''].column_names
_lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0]
_lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1]
_lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2]
# Padding side determines if we do (question|context) or (context|question).
_lowerCamelCase = tokenizer.padding_side == '''right'''
if args.max_seq_length > tokenizer.model_max_length:
logger.warning(
f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the'
f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.'
)
_lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length)
def lowerCAmelCase_ ( lowercase_ : Tuple ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = [q.lstrip() for q in examples[question_column_name]]
# Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results
# in one example possible giving several features when a context is long, each of those features having a
# context that overlaps a bit the context of the previous feature.
__SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer(
examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=lowercase_ , stride=args.doc_stride , return_overflowing_tokens=lowercase_ , return_offsets_mapping=lowercase_ , padding='''max_length''' , )
# Since one example might give us several features if it has a long context, we need a map from a feature to
# its corresponding example. This key gives us just that.
__SCREAMING_SNAKE_CASE : Optional[int] = tokenized_examples.pop('''overflow_to_sample_mapping''' )
# For evaluation, we will need to convert our predictions to substrings of the context, so we keep the
# corresponding example_id and we will store the offset mappings.
__SCREAMING_SNAKE_CASE : Any = []
for i in range(len(tokenized_examples['''input_ids'''] ) ):
# Grab the sequence corresponding to that example (to know what is the context and what is the question).
__SCREAMING_SNAKE_CASE : int = tokenized_examples.sequence_ids(lowercase_ )
__SCREAMING_SNAKE_CASE : str = 1 if pad_on_right else 0
# One example can give several spans, this is the index of the example containing this span of text.
__SCREAMING_SNAKE_CASE : str = sample_mapping[i]
tokenized_examples["example_id"].append(examples['''id'''][sample_index] )
# Set to None the offset_mapping that are not part of the context so it's easy to determine if a token
# position is part of the context or not.
__SCREAMING_SNAKE_CASE : List[str] = [
(o if sequence_ids[k] == context_index else None)
for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] )
]
return tokenized_examples
_lowerCamelCase = raw_datasets['''validation''']
# Validation Feature Creation
_lowerCamelCase = eval_examples.map(
prepare_validation_features,
batched=True,
num_proc=args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not args.overwrite_cache,
desc='''Running tokenizer on validation dataset''',
)
_lowerCamelCase = default_data_collator
_lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping'''])
_lowerCamelCase = DataLoader(
eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size
)
def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Tuple = postprocess_qa_predictions(
examples=lowercase_ , features=lowercase_ , predictions=lowercase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase_ , )
# Format the result to the format the metric expects.
if args.version_2_with_negative:
__SCREAMING_SNAKE_CASE : Union[str, Any] = [
{'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items()
]
else:
__SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()]
__SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples]
return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ )
_lowerCamelCase = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''')
# Evaluation!
logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path)
with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine(
f.read()
) as engine, engine.create_execution_context() as context:
# setup for TRT inferrence
for i in range(len(input_names)):
context.set_binding_shape(i, INPUT_SHAPE)
assert context.all_binding_shapes_specified
def lowerCAmelCase_ ( lowercase_ : Any ):
'''simple docstring'''
return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize
# Allocate device memory for inputs and outputs.
_lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)]
# Allocate output buffer
_lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa)
_lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa)
_lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes)
_lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes)
# Create a stream in which to copy inputs/outputs and run inference.
_lowerCamelCase = cuda.Stream()
# Evaluation
logger.info('''***** Running Evaluation *****''')
logger.info(f' Num examples = {len(eval_dataset)}')
logger.info(f' Batch size = {args.per_device_eval_batch_size}')
_lowerCamelCase = 0.0
_lowerCamelCase = 0
_lowerCamelCase = timeit.default_timer()
_lowerCamelCase = None
for step, batch in enumerate(eval_dataloader):
_lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream)
total_time += infer_time
niter += 1
_lowerCamelCase , _lowerCamelCase = outputs
_lowerCamelCase = torch.tensor(start_logits)
_lowerCamelCase = torch.tensor(end_logits)
# necessary to pad predictions and labels for being gathered
_lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00)
_lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00)
_lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy())
_lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00)
if all_preds is not None:
_lowerCamelCase = nested_truncate(all_preds, len(eval_dataset))
_lowerCamelCase = timeit.default_timer() - start_time
logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset))
# Inference time from TRT
logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 10_00 / niter))
logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00))
logger.info('''Total Number of Inference = %d''', niter)
_lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds)
_lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids)
logger.info(f'Evaluation metrics: {eval_metric}')
| 674 | 0 |
import re
from flax.core.frozen_dict import freeze
from flax.traverse_util import flatten_dict, unflatten_dict
from jax.experimental import PartitionSpec as P
# Sentinels
_snake_case = object()
# For specifying empty leaf dict `{}`
_snake_case = object()
def __lowerCamelCase ( _lowercase , _lowercase ) -> Any:
UpperCamelCase = tuple((re.compile(x + '$' ) for x in qs) )
for i in range(len(lowercase_ ) - len(lowercase_ ) + 1 ):
UpperCamelCase = [x.match(lowercase_ ) for x, y in zip(lowercase_ , ks[i:] )]
if matches and all(lowercase_ ):
return True
return False
def __lowerCamelCase ( _lowercase ) -> int:
def replace(_lowercase , _lowercase ):
for rule, replacement in rules:
if _match(lowercase_ , lowercase_ ):
return replacement
return val
return replace
def __lowerCamelCase ( ) -> Optional[int]:
return [
# embeddings
(("transformer", "wpe", "embedding"), P('mp' , lowercase_ )),
(("transformer", "wte", "embedding"), P('mp' , lowercase_ )),
# atention
(("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(lowercase_ , 'mp' )),
(("attention", "out_proj", "kernel"), P('mp' , lowercase_ )),
(("attention", "out_proj", "bias"), None),
# mlp
(("mlp", "c_fc", "kernel"), P(lowercase_ , 'mp' )),
(("mlp", "c_fc", "bias"), P('mp' )),
(("mlp", "c_proj", "kernel"), P('mp' , lowercase_ )),
(("mlp", "c_proj", "bias"), None),
# layer norms
((r"ln_\d+", "bias"), None),
((r"\d+", r"ln_\d+", "scale"), None),
(("ln_f", "bias"), None),
(("ln_f", "scale"), None),
]
def __lowerCamelCase ( _lowercase ) -> Optional[Any]:
UpperCamelCase = _get_partition_rules()
UpperCamelCase = _replacement_rules(lowercase_ )
UpperCamelCase = {k: _unmatched for k in flatten_dict(lowercase_ )}
UpperCamelCase = {k: replace(lowercase_ , lowercase_ ) for k, v in initd.items()}
assert _unmatched not in result.values(), "Incomplete partition spec."
return freeze(unflatten_dict(lowercase_ ) )
| 282 |
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import is_tf_available, is_torch_available
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow
if is_tf_available():
from transformers import (
AutoConfig,
BertConfig,
GPTaConfig,
TaConfig,
TFAutoModel,
TFAutoModelForCausalLM,
TFAutoModelForMaskedLM,
TFAutoModelForPreTraining,
TFAutoModelForQuestionAnswering,
TFAutoModelForSeqaSeqLM,
TFAutoModelForSequenceClassification,
TFAutoModelWithLMHead,
TFBertForMaskedLM,
TFBertForPreTraining,
TFBertForQuestionAnswering,
TFBertForSequenceClassification,
TFBertModel,
TFGPTaLMHeadModel,
TFRobertaForMaskedLM,
TFTaForConditionalGeneration,
)
from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST
from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST
from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST
if is_torch_available():
from transformers import (
AutoModel,
AutoModelForCausalLM,
AutoModelForMaskedLM,
AutoModelForPreTraining,
AutoModelForQuestionAnswering,
AutoModelForSeqaSeqLM,
AutoModelForSequenceClassification,
AutoModelWithLMHead,
BertForMaskedLM,
BertForPreTraining,
BertForQuestionAnswering,
BertForSequenceClassification,
BertModel,
GPTaLMHeadModel,
RobertaForMaskedLM,
TaForConditionalGeneration,
)
@is_pt_tf_cross_test
class snake_case ( unittest.TestCase ):
@slow
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
__SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
__SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Any ):
for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :int ):
for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained(
_lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
@slow
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
__SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
__SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase )
self.assertIsInstance(_lowerCamelCase , _lowerCamelCase )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
| 674 | 0 |
"""simple docstring"""
import contextlib
import importlib
import io
import unittest
import transformers
# Try to import everything from transformers to ensure every object can be loaded.
from transformers import * # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available
if is_torch_available():
from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification
if is_tf_available():
from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification
if is_flax_available():
from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification
a_ : str = DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co
a_ : Optional[Any] = '''main'''
# Default branch name
a_ : int = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'''
# One particular commit (not the top of `main`)
a_ : Any = '''aaaaaaa'''
# This commit does not exist, so we should 404.
a_ : Optional[Any] = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684'''
# Sha-1 of config.json on the top of `main`, for checking purposes
a_ : Optional[Any] = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'''
@contextlib.contextmanager
def UpperCAmelCase ( ) -> Any:
print('Welcome!' )
yield
print('Bye!' )
@contextlib.contextmanager
def UpperCAmelCase ( ) -> List[Any]:
print('Bonjour!' )
yield
print('Au revoir!' )
class __lowercase( unittest.TestCase ):
'''simple docstring'''
def snake_case_ ( self ):
# If the spec is missing, importlib would not be able to import the module dynamically.
assert transformers.__spec__ is not None
assert importlib.util.find_spec('transformers' ) is not None
class __lowercase( unittest.TestCase ):
'''simple docstring'''
@unittest.mock.patch('sys.stdout' , new_callable=io.StringIO )
def snake_case_ ( self , __a ):
with ContextManagers([] ):
print('Transformers are awesome!' )
# The print statement adds a new line at the end of the output
self.assertEqual(mock_stdout.getvalue() , 'Transformers are awesome!\n' )
@unittest.mock.patch('sys.stdout' , new_callable=io.StringIO )
def snake_case_ ( self , __a ):
with ContextManagers([context_en()] ):
print('Transformers are awesome!' )
# The output should be wrapped with an English welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , 'Welcome!\nTransformers are awesome!\nBye!\n' )
@unittest.mock.patch('sys.stdout' , new_callable=io.StringIO )
def snake_case_ ( self , __a ):
with ContextManagers([context_fr(), context_en()] ):
print('Transformers are awesome!' )
# The output should be wrapped with an English and French welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , 'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n' )
@require_torch
def snake_case_ ( self ):
self.assertEqual(find_labels(_lowerCamelCase ) , ['labels'] )
self.assertEqual(find_labels(_lowerCamelCase ) , ['labels', 'next_sentence_label'] )
self.assertEqual(find_labels(_lowerCamelCase ) , ['start_positions', 'end_positions'] )
class __lowercase( __UpperCAmelCase ):
'''simple docstring'''
pass
self.assertEqual(find_labels(_lowerCamelCase ) , ['labels'] )
@require_tf
def snake_case_ ( self ):
self.assertEqual(find_labels(_lowerCamelCase ) , ['labels'] )
self.assertEqual(find_labels(_lowerCamelCase ) , ['labels', 'next_sentence_label'] )
self.assertEqual(find_labels(_lowerCamelCase ) , ['start_positions', 'end_positions'] )
class __lowercase( __UpperCAmelCase ):
'''simple docstring'''
pass
self.assertEqual(find_labels(_lowerCamelCase ) , ['labels'] )
@require_flax
def snake_case_ ( self ):
# Flax models don't have labels
self.assertEqual(find_labels(_lowerCamelCase ) , [] )
self.assertEqual(find_labels(_lowerCamelCase ) , [] )
self.assertEqual(find_labels(_lowerCamelCase ) , [] )
class __lowercase( __UpperCAmelCase ):
'''simple docstring'''
pass
self.assertEqual(find_labels(_lowerCamelCase ) , [] )
| 594 |
"""simple docstring"""
import os
import re
import warnings
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
if TYPE_CHECKING:
from ...tokenization_utils_base import TextInput
from ...utils import logging
_lowerCamelCase = logging.get_logger(__name__)
_lowerCamelCase = {'''vocab_file''': '''spiece.model'''}
_lowerCamelCase = {
'''vocab_file''': {
'''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''',
'''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''',
'''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''',
'''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''',
'''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''',
}
}
# TODO(PVP) - this should be removed in Transformers v5
_lowerCamelCase = {
'''t5-small''': 5_12,
'''t5-base''': 5_12,
'''t5-large''': 5_12,
'''t5-3b''': 5_12,
'''t5-11b''': 5_12,
}
_lowerCamelCase = '''▁'''
class snake_case ( __UpperCAmelCase ):
lowerCamelCase__ = VOCAB_FILES_NAMES
lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP
lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowerCamelCase__ = ['''input_ids''', '''attention_mask''']
def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ):
# Add extra_ids to the special token list
if extra_ids > 0 and additional_special_tokens is None:
__SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )]
elif extra_ids > 0 and additional_special_tokens is not None:
# Check that we have the right number of extra_id special tokens
__SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) )
if extra_tokens != extra_ids:
raise ValueError(
f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are'''
''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids'''
''' tokens''' )
if legacy:
logger.warning_once(
f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to'''
''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' )
__SCREAMING_SNAKE_CASE : Optional[Any] = legacy
__SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , )
__SCREAMING_SNAKE_CASE : Tuple = vocab_file
__SCREAMING_SNAKE_CASE : List[str] = extra_ids
__SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(_lowerCamelCase )
@staticmethod
def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ):
if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes:
__SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path]
if init_max_model_length is not None and init_max_model_length != max_model_length:
return init_max_model_length
elif init_max_model_length is None:
warnings.warn(
'''This tokenizer was incorrectly instantiated with a model max length of'''
f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this'''
''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with'''
''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on'''
f''' {pretrained_model_name_or_path} automatically truncating your input to'''
f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences'''
f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with'''
''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please'''
''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , )
return max_model_length
@property
def SCREAMING_SNAKE_CASE_ ( self :Tuple ):
return self.sp_model.get_piece_size() + self._extra_ids
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ):
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase )
# normal case: some special tokens
if token_ids_a is None:
return ([0] * len(_lowerCamelCase )) + [1]
return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1]
def SCREAMING_SNAKE_CASE_ ( self :List[str] ):
return list(
set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()]
def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ):
if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id:
warnings.warn(
f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated'''
''' eos tokens being added.''' )
return token_ids
else:
return token_ids + [self.eos_token_id]
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ):
__SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id]
if token_ids_a is None:
return len(token_ids_a + eos ) * [0]
return len(token_ids_a + eos + token_ids_a + eos ) * [0]
def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ):
__SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase )
if token_ids_a is None:
return token_ids_a
else:
__SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase )
return token_ids_a + token_ids_a
def __getstate__( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Any = self.__dict__.copy()
__SCREAMING_SNAKE_CASE : List[str] = None
return state
def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ):
__SCREAMING_SNAKE_CASE : Tuple = d
# for backward compatibility
if not hasattr(self , '''sp_model_kwargs''' ):
__SCREAMING_SNAKE_CASE : Optional[int] = {}
__SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ):
# Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at
# the beginning of the text
if not self.legacy:
__SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' )
return super().tokenize(_lowerCamelCase , **_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ):
if not self.legacy:
__SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase )
if is_first:
__SCREAMING_SNAKE_CASE : str = text[1:]
__SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase )
if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ):
__SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:]
return tokens
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ):
if token.startswith('''<extra_id_''' ):
__SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) )
return self.vocab_size - num - 1
return self.sp_model.piece_to_id(_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ):
if index < self.sp_model.get_piece_size():
__SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase )
else:
__SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>'''
return token
def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ):
__SCREAMING_SNAKE_CASE : str = []
__SCREAMING_SNAKE_CASE : Dict = ''''''
__SCREAMING_SNAKE_CASE : Dict = False
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
if not prev_is_special:
out_string += " "
out_string += self.sp_model.decode(_lowerCamelCase ) + token
__SCREAMING_SNAKE_CASE : List[str] = True
__SCREAMING_SNAKE_CASE : str = []
else:
current_sub_tokens.append(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = False
out_string += self.sp_model.decode(_lowerCamelCase )
return out_string.strip()
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ):
if not os.path.isdir(_lowerCamelCase ):
logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' )
return
__SCREAMING_SNAKE_CASE : List[str] = os.path.join(
_lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , _lowerCamelCase )
elif not os.path.isfile(self.vocab_file ):
with open(_lowerCamelCase , '''wb''' ) as fi:
__SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto()
fi.write(_lowerCamelCase )
return (out_vocab_file,)
| 674 | 0 |
import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union
import pandas as pd
import pyarrow as pa
import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal
__snake_case = datasets.utils.logging.get_logger(__name__)
__snake_case = ["names", "prefix"]
__snake_case = ["warn_bad_lines", "error_bad_lines", "mangle_dupe_cols"]
__snake_case = ["encoding_errors", "on_bad_lines"]
__snake_case = ["date_format"]
@dataclass
class UpperCAmelCase ( datasets.BuilderConfig ):
lowercase = ""","""
lowercase = None
lowercase = """infer"""
lowercase = None
lowercase = None
lowercase = None
lowercase = None
lowercase = None
lowercase = True
lowercase = None
lowercase = None
lowercase = None
lowercase = None
lowercase = False
lowercase = None
lowercase = None
lowercase = None
lowercase = True
lowercase = True
lowercase = False
lowercase = True
lowercase = None
lowercase = """."""
lowercase = None
lowercase = """\""""
lowercase = 0
lowercase = None
lowercase = None
lowercase = None
lowercase = None
lowercase = True
lowercase = True
lowercase = 0
lowercase = True
lowercase = False
lowercase = None
lowercase = 1_0_0_0_0
lowercase = None
lowercase = """strict"""
lowercase = """error"""
lowercase = None
def lowerCamelCase_ ( self : Tuple ):
"""simple docstring"""
if self.delimiter is not None:
UpperCamelCase = self.delimiter
if self.column_names is not None:
UpperCamelCase = self.column_names
@property
def lowerCamelCase_ ( self : List[Any] ):
"""simple docstring"""
UpperCamelCase = {
'''sep''': self.sep,
'''header''': self.header,
'''names''': self.names,
'''index_col''': self.index_col,
'''usecols''': self.usecols,
'''prefix''': self.prefix,
'''mangle_dupe_cols''': self.mangle_dupe_cols,
'''engine''': self.engine,
'''converters''': self.converters,
'''true_values''': self.true_values,
'''false_values''': self.false_values,
'''skipinitialspace''': self.skipinitialspace,
'''skiprows''': self.skiprows,
'''nrows''': self.nrows,
'''na_values''': self.na_values,
'''keep_default_na''': self.keep_default_na,
'''na_filter''': self.na_filter,
'''verbose''': self.verbose,
'''skip_blank_lines''': self.skip_blank_lines,
'''thousands''': self.thousands,
'''decimal''': self.decimal,
'''lineterminator''': self.lineterminator,
'''quotechar''': self.quotechar,
'''quoting''': self.quoting,
'''escapechar''': self.escapechar,
'''comment''': self.comment,
'''encoding''': self.encoding,
'''dialect''': self.dialect,
'''error_bad_lines''': self.error_bad_lines,
'''warn_bad_lines''': self.warn_bad_lines,
'''skipfooter''': self.skipfooter,
'''doublequote''': self.doublequote,
'''memory_map''': self.memory_map,
'''float_precision''': self.float_precision,
'''chunksize''': self.chunksize,
'''encoding_errors''': self.encoding_errors,
'''on_bad_lines''': self.on_bad_lines,
'''date_format''': self.date_format,
}
# some kwargs must not be passed if they don't have a default value
# some others are deprecated and we can also not pass them if they are the default value
for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , _lowerCamelCase ):
del pd_read_csv_kwargs[pd_read_csv_parameter]
# Remove 2.0 new arguments
if not (datasets.config.PANDAS_VERSION.major >= 2):
for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
del pd_read_csv_kwargs[pd_read_csv_parameter]
# Remove 1.3 new arguments
if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
del pd_read_csv_kwargs[pd_read_csv_parameter]
return pd_read_csv_kwargs
class UpperCAmelCase ( datasets.ArrowBasedBuilder ):
lowercase = CsvConfig
def lowerCamelCase_ ( self : Optional[Any] ):
"""simple docstring"""
return datasets.DatasetInfo(features=self.config.features )
def lowerCamelCase_ ( self : Optional[int] , __magic_name__ : Optional[int] ):
"""simple docstring"""
if not self.config.data_files:
raise ValueError(F'At least one data file must be specified, but got data_files={self.config.data_files}' )
UpperCamelCase = dl_manager.download_and_extract(self.config.data_files )
if isinstance(_lowerCamelCase , (str, list, tuple) ):
UpperCamelCase = data_files
if isinstance(_lowerCamelCase , _lowerCamelCase ):
UpperCamelCase = [files]
UpperCamelCase = [dl_manager.iter_files(_lowerCamelCase ) for file in files]
return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )]
UpperCamelCase = []
for split_name, files in data_files.items():
if isinstance(_lowerCamelCase , _lowerCamelCase ):
UpperCamelCase = [files]
UpperCamelCase = [dl_manager.iter_files(_lowerCamelCase ) for file in files]
splits.append(datasets.SplitGenerator(name=_lowerCamelCase , gen_kwargs={"""files""": files} ) )
return splits
def lowerCamelCase_ ( self : Optional[int] , __magic_name__ : pa.Table ):
"""simple docstring"""
if self.config.features is not None:
UpperCamelCase = self.config.features.arrow_schema
if all(not require_storage_cast(_lowerCamelCase ) for feature in self.config.features.values() ):
# cheaper cast
UpperCamelCase = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=_lowerCamelCase )
else:
# more expensive cast; allows str <-> int/float or str to Audio for example
UpperCamelCase = table_cast(_lowerCamelCase , _lowerCamelCase )
return pa_table
def lowerCamelCase_ ( self : Any , __magic_name__ : str ):
"""simple docstring"""
UpperCamelCase = self.config.features.arrow_schema if self.config.features else None
# dtype allows reading an int column as str
UpperCamelCase = (
{
name: dtype.to_pandas_dtype() if not require_storage_cast(_lowerCamelCase ) else object
for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() )
}
if schema is not None
else None
)
for file_idx, file in enumerate(itertools.chain.from_iterable(_lowerCamelCase ) ):
UpperCamelCase = pd.read_csv(_lowerCamelCase , iterator=_lowerCamelCase , dtype=_lowerCamelCase , **self.config.pd_read_csv_kwargs )
try:
for batch_idx, df in enumerate(_lowerCamelCase ):
UpperCamelCase = pa.Table.from_pandas(_lowerCamelCase )
# Uncomment for debugging (will print the Arrow table size and elements)
# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
yield (file_idx, batch_idx), self._cast_table(_lowerCamelCase )
except ValueError as e:
logger.error(F'Failed to read file \'{file}\' with error {type(_lowerCamelCase )}: {e}' )
raise
| 386 |
"""simple docstring"""
import os
import pytest
import yaml
from datasets.features.features import Features, Value
from datasets.info import DatasetInfo, DatasetInfosDict
@pytest.mark.parametrize(
'''files''' , [
['''full:README.md''', '''dataset_infos.json'''],
['''empty:README.md''', '''dataset_infos.json'''],
['''dataset_infos.json'''],
['''full:README.md'''],
] , )
def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' )
if "full:README.md" in files:
with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f:
f.write('''---\ndataset_info:\n dataset_size: 42\n---''' )
if "empty:README.md" in files:
with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f:
f.write('''''' )
# we want to support dataset_infos.json for backward compatibility
if "dataset_infos.json" in files:
with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f:
f.write('''{"default": {"dataset_size": 42}}''' )
__SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ )
assert dataset_infos
assert dataset_infos["default"].dataset_size == 42
@pytest.mark.parametrize(
'''dataset_info''' , [
DatasetInfo(),
DatasetInfo(
description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ),
] , )
def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ )
dataset_info.write_to_directory(lowercase_ )
__SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ )
assert dataset_info == reloaded
assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) )
def lowerCAmelCase_ ( ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Tuple = DatasetInfo(
description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , )
__SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict()
assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML )
for key in DatasetInfo._INCLUDED_INFO_IN_YAML:
assert key in dataset_info_yaml_dict
assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) )
__SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ )
__SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ )
assert dataset_info_yaml_dict == reloaded
def lowerCAmelCase_ ( ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo()
__SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict()
assert dataset_info_yaml_dict == {}
@pytest.mark.parametrize(
'''dataset_infos_dict''' , [
DatasetInfosDict(),
DatasetInfosDict({'''default''': DatasetInfo()} ),
DatasetInfosDict({'''my_config_name''': DatasetInfo()} ),
DatasetInfosDict(
{
'''default''': DatasetInfo(
description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , )
} ),
DatasetInfosDict(
{
'''v1''': DatasetInfo(dataset_size=42 ),
'''v2''': DatasetInfo(dataset_size=1337 ),
} ),
] , )
def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ )
dataset_infos_dict.write_to_directory(lowercase_ )
__SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ )
# the config_name of the dataset_infos_dict take over the attribute
for config_name, dataset_info in dataset_infos_dict.items():
__SCREAMING_SNAKE_CASE : Optional[int] = config_name
# the yaml representation doesn't include fields like description or citation
# so we just test that we can recover what we can from the yaml
__SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() )
assert dataset_infos_dict == reloaded
if dataset_infos_dict:
assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
| 674 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.