code stringlengths 82 53.2k | code_codestyle int64 0 721 | style_context stringlengths 91 41.9k | style_context_codestyle int64 0 699 | label int64 0 1 |
|---|---|---|---|---|
'''simple docstring'''
lowerCAmelCase : Any = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)]
def _A ( A ) -> int:
lowercase : List[str] = 0
while number:
# Increased Speed Slightly by checking every 5 digits together.
sum_of_digits_squared += DIGITS_SQUARED[number % 1_0_0_0_0_0]
number //= 1_0_0_0_0_0
return sum_of_digits_squared
# There are 2 Chains made,
# One ends with 89 with the chain member 58 being the one which when declared first,
# there will be the least number of iterations for all the members to be checked.
# The other one ends with 1 and has only one element 1.
# So 58 and 1 are chosen to be declared at the starting.
# Changed dictionary to an array to quicken the solution
lowerCAmelCase : Any = [None] * 1_0_0_0_0_0_0_0
lowerCAmelCase : Union[str, Any] = True
lowerCAmelCase : Any = False
def _A ( A ) -> bool:
if CHAINS[number - 1] is not None:
return CHAINS[number - 1] # type: ignore
lowercase : Union[str, Any] = chain(next_number(_lowerCamelCase ) )
lowercase : str = number_chain
while number < 1_0_0_0_0_0_0_0:
lowercase : Tuple = number_chain
number *= 1_0
return number_chain
def _A ( A = 1_0_0_0_0_0_0_0 ) -> int:
for i in range(1 ,_lowerCamelCase ):
if CHAINS[i] is None:
chain(i + 1 )
return CHAINS[:number].count(_lowerCamelCase )
if __name__ == "__main__":
import doctest
doctest.testmod()
print(F'''{solution() = }''')
| 372 |
"""simple docstring"""
import warnings
from ...utils import logging
from .image_processing_mobilevit import MobileViTImageProcessor
UpperCAmelCase = logging.get_logger(__name__)
class lowercase ( lowercase__ ):
def __init__(self : Dict ,*SCREAMING_SNAKE_CASE_ : str ,**SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> None:
"""simple docstring"""
warnings.warn(
'''The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.'''
''' Please use MobileViTImageProcessor instead.''' ,SCREAMING_SNAKE_CASE_ ,)
super().__init__(*SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ )
| 535 | 0 |
'''simple docstring'''
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available
from transformers.models.bert.tokenization_bert import BertTokenizer
from transformers.testing_utils import require_tensorflow_text, require_tf, slow
if is_tf_available():
import tensorflow as tf
if is_tensorflow_text_available():
from transformers.models.bert import TFBertTokenizer
a__ : int = ['bert-base-uncased', 'bert-base-cased']
a__ : Dict = 'hf-internal-testing/tiny-bert-tf-only'
if is_tf_available():
class lowercase_ ( tf.keras.Model ):
def __init__( self , a ):
super().__init__()
UpperCamelCase__ = tokenizer
UpperCamelCase__ = AutoConfig.from_pretrained(a )
UpperCamelCase__ = TFAutoModel.from_config(a )
def __a ( self , a ):
UpperCamelCase__ = self.tokenizer(a )
UpperCamelCase__ = self.bert(**a )
return out["pooler_output"]
@require_tf
@require_tensorflow_text
class lowercase_ ( unittest.TestCase ):
def __a ( self ):
super().setUp()
UpperCamelCase__ = [
BertTokenizer.from_pretrained(a ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2)
] # repeat for when fast_bert_tokenizer=false
UpperCamelCase__ = [TFBertTokenizer.from_pretrained(a ) for checkpoint in TOKENIZER_CHECKPOINTS] + [
TFBertTokenizer.from_pretrained(a , use_fast_bert_tokenizer=a )
for checkpoint in TOKENIZER_CHECKPOINTS
]
assert len(self.tokenizers ) == len(self.tf_tokenizers )
UpperCamelCase__ = [
"This is a straightforward English test sentence.",
"This one has some weird characters\rto\nsee\r\nif those\u00E9break things.",
"Now we're going to add some Chinese: 一 二 三 一二三",
"And some much more rare Chinese: 齉 堃 齉堃",
"Je vais aussi écrire en français pour tester les accents",
"Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ",
]
UpperCamelCase__ = list(zip(self.test_sentences , self.test_sentences[::-1] ) )
def __a ( self ):
for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ):
for test_inputs in (self.test_sentences, self.paired_sentences):
UpperCamelCase__ = tokenizer(a , return_tensors="tf" , padding="longest" )
UpperCamelCase__ = tf_tokenizer(a )
for key in python_outputs.keys():
self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) )
self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) )
@slow
def __a ( self ):
for tf_tokenizer in self.tf_tokenizers:
UpperCamelCase__ = tf_tokenizer(self.paired_sentences )
UpperCamelCase__ = tf_tokenizer(
text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , )
for key in merged_outputs.keys():
self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) )
@slow
def __a ( self ):
for tf_tokenizer in self.tf_tokenizers:
UpperCamelCase__ = tf.function(a )
for test_inputs in (self.test_sentences, self.paired_sentences):
UpperCamelCase__ = tf.constant(a )
UpperCamelCase__ = compiled_tokenizer(a )
UpperCamelCase__ = tf_tokenizer(a )
for key in eager_outputs.keys():
self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) )
@slow
def __a ( self ):
for tf_tokenizer in self.tf_tokenizers:
UpperCamelCase__ = ModelToSave(tokenizer=a )
UpperCamelCase__ = tf.convert_to_tensor(self.test_sentences )
UpperCamelCase__ = model(a ) # Build model with some sample inputs
with TemporaryDirectory() as tempdir:
UpperCamelCase__ = Path(a ) / "saved.model"
model.save(a )
UpperCamelCase__ = tf.keras.models.load_model(a )
UpperCamelCase__ = loaded_model(a )
# We may see small differences because the loaded model is compiled, so we need an epsilon for the test
self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1e-5 )
| 717 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
is_vision_available,
)
a__ : Optional[int] = {
'configuration_owlvit': [
'OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP',
'OwlViTConfig',
'OwlViTOnnxConfig',
'OwlViTTextConfig',
'OwlViTVisionConfig',
],
'processing_owlvit': ['OwlViTProcessor'],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a__ : Dict = ['OwlViTFeatureExtractor']
a__ : Tuple = ['OwlViTImageProcessor']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a__ : Dict = [
'OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST',
'OwlViTModel',
'OwlViTPreTrainedModel',
'OwlViTTextModel',
'OwlViTVisionModel',
'OwlViTForObjectDetection',
]
if TYPE_CHECKING:
from .configuration_owlvit import (
OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP,
OwlViTConfig,
OwlViTOnnxConfig,
OwlViTTextConfig,
OwlViTVisionConfig,
)
from .processing_owlvit import OwlViTProcessor
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_owlvit import OwlViTFeatureExtractor
from .image_processing_owlvit import OwlViTImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_owlvit import (
OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
OwlViTForObjectDetection,
OwlViTModel,
OwlViTPreTrainedModel,
OwlViTTextModel,
OwlViTVisionModel,
)
else:
import sys
a__ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 223 | 0 |
'''simple docstring'''
import unittest
from transformers import load_tool
from .test_tools_common import ToolTesterMixin
class _lowerCAmelCase ( unittest.TestCase , A__ ):
"""simple docstring"""
def lowerCAmelCase ( self : List[str] )-> int:
snake_case = load_tool("""text-classification""" )
self.tool.setup()
snake_case = load_tool("""text-classification""" , remote=__snake_case )
def lowerCAmelCase ( self : int )-> Optional[Any]:
snake_case = self.tool("""That's quite cool""" , ["""positive""", """negative"""] )
self.assertEqual(__snake_case , """positive""" )
def lowerCAmelCase ( self : Dict )-> Optional[int]:
snake_case = self.remote_tool("""That's quite cool""" , ["""positive""", """negative"""] )
self.assertEqual(__snake_case , """positive""" )
def lowerCAmelCase ( self : Optional[int] )-> Union[str, Any]:
snake_case = self.tool(text="""That's quite cool""" , labels=["""positive""", """negative"""] )
self.assertEqual(__snake_case , """positive""" )
def lowerCAmelCase ( self : str )-> Any:
snake_case = self.remote_tool(text="""That's quite cool""" , labels=["""positive""", """negative"""] )
self.assertEqual(__snake_case , """positive""" )
| 369 |
'''simple docstring'''
from __future__ import annotations
def __lowerCamelCase ( __lowerCAmelCase : float , __lowerCAmelCase : float , __lowerCAmelCase : float ) -> float:
if days_between_payments <= 0:
raise ValueError("""days_between_payments must be > 0""" )
if daily_interest_rate < 0:
raise ValueError("""daily_interest_rate must be >= 0""" )
if principal <= 0:
raise ValueError("""principal must be > 0""" )
return principal * daily_interest_rate * days_between_payments
def __lowerCamelCase ( __lowerCAmelCase : float , __lowerCAmelCase : float , __lowerCAmelCase : float , ) -> float:
if number_of_compounding_periods <= 0:
raise ValueError("""number_of_compounding_periods must be > 0""" )
if nominal_annual_interest_rate_percentage < 0:
raise ValueError("""nominal_annual_interest_rate_percentage must be >= 0""" )
if principal <= 0:
raise ValueError("""principal must be > 0""" )
return principal * (
(1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods
- 1
)
def __lowerCamelCase ( __lowerCAmelCase : float , __lowerCAmelCase : float , __lowerCAmelCase : float , ) -> float:
if number_of_years <= 0:
raise ValueError("""number_of_years must be > 0""" )
if nominal_annual_percentage_rate < 0:
raise ValueError("""nominal_annual_percentage_rate must be >= 0""" )
if principal <= 0:
raise ValueError("""principal must be > 0""" )
return compound_interest(
__lowerCAmelCase , nominal_annual_percentage_rate / 3_65 , number_of_years * 3_65 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 369 | 1 |
'''simple docstring'''
import argparse
import logging
import os
from datetime import datetime
import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, RandomSampler, TensorDataset
from tqdm import tqdm
from transformers import GPTaLMHeadModel
A : int = logging.getLogger(__name__)
def lowercase_ ( lowercase__ , lowercase__ ) ->Optional[int]:
# save results
if os.path.exists(lowercase__ ):
if os.path.exists(os.path.join(lowercase__ , 'config.json' ) ) and os.path.isfile(
os.path.join(lowercase__ , 'config.json' ) ):
os.remove(os.path.join(lowercase__ , 'config.json' ) )
if os.path.exists(os.path.join(lowercase__ , 'pytorch_model.bin' ) ) and os.path.isfile(
os.path.join(lowercase__ , 'pytorch_model.bin' ) ):
os.remove(os.path.join(lowercase__ , 'pytorch_model.bin' ) )
else:
os.makedirs(lowercase__ )
model.save_pretrained(lowercase__ )
def lowercase_ ( lowercase__ , lowercase__=False ) ->Tuple:
_snake_case: Union[str, Any] = 2
if unlogit:
_snake_case: Dict = torch.pow(lowercase__ , lowercase__ )
_snake_case: Optional[int] = p * torch.log(lowercase__ )
_snake_case: Optional[Any] = 0
return -plogp.sum(dim=-1 )
def lowercase_ ( lowercase__ ) ->Any:
logger.info('lv, h >\t' + '\t'.join(F'''{x + 1}''' for x in range(len(lowercase__ ) ) ) )
for row in range(len(lowercase__ ) ):
if tensor.dtype != torch.long:
logger.info(F'''layer {row + 1}:\t''' + '\t'.join(F'''{x:.5f}''' for x in tensor[row].cpu().data ) )
else:
logger.info(F'''layer {row + 1}:\t''' + '\t'.join(F'''{x:d}''' for x in tensor[row].cpu().data ) )
def lowercase_ ( lowercase__ , lowercase__ , lowercase__ , lowercase__=True , lowercase__=True , lowercase__=None , lowercase__=False ) ->Optional[Any]:
_snake_case , _snake_case: Optional[int] = model.config.num_hidden_layers, model.config.num_attention_heads
_snake_case: List[Any] = torch.zeros(lowercase__ , lowercase__ ).to(args.device )
_snake_case: Union[str, Any] = torch.zeros(lowercase__ , lowercase__ ).to(args.device )
if head_mask is None:
_snake_case: str = torch.ones(lowercase__ , lowercase__ ).to(args.device )
head_mask.requires_grad_(requires_grad=lowercase__ )
# If actually pruned attention multi-head, set head mask to None to avoid shape mismatch
if actually_pruned:
_snake_case: Any = None
_snake_case: Optional[int] = 0.0
_snake_case: Union[str, Any] = 0.0
for step, inputs in enumerate(tqdm(lowercase__ , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ):
_snake_case: Optional[Any] = tuple(t.to(args.device ) for t in inputs )
((_snake_case) , ): List[str] = inputs
# Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
_snake_case: Optional[int] = model(lowercase__ , labels=lowercase__ , head_mask=lowercase__ )
# (loss), lm_logits, presents, (all hidden_states), (attentions)
_snake_case , _snake_case , _snake_case: Union[str, Any] = (
outputs[0],
outputs[1],
outputs[-1],
) # Loss and logits are the first, attention the last
loss.backward() # Backpropagate to populate the gradients in the head mask
total_loss += loss.detach().cpu().numpy()
if compute_entropy:
for layer, attn in enumerate(lowercase__ ):
_snake_case: Optional[int] = entropy(attn.detach() , lowercase__ )
attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach()
if compute_importance:
head_importance += head_mask.grad.abs().detach()
tot_tokens += torch.ones_like(lowercase__ ).float().detach().sum().data
# Normalize
attn_entropy /= tot_tokens
head_importance /= tot_tokens
# Layerwise importance normalization
if not args.dont_normalize_importance_by_layer:
_snake_case: List[Any] = 2
_snake_case: int = torch.pow(torch.pow(lowercase__ , lowercase__ ).sum(-1 ) , 1 / exponent )
head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20
if not args.dont_normalize_global_importance:
_snake_case: List[str] = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())
# Print matrices
if compute_entropy:
logger.info('Attention entropies' )
print_ad_tensor(lowercase__ )
if compute_importance:
logger.info('Head importance scores' )
print_ad_tensor(lowercase__ )
logger.info('Head ranked by importance scores' )
_snake_case: Optional[int] = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device )
_snake_case: List[str] = torch.arange(
head_importance.numel() , device=args.device )
_snake_case: Any = head_ranks.view_as(lowercase__ )
print_ad_tensor(lowercase__ )
return attn_entropy, head_importance, total_loss
def lowercase_ ( lowercase__ , lowercase__ , lowercase__ ) ->List[str]:
_snake_case , _snake_case , _snake_case: int = compute_heads_importance(lowercase__ , lowercase__ , lowercase__ , compute_entropy=lowercase__ )
_snake_case: List[str] = 1 / loss # instead of downsteam score use the LM loss
logger.info('Pruning: original score: %f, threshold: %f' , lowercase__ , original_score * args.masking_threshold )
_snake_case: Optional[Any] = torch.ones_like(lowercase__ )
_snake_case: List[str] = max(1 , int(new_head_mask.numel() * args.masking_amount ) )
_snake_case: Tuple = original_score
while current_score >= original_score * args.masking_threshold:
_snake_case: Optional[Any] = new_head_mask.clone().detach() # save current head mask
# heads from least important to most - keep only not-masked heads
_snake_case: int = float('Inf' )
_snake_case: Optional[Any] = head_importance.view(-1 ).sort()[1]
if len(lowercase__ ) <= num_to_mask:
print('BREAK BY num_to_mask' )
break
# mask heads
_snake_case: Dict = current_heads_to_mask[:num_to_mask]
logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) )
_snake_case: Optional[int] = new_head_mask.view(-1 )
_snake_case: Optional[Any] = 0.0
_snake_case: List[str] = new_head_mask.view_as(lowercase__ )
_snake_case: int = new_head_mask.clone().detach()
print_ad_tensor(lowercase__ )
# Compute metric and head importance again
_snake_case , _snake_case , _snake_case: Tuple = compute_heads_importance(
lowercase__ , lowercase__ , lowercase__ , compute_entropy=lowercase__ , head_mask=lowercase__ )
_snake_case: str = 1 / loss
logger.info(
'Masking: current score: %f, remaining heads %d (%.1f percents)' , lowercase__ , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 100 , )
logger.info('Final head mask' )
print_ad_tensor(lowercase__ )
np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() )
return head_mask
def lowercase_ ( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) ->List[str]:
_snake_case: Optional[Any] = datetime.now()
_snake_case , _snake_case , _snake_case: Tuple = compute_heads_importance(
lowercase__ , lowercase__ , lowercase__ , compute_entropy=lowercase__ , compute_importance=lowercase__ , head_mask=lowercase__ )
_snake_case: List[Any] = 1 / loss
_snake_case: str = datetime.now() - before_time
_snake_case: str = sum(p.numel() for p in model.parameters() )
_snake_case: int = {
layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(lowercase__ ) )
}
for k, v in heads_to_prune.items():
if isinstance(lowercase__ , lowercase__ ):
_snake_case: Optional[Any] = [
v,
]
assert sum(len(lowercase__ ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item()
model.prune_heads(lowercase__ )
_snake_case: Optional[int] = sum(p.numel() for p in model.parameters() )
_snake_case: int = datetime.now()
_snake_case , _snake_case , _snake_case: int = compute_heads_importance(
lowercase__ , lowercase__ , lowercase__ , compute_entropy=lowercase__ , compute_importance=lowercase__ , head_mask=lowercase__ , actually_pruned=lowercase__ , )
_snake_case: int = 1 / loss
_snake_case: Union[str, Any] = datetime.now() - before_time
logger.info(
'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , lowercase__ , lowercase__ , pruned_num_params / original_num_params * 100 , )
logger.info('Pruning: score with masking: %f score with pruning: %f' , lowercase__ , lowercase__ )
logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 100 )
save_model(lowercase__ , args.output_dir )
def lowercase_ ( ) ->Optional[Any]:
_snake_case: Any = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--data_dir' , default=lowercase__ , type=lowercase__ , required=lowercase__ , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , )
parser.add_argument(
'--model_name_or_path' , default=lowercase__ , type=lowercase__ , required=lowercase__ , help='Path to pretrained model or model identifier from huggingface.co/models' , )
parser.add_argument(
'--output_dir' , default=lowercase__ , type=lowercase__ , required=lowercase__ , help='The output directory where the model predictions and checkpoints will be written.' , )
# Other parameters
parser.add_argument(
'--config_name' , default='' , type=lowercase__ , help='Pretrained config name or path if not the same as model_name_or_path' , )
parser.add_argument(
'--tokenizer_name' , default='' , type=lowercase__ , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , )
parser.add_argument(
'--cache_dir' , default=lowercase__ , type=lowercase__ , help='Where do you want to store the pre-trained models downloaded from s3' , )
parser.add_argument(
'--data_subset' , type=lowercase__ , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' )
parser.add_argument(
'--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' )
parser.add_argument(
'--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' )
parser.add_argument(
'--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' )
parser.add_argument(
'--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , )
parser.add_argument(
'--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' )
parser.add_argument(
'--masking_threshold' , default=0.9 , type=lowercase__ , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , )
parser.add_argument(
'--masking_amount' , default=0.1 , type=lowercase__ , help='Amount to heads to masking at each masking step.' )
parser.add_argument('--metric_name' , default='acc' , type=lowercase__ , help='Metric to use for head masking.' )
parser.add_argument(
'--max_seq_length' , default=128 , type=lowercase__ , help=(
'The maximum total input sequence length after WordPiece tokenization. \n'
'Sequences longer than this will be truncated, sequences shorter padded.'
) , )
parser.add_argument('--batch_size' , default=1 , type=lowercase__ , help='Batch size.' )
parser.add_argument('--seed' , type=lowercase__ , default=42 )
parser.add_argument('--local_rank' , type=lowercase__ , default=-1 , help='local_rank for distributed training on gpus' )
parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' )
parser.add_argument('--server_ip' , type=lowercase__ , default='' , help='Can be used for distant debugging.' )
parser.add_argument('--server_port' , type=lowercase__ , default='' , help='Can be used for distant debugging.' )
_snake_case: Any = parser.parse_args()
if args.server_ip and args.server_port:
# Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
import ptvsd
print('Waiting for debugger attach' )
ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=lowercase__ )
ptvsd.wait_for_attach()
# Setup devices and distributed training
if args.local_rank == -1 or args.no_cuda:
_snake_case: List[Any] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' )
_snake_case: List[str] = 0 if args.no_cuda else torch.cuda.device_count()
else:
torch.cuda.set_device(args.local_rank )
_snake_case: int = torch.device('cuda' , args.local_rank )
_snake_case: Optional[int] = 1
torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend
# Setup logging
logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN )
logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) )
_snake_case: Union[str, Any] = GPTaLMHeadModel.from_pretrained(args.model_name_or_path )
# Distributed and parallel training
model.to(args.device )
if args.local_rank != -1:
_snake_case: Optional[int] = nn.parallel.DistributedDataParallel(
lowercase__ , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=lowercase__ )
elif args.n_gpu > 1:
_snake_case: str = nn.DataParallel(lowercase__ )
# Print/save training arguments
os.makedirs(args.output_dir , exist_ok=lowercase__ )
torch.save(lowercase__ , os.path.join(args.output_dir , 'run_args.bin' ) )
logger.info('Training/evaluation parameters %s' , lowercase__ )
# Prepare dataset
_snake_case: Tuple = np.concatenate(
[
np.loadtxt(args.data_dir , dtype=np.intaa ),
] )
_snake_case: Any = (torch.from_numpy(lowercase__ ),)
_snake_case: Any = TensorDataset(*lowercase__ )
_snake_case: Dict = RandomSampler(lowercase__ )
_snake_case: Union[str, Any] = DataLoader(lowercase__ , sampler=lowercase__ , batch_size=args.batch_size )
# Compute head entropy and importance score
compute_heads_importance(lowercase__ , lowercase__ , lowercase__ )
# Try head masking (set heads to zero until the score goes under a threshole)
# and head pruning (remove masked heads and see the effect on the network)
if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0:
_snake_case: Dict = mask_heads(lowercase__ , lowercase__ , lowercase__ )
prune_heads(lowercase__ , lowercase__ , lowercase__ , lowercase__ )
if __name__ == "__main__":
main()
| 273 |
'''simple docstring'''
from __future__ import annotations
import sys
from collections import deque
from typing import Generic, TypeVar
A : str = TypeVar('T')
class lowerCamelCase ( Generic[T] ):
_SCREAMING_SNAKE_CASE = 42 # Cache store of keys
_SCREAMING_SNAKE_CASE = 42 # References of the keys in cache
_SCREAMING_SNAKE_CASE = 10 # Maximum capacity of cache
def __init__( self : List[Any] , __snake_case : int ):
'''simple docstring'''
_snake_case: Dict = deque()
_snake_case: Union[str, Any] = set()
if not n:
_snake_case: Optional[int] = sys.maxsize
elif n < 0:
raise ValueError('n should be an integer greater than 0.' )
else:
_snake_case: Tuple = n
def SCREAMING_SNAKE_CASE_ ( self : Any , __snake_case : T ):
'''simple docstring'''
if x not in self.key_reference:
if len(self.dq_store ) == LRUCache._MAX_CAPACITY:
_snake_case: int = self.dq_store.pop()
self.key_reference.remove(__snake_case )
else:
self.dq_store.remove(__snake_case )
self.dq_store.appendleft(__snake_case )
self.key_reference.add(__snake_case )
def SCREAMING_SNAKE_CASE_ ( self : int ):
'''simple docstring'''
for k in self.dq_store:
print(__snake_case )
def __repr__( self : List[Any] ):
'''simple docstring'''
return f'''LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}'''
if __name__ == "__main__":
import doctest
doctest.testmod()
A : LRUCache[str | int] = 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]"
| 273 | 1 |
"""simple docstring"""
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
import torch.nn as nn
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer
@dataclass
class __A ( SCREAMING_SNAKE_CASE_ ):
_UpperCamelCase : torch.FloatTensor
class __A ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
@register_to_config
def __init__( self , a__ = 3 , a__ = 3 , a__ = ("DownEncoderBlock2D",) , a__ = ("UpDecoderBlock2D",) , a__ = (64,) , a__ = 1 , a__ = "silu" , a__ = 3 , a__ = 32 , a__ = 256 , a__ = 32 , a__ = None , a__ = 0.1_8_2_1_5 , a__ = "group" , ):
super().__init__()
# pass init params to Encoder
_lowerCAmelCase : List[Any] = Encoder(
in_channels=a__ , out_channels=a__ , down_block_types=a__ , block_out_channels=a__ , layers_per_block=a__ , act_fn=a__ , norm_num_groups=a__ , double_z=a__ , )
_lowerCAmelCase : Tuple = vq_embed_dim if vq_embed_dim is not None else latent_channels
_lowerCAmelCase : int = nn.Convad(a__ , a__ , 1 )
_lowerCAmelCase : Dict = VectorQuantizer(a__ , a__ , beta=0.2_5 , remap=a__ , sane_index_shape=a__ )
_lowerCAmelCase : int = nn.Convad(a__ , a__ , 1 )
# pass init params to Decoder
_lowerCAmelCase : List[Any] = Decoder(
in_channels=a__ , out_channels=a__ , up_block_types=a__ , block_out_channels=a__ , layers_per_block=a__ , act_fn=a__ , norm_num_groups=a__ , norm_type=a__ , )
@apply_forward_hook
def __A ( self , a__ , a__ = True ):
_lowerCAmelCase : Optional[Any] = self.encoder(a__ )
_lowerCAmelCase : Optional[Any] = self.quant_conv(a__ )
if not return_dict:
return (h,)
return VQEncoderOutput(latents=a__ )
@apply_forward_hook
def __A ( self , a__ , a__ = False , a__ = True ):
# also go through quantization layer
if not force_not_quantize:
_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Optional[Any] = self.quantize(a__ )
else:
_lowerCAmelCase : Any = h
_lowerCAmelCase : Optional[int] = self.post_quant_conv(a__ )
_lowerCAmelCase : Dict = self.decoder(a__ , quant if self.config.norm_type == """spatial""" else None )
if not return_dict:
return (dec,)
return DecoderOutput(sample=a__ )
def __A ( self , a__ , a__ = True ):
_lowerCAmelCase : Optional[int] = sample
_lowerCAmelCase : str = self.encode(a__ ).latents
_lowerCAmelCase : List[str] = self.decode(a__ ).sample
if not return_dict:
return (dec,)
return DecoderOutput(sample=a__ )
| 213 | """simple docstring"""
from __future__ import annotations
from collections import deque
class __A :
def __init__( self , a__ ):
_lowerCAmelCase : list[dict] = []
self.adlist.append(
{"""value""": """""", """next_states""": [], """fail_state""": 0, """output""": []} )
for keyword in keywords:
self.add_keyword(a__ )
self.set_fail_transitions()
def __A ( self , a__ , a__ ):
for state in self.adlist[current_state]["next_states"]:
if char == self.adlist[state]["value"]:
return state
return None
def __A ( self , a__ ):
_lowerCAmelCase : Union[str, Any] = 0
for character in keyword:
_lowerCAmelCase : str = self.find_next_state(a__ , a__ )
if next_state is None:
self.adlist.append(
{
"""value""": character,
"""next_states""": [],
"""fail_state""": 0,
"""output""": [],
} )
self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 )
_lowerCAmelCase : List[str] = len(self.adlist ) - 1
else:
_lowerCAmelCase : Any = next_state
self.adlist[current_state]["output"].append(a__ )
def __A ( self ):
_lowerCAmelCase : deque = deque()
for node in self.adlist[0]["next_states"]:
q.append(a__ )
_lowerCAmelCase : str = 0
while q:
_lowerCAmelCase : Optional[Any] = q.popleft()
for child in self.adlist[r]["next_states"]:
q.append(a__ )
_lowerCAmelCase : Tuple = self.adlist[r]["""fail_state"""]
while (
self.find_next_state(a__ , self.adlist[child]["""value"""] ) is None
and state != 0
):
_lowerCAmelCase : List[Any] = self.adlist[state]["""fail_state"""]
_lowerCAmelCase : Optional[int] = self.find_next_state(
a__ , self.adlist[child]["""value"""] )
if self.adlist[child]["fail_state"] is None:
_lowerCAmelCase : int = 0
_lowerCAmelCase : str = (
self.adlist[child]["""output"""]
+ self.adlist[self.adlist[child]["""fail_state"""]]["""output"""]
)
def __A ( self , a__ ):
_lowerCAmelCase : dict = {} # returns a dict with keywords and list of its occurrences
_lowerCAmelCase : Any = 0
for i in range(len(a__ ) ):
while (
self.find_next_state(a__ , string[i] ) is None
and current_state != 0
):
_lowerCAmelCase : Any = self.adlist[current_state]["""fail_state"""]
_lowerCAmelCase : List[Any] = self.find_next_state(a__ , string[i] )
if next_state is None:
_lowerCAmelCase : Optional[Any] = 0
else:
_lowerCAmelCase : Optional[int] = next_state
for key in self.adlist[current_state]["output"]:
if key not in result:
_lowerCAmelCase : List[Any] = []
result[key].append(i - len(a__ ) + 1 )
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
| 213 | 1 |
from __future__ import annotations
from math import pi
def _snake_case (__lowercase , __lowercase , __lowercase):
if (inductance, frequency, reactance).count(0) != 1:
raise ValueError('One and only one argument must be 0')
if inductance < 0:
raise ValueError('Inductance cannot be negative')
if frequency < 0:
raise ValueError('Frequency cannot be negative')
if reactance < 0:
raise ValueError('Inductive reactance cannot be negative')
if inductance == 0:
return {"inductance": reactance / (2 * pi * frequency)}
elif frequency == 0:
return {"frequency": reactance / (2 * pi * inductance)}
elif reactance == 0:
return {"reactance": 2 * pi * frequency * inductance}
else:
raise ValueError('Exactly one argument must be 0')
if __name__ == "__main__":
import doctest
doctest.testmod()
| 719 |
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 _a ( unittest.TestCase ):
"""simple docstring"""
def _UpperCAmelCase ( self ) -> Dict:
UpperCamelCase_ = tempfile.mkdtemp()
# fmt: off
UpperCamelCase_ = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest']
# fmt: on
UpperCamelCase_ = 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] ) )
UpperCamelCase_ = {
'do_resize': True,
'size': {'height': 18, 'width': 18},
'do_normalize': True,
'image_mean': [0.5, 0.5, 0.5],
'image_std': [0.5, 0.5, 0.5],
}
UpperCamelCase_ = os.path.join(self.tmpdirname , _UpperCAmelCase )
with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp:
json.dump(_UpperCAmelCase , _UpperCAmelCase )
def _UpperCAmelCase ( self , **_UpperCAmelCase ) -> Optional[Any]:
return BertTokenizer.from_pretrained(self.tmpdirname , **_UpperCAmelCase )
def _UpperCAmelCase ( self , **_UpperCAmelCase ) -> Optional[int]:
return ViTImageProcessor.from_pretrained(self.tmpdirname , **_UpperCAmelCase )
def _UpperCAmelCase ( self ) -> Any:
shutil.rmtree(self.tmpdirname )
def _UpperCAmelCase ( self ) -> Optional[int]:
UpperCamelCase_ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )]
UpperCamelCase_ = [Image.fromarray(np.moveaxis(_UpperCAmelCase , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def _UpperCAmelCase ( self ) -> Tuple:
UpperCamelCase_ = self.get_tokenizer()
UpperCamelCase_ = self.get_image_processor()
UpperCamelCase_ = VisionTextDualEncoderProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase )
processor.save_pretrained(self.tmpdirname )
UpperCamelCase_ = 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 , _UpperCAmelCase )
def _UpperCAmelCase ( self ) -> Optional[Any]:
UpperCamelCase_ = VisionTextDualEncoderProcessor(
tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
UpperCamelCase_ = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' )
UpperCamelCase_ = self.get_image_processor(do_normalize=_UpperCAmelCase , padding_value=1.0 )
UpperCamelCase_ = VisionTextDualEncoderProcessor.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 , (BertTokenizer, BertTokenizerFast) )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , _UpperCAmelCase )
def _UpperCAmelCase ( self ) -> str:
UpperCamelCase_ = self.get_image_processor()
UpperCamelCase_ = self.get_tokenizer()
UpperCamelCase_ = VisionTextDualEncoderProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase )
UpperCamelCase_ = self.prepare_image_inputs()
UpperCamelCase_ = image_processor(_UpperCAmelCase , return_tensors='np' )
UpperCamelCase_ = 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 _UpperCAmelCase ( self ) -> Optional[int]:
UpperCamelCase_ = self.get_image_processor()
UpperCamelCase_ = self.get_tokenizer()
UpperCamelCase_ = VisionTextDualEncoderProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase )
UpperCamelCase_ = 'lower newer'
UpperCamelCase_ = processor(text=_UpperCAmelCase )
UpperCamelCase_ = tokenizer(_UpperCAmelCase )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def _UpperCAmelCase ( self ) -> Any:
UpperCamelCase_ = self.get_image_processor()
UpperCamelCase_ = self.get_tokenizer()
UpperCamelCase_ = VisionTextDualEncoderProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase )
UpperCamelCase_ = 'lower newer'
UpperCamelCase_ = self.prepare_image_inputs()
UpperCamelCase_ = processor(text=_UpperCAmelCase , images=_UpperCAmelCase )
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(_UpperCAmelCase ):
processor()
def _UpperCAmelCase ( self ) -> Union[str, Any]:
UpperCamelCase_ = self.get_image_processor()
UpperCamelCase_ = self.get_tokenizer()
UpperCamelCase_ = VisionTextDualEncoderProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase )
UpperCamelCase_ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
UpperCamelCase_ = processor.batch_decode(_UpperCAmelCase )
UpperCamelCase_ = tokenizer.batch_decode(_UpperCAmelCase )
self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase )
def _UpperCAmelCase ( self ) -> List[Any]:
UpperCamelCase_ = self.get_image_processor()
UpperCamelCase_ = self.get_tokenizer()
UpperCamelCase_ = VisionTextDualEncoderProcessor(tokenizer=_UpperCAmelCase , image_processor=_UpperCAmelCase )
UpperCamelCase_ = 'lower newer'
UpperCamelCase_ = self.prepare_image_inputs()
UpperCamelCase_ = processor(text=_UpperCAmelCase , images=_UpperCAmelCase )
self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
| 618 | 0 |
'''simple docstring'''
import functools
import operator
from ...configuration_utils import PretrainedConfig
from ...utils import logging
A__ : List[Any] = logging.get_logger(__name__)
A__ : Any = {
"""microsoft/unispeech-sat-base-100h-libri-ft""": (
"""https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json"""
),
# See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat
}
class UpperCAmelCase_ (_UpperCAmelCase ):
"""simple docstring"""
lowerCamelCase : Tuple = 'unispeech-sat'
def __init__( self , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=7_68 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=30_72 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0_2 , SCREAMING_SNAKE_CASE_=1E-5 , SCREAMING_SNAKE_CASE_="group" , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12) , SCREAMING_SNAKE_CASE_=(5, 2, 2, 2, 2, 2, 2) , SCREAMING_SNAKE_CASE_=(10, 3, 3, 3, 3, 2, 2) , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1_28 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=0.0_5 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=3_20 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=1_00 , SCREAMING_SNAKE_CASE_=2_56 , SCREAMING_SNAKE_CASE_=2_56 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_="mean" , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=2_56 , SCREAMING_SNAKE_CASE_=(5_12, 5_12, 5_12, 5_12, 15_00) , SCREAMING_SNAKE_CASE_=(5, 3, 3, 1, 1) , SCREAMING_SNAKE_CASE_=(1, 2, 3, 1, 1) , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=5_04 , **SCREAMING_SNAKE_CASE_ , ) -> Dict:
super().__init__(**SCREAMING_SNAKE_CASE_ , pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ )
__lowerCamelCase : Union[str, Any] = hidden_size
__lowerCamelCase : List[str] = feat_extract_norm
__lowerCamelCase : Tuple = feat_extract_activation
__lowerCamelCase : str = list(SCREAMING_SNAKE_CASE_ )
__lowerCamelCase : Tuple = list(SCREAMING_SNAKE_CASE_ )
__lowerCamelCase : str = list(SCREAMING_SNAKE_CASE_ )
__lowerCamelCase : Union[str, Any] = conv_bias
__lowerCamelCase : str = num_conv_pos_embeddings
__lowerCamelCase : Tuple = num_conv_pos_embedding_groups
__lowerCamelCase : Union[str, Any] = len(self.conv_dim )
__lowerCamelCase : int = num_hidden_layers
__lowerCamelCase : Tuple = intermediate_size
__lowerCamelCase : Dict = hidden_act
__lowerCamelCase : Optional[int] = num_attention_heads
__lowerCamelCase : str = hidden_dropout
__lowerCamelCase : Optional[Any] = attention_dropout
__lowerCamelCase : Optional[Any] = activation_dropout
__lowerCamelCase : Optional[Any] = feat_proj_dropout
__lowerCamelCase : Optional[Any] = final_dropout
__lowerCamelCase : Any = layerdrop
__lowerCamelCase : Union[str, Any] = layer_norm_eps
__lowerCamelCase : List[Any] = initializer_range
__lowerCamelCase : Any = vocab_size
__lowerCamelCase : str = num_clusters
__lowerCamelCase : Tuple = do_stable_layer_norm
__lowerCamelCase : Tuple = use_weighted_layer_sum
if (
(len(self.conv_stride ) != self.num_feat_extract_layers)
or (len(self.conv_kernel ) != self.num_feat_extract_layers)
or (len(self.conv_dim ) != self.num_feat_extract_layers)
):
raise ValueError(
'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =='
' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ='
f' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,'
f' `len(config.conv_kernel) = {len(self.conv_kernel )}`.' )
# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
__lowerCamelCase : List[Any] = apply_spec_augment
__lowerCamelCase : Union[str, Any] = mask_time_prob
__lowerCamelCase : Tuple = mask_time_length
__lowerCamelCase : Tuple = mask_time_min_masks
__lowerCamelCase : List[Any] = mask_feature_prob
__lowerCamelCase : Dict = mask_feature_length
__lowerCamelCase : Tuple = mask_feature_min_masks
# parameters for pretraining with codevector quantized representations
__lowerCamelCase : List[str] = num_codevectors_per_group
__lowerCamelCase : List[Any] = num_codevector_groups
__lowerCamelCase : Tuple = contrastive_logits_temperature
__lowerCamelCase : Optional[int] = feat_quantizer_dropout
__lowerCamelCase : str = num_negatives
__lowerCamelCase : str = codevector_dim
__lowerCamelCase : Optional[Any] = proj_codevector_dim
__lowerCamelCase : Optional[int] = diversity_loss_weight
# ctc loss
__lowerCamelCase : List[Any] = ctc_loss_reduction
__lowerCamelCase : Optional[Any] = ctc_zero_infinity
# SequenceClassification-specific parameter. Feel free to ignore for other classes.
__lowerCamelCase : Any = classifier_proj_size
# XVector-specific parameters. Feel free to ignore for other classes.
__lowerCamelCase : List[str] = list(SCREAMING_SNAKE_CASE_ )
__lowerCamelCase : Tuple = list(SCREAMING_SNAKE_CASE_ )
__lowerCamelCase : Optional[Any] = list(SCREAMING_SNAKE_CASE_ )
__lowerCamelCase : Union[str, Any] = xvector_output_dim
@property
def lowercase_ ( self ) -> Union[str, Any]:
return functools.reduce(operator.mul , self.conv_stride , 1 )
| 13 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowerCAmelCase__ = logging.get_logger(__name__)
lowerCAmelCase__ = {
"""google/pegasus-large""": """https://huggingface.co/google/pegasus-large/resolve/main/config.json""",
# See all PEGASUS models at https://huggingface.co/models?filter=pegasus
}
class a__ ( snake_case ):
"""simple docstring"""
__lowerCamelCase = 'pegasus'
__lowerCamelCase = ['past_key_values']
__lowerCamelCase = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}
def __init__( self , lowercase=50265 , lowercase=1024 , lowercase=12 , lowercase=4096 , lowercase=16 , lowercase=12 , lowercase=4096 , lowercase=16 , lowercase=0.0 , lowercase=0.0 , lowercase=True , lowercase=True , lowercase="gelu" , lowercase=1024 , lowercase=0.1 , lowercase=0.0 , lowercase=0.0 , lowercase=0.02 , lowercase=0 , lowercase=False , lowercase=0 , lowercase=1 , lowercase=1 , **lowercase , ) -> Optional[Any]:
'''simple docstring'''
A__ = vocab_size
A__ = max_position_embeddings
A__ = d_model
A__ = encoder_ffn_dim
A__ = encoder_layers
A__ = encoder_attention_heads
A__ = decoder_ffn_dim
A__ = decoder_layers
A__ = decoder_attention_heads
A__ = dropout
A__ = attention_dropout
A__ = activation_dropout
A__ = activation_function
A__ = init_std
A__ = encoder_layerdrop
A__ = decoder_layerdrop
A__ = use_cache
A__ = encoder_layers
A__ = scale_embedding # scale factor will be sqrt(d_model) if True
super().__init__(
pad_token_id=lowercase , eos_token_id=lowercase , is_encoder_decoder=lowercase , decoder_start_token_id=lowercase , forced_eos_token_id=lowercase , **lowercase , )
@property
def UpperCamelCase ( self ) -> int:
'''simple docstring'''
return self.encoder_attention_heads
@property
def UpperCamelCase ( self ) -> int:
'''simple docstring'''
return self.d_model
| 514 | 0 |
"""simple docstring"""
import os
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_doctest_list.py
__lowercase = """."""
if __name__ == "__main__":
__lowercase = os.path.join(REPO_PATH, """utils/documentation_tests.txt""")
__lowercase = []
__lowercase = []
with open(doctest_file_path) as fp:
for line in fp:
__lowercase = line.strip()
__lowercase = os.path.join(REPO_PATH, line)
if not (os.path.isfile(path) or os.path.isdir(path)):
non_existent_paths.append(line)
all_paths.append(path)
if len(non_existent_paths) > 0:
__lowercase = """\n""".join(non_existent_paths)
raise ValueError(f'''`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}''')
if all_paths != sorted(all_paths):
raise ValueError("""Files in `utils/documentation_tests.txt` are not in alphabetical order.""")
| 135 |
"""simple docstring"""
def lowercase ( )-> Union[str, Any]:
'''simple docstring'''
a : Tuple = 0
for i in range(1 , 1_001 ):
total += i**i
return str(A_ )[-10:]
if __name__ == "__main__":
print(solution())
| 135 | 1 |
"""simple docstring"""
import argparse
from collections import defaultdict
import yaml
__UpperCAmelCase ="""docs/source/en/_toctree.yml"""
def __a ( A ) -> Optional[int]:
'''simple docstring'''
A__ = defaultdict(A )
for doc in model_doc:
counts[doc["local"]] += 1
A__ = [key for key, value in counts.items() if value > 1]
A__ = []
for duplicate_key in duplicates:
A__ = list({doc["title"] for doc in model_doc if doc["local"] == duplicate_key} )
if len(A ) > 1:
raise ValueError(
f"""{duplicate_key} is present several times in the documentation table of content at """
"`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the "
"others." )
# Only add this once
new_doc.append({"local": duplicate_key, "title": titles[0]} )
# Add none duplicate-keys
new_doc.extend([doc for doc in model_doc if counts[doc["local"]] == 1] )
# Sort
return sorted(A , key=lambda A : s["title"].lower() )
def __a ( A=False ) -> Union[str, Any]:
'''simple docstring'''
with open(A , encoding="utf-8" ) as f:
A__ = yaml.safe_load(f.read() )
# Get to the API doc
A__ = 0
while content[api_idx]["title"] != "API":
api_idx += 1
A__ = content[api_idx]["sections"]
# Then to the model doc
A__ = 0
while api_doc[model_idx]["title"] != "Models":
model_idx += 1
A__ = api_doc[model_idx]["sections"]
A__ = [(idx, section) for idx, section in enumerate(A ) if "sections" in section]
A__ = False
for idx, modality_doc in modalities_docs:
A__ = modality_doc["sections"]
A__ = clean_model_doc_toc(A )
if old_modality_doc != new_modality_doc:
A__ = True
if overwrite:
A__ = new_modality_doc
if diff:
if overwrite:
A__ = model_doc
A__ = api_doc
with open(A , "w" , encoding="utf-8" ) as f:
f.write(yaml.dump(A , allow_unicode=A ) )
else:
raise ValueError(
"The model doc part of the table of content is not properly sorted, run `make style` to fix this." )
if __name__ == "__main__":
__UpperCAmelCase =argparse.ArgumentParser()
parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
__UpperCAmelCase =parser.parse_args()
check_model_doc(args.fix_and_overwrite) | 337 |
"""simple docstring"""
import importlib
import sys
from argparse import REMAINDER, ArgumentParser
from pathlib import Path
import torch_xla.distributed.xla_multiprocessing as xmp
def __a ( ) -> Optional[Any]:
'''simple docstring'''
A__ = ArgumentParser(
description=(
"PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes"
) )
# Optional arguments for the launch helper
parser.add_argument("--num_cores" , type=A , default=1 , help="Number of TPU cores to use (1 or 8)." )
# positional
parser.add_argument(
"training_script" , type=A , help=(
"The full path to the single TPU training "
"program/script to be launched in parallel, "
"followed by all the arguments for the "
"training script"
) , )
# rest from the training program
parser.add_argument("training_script_args" , nargs=A )
return parser.parse_args()
def __a ( ) -> List[str]:
'''simple docstring'''
A__ = parse_args()
# Import training_script as a module.
A__ = Path(args.training_script )
sys.path.append(str(script_fpath.parent.resolve() ) )
A__ = script_fpath.stem
A__ = importlib.import_module(A )
# Patch sys.argv
A__ = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )]
xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores )
if __name__ == "__main__":
main() | 337 | 1 |
'''simple docstring'''
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 ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel
from transformers.utils import logging
logging.set_verbosity_info()
A = logging.get_logger(__name__)
def a(lowercase__ , lowercase__=False ):
'''simple docstring'''
snake_case_ = []
for i in range(config.num_hidden_layers ):
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
rename_keys.append((f"""blocks.{i}.norm1.weight""", f"""vit.encoder.layer.{i}.layernorm_before.weight""") )
rename_keys.append((f"""blocks.{i}.norm1.bias""", f"""vit.encoder.layer.{i}.layernorm_before.bias""") )
rename_keys.append((f"""blocks.{i}.attn.proj.weight""", f"""vit.encoder.layer.{i}.attention.output.dense.weight""") )
rename_keys.append((f"""blocks.{i}.attn.proj.bias""", f"""vit.encoder.layer.{i}.attention.output.dense.bias""") )
rename_keys.append((f"""blocks.{i}.norm2.weight""", f"""vit.encoder.layer.{i}.layernorm_after.weight""") )
rename_keys.append((f"""blocks.{i}.norm2.bias""", f"""vit.encoder.layer.{i}.layernorm_after.bias""") )
rename_keys.append((f"""blocks.{i}.mlp.fc1.weight""", f"""vit.encoder.layer.{i}.intermediate.dense.weight""") )
rename_keys.append((f"""blocks.{i}.mlp.fc1.bias""", f"""vit.encoder.layer.{i}.intermediate.dense.bias""") )
rename_keys.append((f"""blocks.{i}.mlp.fc2.weight""", f"""vit.encoder.layer.{i}.output.dense.weight""") )
rename_keys.append((f"""blocks.{i}.mlp.fc2.bias""", f"""vit.encoder.layer.{i}.output.dense.bias""") )
# projection layer + position embeddings
rename_keys.extend(
[
('cls_token', 'vit.embeddings.cls_token'),
('patch_embed.proj.weight', 'vit.embeddings.patch_embeddings.projection.weight'),
('patch_embed.proj.bias', 'vit.embeddings.patch_embeddings.projection.bias'),
('pos_embed', 'vit.embeddings.position_embeddings'),
] )
if base_model:
# layernorm + pooler
rename_keys.extend(
[
('norm.weight', 'layernorm.weight'),
('norm.bias', 'layernorm.bias'),
] )
# if just the base model, we should remove "vit" from all keys that start with "vit"
snake_case_ = [(pair[0], pair[1][4:]) if pair[1].startswith('vit' ) else pair for pair in rename_keys]
else:
# layernorm + classification head
rename_keys.extend(
[
('norm.weight', 'vit.layernorm.weight'),
('norm.bias', 'vit.layernorm.bias'),
('head.weight', 'classifier.weight'),
('head.bias', 'classifier.bias'),
] )
return rename_keys
def a(lowercase__ , lowercase__ , lowercase__=False ):
'''simple docstring'''
for i in range(config.num_hidden_layers ):
if base_model:
snake_case_ = ''
else:
snake_case_ = 'vit.'
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
snake_case_ = state_dict.pop(f"""blocks.{i}.attn.qkv.weight""" )
snake_case_ = state_dict.pop(f"""blocks.{i}.attn.qkv.bias""" )
# next, add query, keys and values (in that order) to the state dict
snake_case_ = in_proj_weight[
: config.hidden_size, :
]
snake_case_ = in_proj_bias[: config.hidden_size]
snake_case_ = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
snake_case_ = in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
snake_case_ = in_proj_weight[
-config.hidden_size :, :
]
snake_case_ = in_proj_bias[-config.hidden_size :]
def a(lowercase__ ):
'''simple docstring'''
snake_case_ = ['head.weight', 'head.bias']
for k in ignore_keys:
state_dict.pop(lowercase__ , lowercase__ )
def a(lowercase__ , lowercase__ , lowercase__ ):
'''simple docstring'''
snake_case_ = dct.pop(lowercase__ )
snake_case_ = val
def a():
'''simple docstring'''
snake_case_ = 'http://images.cocodataset.org/val2017/000000039769.jpg'
snake_case_ = Image.open(requests.get(lowercase__ , stream=lowercase__ ).raw )
return im
@torch.no_grad()
def a(lowercase__ , lowercase__ , lowercase__=True ):
'''simple docstring'''
snake_case_ = ViTConfig()
# patch_size
if model_name[-1] == "8":
snake_case_ = 8
# set labels if required
if not base_model:
snake_case_ = 1000
snake_case_ = 'huggingface/label-files'
snake_case_ = 'imagenet-1k-id2label.json'
snake_case_ = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type='dataset' ) , 'r' ) )
snake_case_ = {int(lowercase__ ): v for k, v in idalabel.items()}
snake_case_ = idalabel
snake_case_ = {v: k for k, v in idalabel.items()}
# size of the architecture
if model_name in ["dino_vits8", "dino_vits16"]:
snake_case_ = 384
snake_case_ = 1536
snake_case_ = 12
snake_case_ = 6
# load original model from torch hub
snake_case_ = torch.hub.load('facebookresearch/dino:main' , lowercase__ )
original_model.eval()
# load state_dict of original model, remove and rename some keys
snake_case_ = original_model.state_dict()
if base_model:
remove_classification_head_(lowercase__ )
snake_case_ = create_rename_keys(lowercase__ , base_model=lowercase__ )
for src, dest in rename_keys:
rename_key(lowercase__ , lowercase__ , lowercase__ )
read_in_q_k_v(lowercase__ , lowercase__ , lowercase__ )
# load HuggingFace model
if base_model:
snake_case_ = ViTModel(lowercase__ , add_pooling_layer=lowercase__ ).eval()
else:
snake_case_ = ViTForImageClassification(lowercase__ ).eval()
model.load_state_dict(lowercase__ )
# Check outputs on an image, prepared by ViTImageProcessor
snake_case_ = ViTImageProcessor()
snake_case_ = image_processor(images=prepare_img() , return_tensors='pt' )
snake_case_ = encoding['pixel_values']
snake_case_ = model(lowercase__ )
if base_model:
snake_case_ = original_model(lowercase__ )
assert torch.allclose(lowercase__ , outputs.last_hidden_state[:, 0, :] , atol=1e-1 )
else:
snake_case_ = original_model(lowercase__ )
assert logits.shape == outputs.logits.shape
assert torch.allclose(lowercase__ , outputs.logits , atol=1e-3 )
Path(lowercase__ ).mkdir(exist_ok=lowercase__ )
print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" )
model.save_pretrained(lowercase__ )
print(f"""Saving image processor to {pytorch_dump_folder_path}""" )
image_processor.save_pretrained(lowercase__ )
if __name__ == "__main__":
A = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--model_name',
default='dino_vitb16',
type=str,
help='Name of the model trained with DINO you\'d like to convert.',
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.'
)
parser.add_argument(
'--base_model',
action='store_true',
help='Whether to only convert the base model (no projection head weights).',
)
parser.set_defaults(base_model=True)
A = parser.parse_args()
convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)
| 718 |
import inspect
import unittest
from transformers import MobileViTConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel
from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import MobileViTImageProcessor
class SCREAMING_SNAKE_CASE ( __snake_case ):
"""simple docstring"""
def __lowerCAmelCase ( self ):
"""simple docstring"""
snake_case_ = self.config_class(**self.inputs_dict )
self.parent.assertTrue(hasattr(__UpperCamelCase , 'hidden_sizes' ) )
self.parent.assertTrue(hasattr(__UpperCamelCase , 'neck_hidden_sizes' ) )
self.parent.assertTrue(hasattr(__UpperCamelCase , 'num_attention_heads' ) )
class SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self , __UpperCamelCase , __UpperCamelCase=13 , __UpperCamelCase=32 , __UpperCamelCase=2 , __UpperCamelCase=3 , __UpperCamelCase=6_40 , __UpperCamelCase=4 , __UpperCamelCase="silu" , __UpperCamelCase=3 , __UpperCamelCase=32 , __UpperCamelCase=0.1 , __UpperCamelCase=0.1 , __UpperCamelCase=0.1 , __UpperCamelCase=0.02 , __UpperCamelCase=True , __UpperCamelCase=True , __UpperCamelCase=10 , __UpperCamelCase=None , ):
"""simple docstring"""
snake_case_ = parent
snake_case_ = batch_size
snake_case_ = image_size
snake_case_ = patch_size
snake_case_ = num_channels
snake_case_ = last_hidden_size
snake_case_ = num_attention_heads
snake_case_ = hidden_act
snake_case_ = conv_kernel_size
snake_case_ = output_stride
snake_case_ = hidden_dropout_prob
snake_case_ = attention_probs_dropout_prob
snake_case_ = classifier_dropout_prob
snake_case_ = use_labels
snake_case_ = is_training
snake_case_ = num_labels
snake_case_ = initializer_range
snake_case_ = scope
def __lowerCAmelCase ( self ):
"""simple docstring"""
snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
snake_case_ = None
snake_case_ = None
if self.use_labels:
snake_case_ = ids_tensor([self.batch_size] , self.num_labels )
snake_case_ = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels )
snake_case_ = self.get_config()
return config, pixel_values, labels, pixel_labels
def __lowerCAmelCase ( self ):
"""simple docstring"""
return MobileViTConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , )
def __lowerCAmelCase ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
"""simple docstring"""
snake_case_ = MobileViTModel(config=__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
snake_case_ = model(__UpperCamelCase )
self.parent.assertEqual(
result.last_hidden_state.shape , (
self.batch_size,
self.last_hidden_size,
self.image_size // self.output_stride,
self.image_size // self.output_stride,
) , )
def __lowerCAmelCase ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
"""simple docstring"""
snake_case_ = self.num_labels
snake_case_ = MobileViTForImageClassification(__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
snake_case_ = model(__UpperCamelCase , labels=__UpperCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def __lowerCAmelCase ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
"""simple docstring"""
snake_case_ = self.num_labels
snake_case_ = MobileViTForSemanticSegmentation(__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
snake_case_ = model(__UpperCamelCase )
self.parent.assertEqual(
result.logits.shape , (
self.batch_size,
self.num_labels,
self.image_size // self.output_stride,
self.image_size // self.output_stride,
) , )
snake_case_ = model(__UpperCamelCase , labels=__UpperCamelCase )
self.parent.assertEqual(
result.logits.shape , (
self.batch_size,
self.num_labels,
self.image_size // self.output_stride,
self.image_size // self.output_stride,
) , )
def __lowerCAmelCase ( self ):
"""simple docstring"""
snake_case_ = self.prepare_config_and_inputs()
snake_case_ , snake_case_ , snake_case_ , snake_case_ = config_and_inputs
snake_case_ = {'pixel_values': pixel_values}
return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , unittest.TestCase ):
"""simple docstring"""
__A = (
(MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
if is_torch_available()
else ()
)
__A = (
{
"""feature-extraction""": MobileViTModel,
"""image-classification""": MobileViTForImageClassification,
"""image-segmentation""": MobileViTForSemanticSegmentation,
}
if is_torch_available()
else {}
)
__A = False
__A = False
__A = False
__A = False
def __lowerCAmelCase ( self ):
"""simple docstring"""
snake_case_ = MobileViTModelTester(self )
snake_case_ = MobileViTConfigTester(self , config_class=__UpperCamelCase , has_text_modality=__UpperCamelCase )
def __lowerCAmelCase ( self ):
"""simple docstring"""
self.config_tester.run_common_tests()
@unittest.skip(reason='MobileViT does not use inputs_embeds' )
def __lowerCAmelCase ( self ):
"""simple docstring"""
pass
@unittest.skip(reason='MobileViT does not support input and output embeddings' )
def __lowerCAmelCase ( self ):
"""simple docstring"""
pass
@unittest.skip(reason='MobileViT does not output attentions' )
def __lowerCAmelCase ( self ):
"""simple docstring"""
pass
def __lowerCAmelCase ( self ):
"""simple docstring"""
snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
snake_case_ = model_class(__UpperCamelCase )
snake_case_ = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
snake_case_ = [*signature.parameters.keys()]
snake_case_ = ['pixel_values']
self.assertListEqual(arg_names[:1] , __UpperCamelCase )
@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' )
def __lowerCAmelCase ( self ):
"""simple docstring"""
pass
def __lowerCAmelCase ( self ):
"""simple docstring"""
snake_case_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__UpperCamelCase )
def __lowerCAmelCase ( self ):
"""simple docstring"""
def check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
snake_case_ = model_class(__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
with torch.no_grad():
snake_case_ = model(**self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) )
snake_case_ = outputs.hidden_states
snake_case_ = 5
self.assertEqual(len(__UpperCamelCase ) , __UpperCamelCase )
# MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
# with the width and height being successively divided by 2.
snake_case_ = 2
for i in range(len(__UpperCamelCase ) ):
self.assertListEqual(
list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , )
divisor *= 2
self.assertEqual(self.model_tester.output_stride , divisor // 2 )
snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
snake_case_ = True
check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
snake_case_ = True
check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
def __lowerCAmelCase ( self ):
"""simple docstring"""
snake_case_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase )
def __lowerCAmelCase ( self ):
"""simple docstring"""
snake_case_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_semantic_segmentation(*__UpperCamelCase )
@slow
def __lowerCAmelCase ( self ):
"""simple docstring"""
for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
snake_case_ = MobileViTModel.from_pretrained(__UpperCamelCase )
self.assertIsNotNone(__UpperCamelCase )
def a():
'''simple docstring'''
snake_case_ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
return image
@require_torch
@require_vision
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
@cached_property
def __lowerCAmelCase ( self ):
"""simple docstring"""
return MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small' ) if is_vision_available() else None
@slow
def __lowerCAmelCase ( self ):
"""simple docstring"""
snake_case_ = MobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small' ).to(__UpperCamelCase )
snake_case_ = self.default_image_processor
snake_case_ = prepare_img()
snake_case_ = image_processor(images=__UpperCamelCase , return_tensors='pt' ).to(__UpperCamelCase )
# forward pass
with torch.no_grad():
snake_case_ = model(**__UpperCamelCase )
# verify the logits
snake_case_ = torch.Size((1, 10_00) )
self.assertEqual(outputs.logits.shape , __UpperCamelCase )
snake_case_ = torch.tensor([-1.9364, -1.2327, -0.4653] ).to(__UpperCamelCase )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , __UpperCamelCase , atol=1E-4 ) )
@slow
def __lowerCAmelCase ( self ):
"""simple docstring"""
snake_case_ = MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )
snake_case_ = model.to(__UpperCamelCase )
snake_case_ = MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )
snake_case_ = prepare_img()
snake_case_ = image_processor(images=__UpperCamelCase , return_tensors='pt' ).to(__UpperCamelCase )
# forward pass
with torch.no_grad():
snake_case_ = model(**__UpperCamelCase )
snake_case_ = outputs.logits
# verify the logits
snake_case_ = torch.Size((1, 21, 32, 32) )
self.assertEqual(logits.shape , __UpperCamelCase )
snake_case_ = torch.tensor(
[
[[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]],
[[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]],
[[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]],
] , device=__UpperCamelCase , )
self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , __UpperCamelCase , atol=1E-4 ) )
@slow
def __lowerCAmelCase ( self ):
"""simple docstring"""
snake_case_ = MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )
snake_case_ = model.to(__UpperCamelCase )
snake_case_ = MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )
snake_case_ = prepare_img()
snake_case_ = image_processor(images=__UpperCamelCase , return_tensors='pt' ).to(__UpperCamelCase )
# forward pass
with torch.no_grad():
snake_case_ = model(**__UpperCamelCase )
snake_case_ = outputs.logits.detach().cpu()
snake_case_ = image_processor.post_process_semantic_segmentation(outputs=__UpperCamelCase , target_sizes=[(50, 60)] )
snake_case_ = torch.Size((50, 60) )
self.assertEqual(segmentation[0].shape , __UpperCamelCase )
snake_case_ = image_processor.post_process_semantic_segmentation(outputs=__UpperCamelCase )
snake_case_ = torch.Size((32, 32) )
self.assertEqual(segmentation[0].shape , __UpperCamelCase )
| 46 | 0 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
_lowercase = {
'''configuration_groupvit''': [
'''GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''GroupViTConfig''',
'''GroupViTOnnxConfig''',
'''GroupViTTextConfig''',
'''GroupViTVisionConfig''',
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = [
'''GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''GroupViTModel''',
'''GroupViTPreTrainedModel''',
'''GroupViTTextModel''',
'''GroupViTVisionModel''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowercase = [
'''TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TFGroupViTModel''',
'''TFGroupViTPreTrainedModel''',
'''TFGroupViTTextModel''',
'''TFGroupViTVisionModel''',
]
if TYPE_CHECKING:
from .configuration_groupvit import (
GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP,
GroupViTConfig,
GroupViTOnnxConfig,
GroupViTTextConfig,
GroupViTVisionConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_groupvit import (
GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
GroupViTModel,
GroupViTPreTrainedModel,
GroupViTTextModel,
GroupViTVisionModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_groupvit import (
TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFGroupViTModel,
TFGroupViTPreTrainedModel,
TFGroupViTTextModel,
TFGroupViTVisionModel,
)
else:
import sys
_lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__) | 91 |
'''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 __SCREAMING_SNAKE_CASE ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ):
'''simple docstring'''
lowerCAmelCase__ : List[str] = StableDiffusionXLImgaImgPipeline
lowerCAmelCase__ : str = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"}
lowerCAmelCase__ : List[str] = PipelineTesterMixin.required_optional_params - {"latents"}
lowerCAmelCase__ : List[str] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
lowerCAmelCase__ : int = IMAGE_TO_IMAGE_IMAGE_PARAMS
lowerCAmelCase__ : int = IMAGE_TO_IMAGE_IMAGE_PARAMS
def _lowerCamelCase ( self : str ) -> Union[str, Any]:
torch.manual_seed(0 )
_lowercase : int = UNetaDConditionModel(
block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') ,up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') ,attention_head_dim=(2, 4) ,use_linear_projection=UpperCamelCase ,addition_embed_type='text_time' ,addition_time_embed_dim=8 ,transformer_layers_per_block=(1, 2) ,projection_class_embeddings_input_dim=80 ,cross_attention_dim=64 ,)
_lowercase : List[Any] = EulerDiscreteScheduler(
beta_start=0.0_0_0_8_5 ,beta_end=0.0_1_2 ,steps_offset=1 ,beta_schedule='scaled_linear' ,timestep_spacing='leading' ,)
torch.manual_seed(0 )
_lowercase : int = AutoencoderKL(
block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] ,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] ,latent_channels=4 ,sample_size=128 ,)
torch.manual_seed(0 )
_lowercase : int = CLIPTextConfig(
bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1e-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,hidden_act='gelu' ,projection_dim=32 ,)
_lowercase : Optional[int] = CLIPTextModel(UpperCamelCase )
_lowercase : Optional[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ,local_files_only=UpperCamelCase )
_lowercase : Optional[int] = CLIPTextModelWithProjection(UpperCamelCase )
_lowercase : Union[str, Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ,local_files_only=UpperCamelCase )
_lowercase : Tuple = {
'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 _lowerCamelCase ( self : Union[str, Any] ,UpperCamelCase : Union[str, Any] ,UpperCamelCase : Tuple=0 ) -> str:
_lowercase : Union[str, Any] = floats_tensor((1, 3, 32, 32) ,rng=random.Random(UpperCamelCase ) ).to(UpperCamelCase )
_lowercase : Optional[int] = image / 2 + 0.5
if str(UpperCamelCase ).startswith('mps' ):
_lowercase : List[Any] = torch.manual_seed(UpperCamelCase )
else:
_lowercase : Union[str, Any] = torch.Generator(device=UpperCamelCase ).manual_seed(UpperCamelCase )
_lowercase : List[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.7_5,
}
return inputs
def _lowerCamelCase ( self : List[Any] ) -> Any:
_lowercase : Dict = 'cpu' # ensure determinism for the device-dependent torch.Generator
_lowercase : int = self.get_dummy_components()
_lowercase : Dict = StableDiffusionXLImgaImgPipeline(**UpperCamelCase )
_lowercase : Optional[Any] = sd_pipe.to(UpperCamelCase )
sd_pipe.set_progress_bar_config(disable=UpperCamelCase )
_lowercase : Union[str, Any] = self.get_dummy_inputs(UpperCamelCase )
_lowercase : Optional[int] = sd_pipe(**UpperCamelCase ).images
_lowercase : Any = image[0, -3:, -3:, -1]
assert image.shape == (1, 32, 32, 3)
_lowercase : Optional[int] = np.array([0.4_6_5_6, 0.4_8_4_0, 0.4_4_3_9, 0.6_6_9_8, 0.5_5_7_4, 0.4_5_2_4, 0.5_7_9_9, 0.5_9_4_3, 0.5_1_6_5] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def _lowerCamelCase ( self : Tuple ) -> List[Any]:
super().test_attention_slicing_forward_pass(expected_max_diff=3e-3 )
def _lowerCamelCase ( self : List[Any] ) -> List[Any]:
super().test_inference_batch_single_identical(expected_max_diff=3e-3 )
def _lowerCamelCase ( self : List[Any] ) -> List[str]:
pass
def _lowerCamelCase ( self : List[Any] ) -> List[Any]:
_lowercase : Optional[Any] = self.get_dummy_components()
_lowercase : List[Any] = StableDiffusionXLImgaImgPipeline(**UpperCamelCase )
_lowercase : int = sd_pipe.to(UpperCamelCase )
_lowercase : Any = sd_pipe.to(UpperCamelCase )
sd_pipe.set_progress_bar_config(disable=UpperCamelCase )
# forward without prompt embeds
_lowercase : List[str] = self.get_dummy_inputs(UpperCamelCase )
_lowercase : Optional[int] = 3 * ['this is a negative prompt']
_lowercase : Optional[int] = negative_prompt
_lowercase : List[Any] = 3 * [inputs['prompt']]
_lowercase : Union[str, Any] = sd_pipe(**UpperCamelCase )
_lowercase : Union[str, Any] = output.images[0, -3:, -3:, -1]
# forward with prompt embeds
_lowercase : Tuple = self.get_dummy_inputs(UpperCamelCase )
_lowercase : Optional[Any] = 3 * ['this is a negative prompt']
_lowercase : str = 3 * [inputs.pop('prompt' )]
(
(
_lowercase
) , (
_lowercase
) , (
_lowercase
) , (
_lowercase
) ,
) : Optional[Any] = sd_pipe.encode_prompt(UpperCamelCase ,negative_prompt=UpperCamelCase )
_lowercase : List[str] = sd_pipe(
**UpperCamelCase ,prompt_embeds=UpperCamelCase ,negative_prompt_embeds=UpperCamelCase ,pooled_prompt_embeds=UpperCamelCase ,negative_pooled_prompt_embeds=UpperCamelCase ,)
_lowercase : List[Any] = 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 __SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def _lowerCamelCase ( self : Dict ) -> Optional[int]:
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def _lowerCamelCase ( self : Tuple ,UpperCamelCase : str ,UpperCamelCase : List[str]="cpu" ,UpperCamelCase : str=torch.floataa ,UpperCamelCase : int=0 ) -> Any:
_lowercase : Optional[int] = torch.Generator(device=UpperCamelCase ).manual_seed(UpperCamelCase )
_lowercase : Tuple = np.random.RandomState(UpperCamelCase ).standard_normal((1, 4, 64, 64) )
_lowercase : str = torch.from_numpy(UpperCamelCase ).to(device=UpperCamelCase ,dtype=UpperCamelCase )
_lowercase : str = {
'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 _lowerCamelCase ( self : Optional[Any] ) -> Tuple:
_lowercase : Dict = DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base' )
pipe.to(UpperCamelCase )
pipe.set_progress_bar_config(disable=UpperCamelCase )
_lowercase : int = self.get_inputs(UpperCamelCase )
_lowercase : str = pipe(**UpperCamelCase ).images
_lowercase : Any = image[0, -3:, -3:, -1].flatten()
assert image.shape == (1, 512, 512, 3)
_lowercase : Dict = np.array([0.4_9_4_9_3, 0.4_7_8_9_6, 0.4_0_7_9_8, 0.5_4_2_1_4, 0.5_3_2_1_2, 0.4_8_2_0_2, 0.4_7_6_5_6, 0.4_6_3_2_9, 0.4_8_5_0_6] )
assert np.abs(image_slice - expected_slice ).max() < 7e-3 | 125 | 0 |
"""simple docstring"""
import unittest
from transformers import (
MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
TextClassificationPipeline,
pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow
from .test_pipelines_common import ANY
# These 2 model types require different inputs than those of the usual text models.
SCREAMING_SNAKE_CASE : int = {'''LayoutLMv2Config''', '''LayoutLMv3Config'''}
@is_pipeline_test
class snake_case_ ( unittest.TestCase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_: Dict = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
SCREAMING_SNAKE_CASE_: List[str] = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
if model_mapping is not None:
SCREAMING_SNAKE_CASE_: Union[str, Any] = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
if tf_model_mapping is not None:
SCREAMING_SNAKE_CASE_: int = {
config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
}
@require_torch
def _UpperCAmelCase ( self ):
"""simple docstring"""
A__ = pipeline(
task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='pt' )
A__ = text_classifier('This is great !' )
self.assertEqual(nested_simplify(__a ) , [{'label': 'LABEL_0', 'score': 0.504}] )
A__ = text_classifier('This is great !' , top_k=2 )
self.assertEqual(
nested_simplify(__a ) , [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}] )
A__ = text_classifier(['This is great !', 'This is bad'] , top_k=2 )
self.assertEqual(
nested_simplify(__a ) , [
[{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}],
[{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}],
] , )
A__ = text_classifier('This is great !' , top_k=1 )
self.assertEqual(nested_simplify(__a ) , [{'label': 'LABEL_0', 'score': 0.504}] )
# Legacy behavior
A__ = text_classifier('This is great !' , return_all_scores=__a )
self.assertEqual(nested_simplify(__a ) , [{'label': 'LABEL_0', 'score': 0.504}] )
A__ = text_classifier('This is great !' , return_all_scores=__a )
self.assertEqual(
nested_simplify(__a ) , [[{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}]] )
A__ = text_classifier(['This is great !', 'Something else'] , return_all_scores=__a )
self.assertEqual(
nested_simplify(__a ) , [
[{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}],
[{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}],
] , )
A__ = text_classifier(['This is great !', 'Something else'] , return_all_scores=__a )
self.assertEqual(
nested_simplify(__a ) , [
{'label': 'LABEL_0', 'score': 0.504},
{'label': 'LABEL_0', 'score': 0.504},
] , )
@require_torch
def _UpperCAmelCase ( self ):
"""simple docstring"""
import torch
A__ = pipeline(
task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='pt' , device=torch.device('cpu' ) , )
A__ = text_classifier('This is great !' )
self.assertEqual(nested_simplify(__a ) , [{'label': 'LABEL_0', 'score': 0.504}] )
@require_tf
def _UpperCAmelCase ( self ):
"""simple docstring"""
A__ = pipeline(
task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='tf' )
A__ = text_classifier('This is great !' )
self.assertEqual(nested_simplify(__a ) , [{'label': 'LABEL_0', 'score': 0.504}] )
@slow
@require_torch
def _UpperCAmelCase ( self ):
"""simple docstring"""
A__ = pipeline('text-classification' )
A__ = text_classifier('This is great !' )
self.assertEqual(nested_simplify(__a ) , [{'label': 'POSITIVE', 'score': 1.0}] )
A__ = text_classifier('This is bad !' )
self.assertEqual(nested_simplify(__a ) , [{'label': 'NEGATIVE', 'score': 1.0}] )
A__ = text_classifier('Birds are a type of animal' )
self.assertEqual(nested_simplify(__a ) , [{'label': 'POSITIVE', 'score': 0.988}] )
@slow
@require_tf
def _UpperCAmelCase ( self ):
"""simple docstring"""
A__ = pipeline('text-classification' , framework='tf' )
A__ = text_classifier('This is great !' )
self.assertEqual(nested_simplify(__a ) , [{'label': 'POSITIVE', 'score': 1.0}] )
A__ = text_classifier('This is bad !' )
self.assertEqual(nested_simplify(__a ) , [{'label': 'NEGATIVE', 'score': 1.0}] )
A__ = text_classifier('Birds are a type of animal' )
self.assertEqual(nested_simplify(__a ) , [{'label': 'POSITIVE', 'score': 0.988}] )
def _UpperCAmelCase ( self , __a , __a , __a ):
"""simple docstring"""
A__ = TextClassificationPipeline(model=__a , tokenizer=__a )
return text_classifier, ["HuggingFace is in", "This is another test"]
def _UpperCAmelCase ( self , __a , __a ):
"""simple docstring"""
A__ = text_classifier.model
# Small inputs because BartTokenizer tiny has maximum position embeddings = 22
A__ = 'HuggingFace is in'
A__ = text_classifier(__a )
self.assertEqual(nested_simplify(__a ) , [{'label': ANY(__a ), 'score': ANY(__a )}] )
self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() )
A__ = ['HuggingFace is in ', 'Paris is in France']
A__ = text_classifier(__a )
self.assertEqual(
nested_simplify(__a ) , [{'label': ANY(__a ), 'score': ANY(__a )}, {'label': ANY(__a ), 'score': ANY(__a )}] , )
self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() )
self.assertTrue(outputs[1]['label'] in model.config.idalabel.values() )
# Forcing to get all results with `top_k=None`
# This is NOT the legacy format
A__ = text_classifier(__a , top_k=__a )
A__ = len(model.config.idalabel.values() )
self.assertEqual(
nested_simplify(__a ) , [[{'label': ANY(__a ), 'score': ANY(__a )}] * N, [{'label': ANY(__a ), 'score': ANY(__a )}] * N] , )
A__ = {'text': 'HuggingFace is in ', 'text_pair': 'Paris is in France'}
A__ = text_classifier(__a )
self.assertEqual(
nested_simplify(__a ) , {'label': ANY(__a ), 'score': ANY(__a )} , )
self.assertTrue(outputs['label'] in model.config.idalabel.values() )
# This might be used a text pair, but tokenizer + pipe interaction
# makes it hard to understand that it's not using the pair properly
# https://github.com/huggingface/transformers/issues/17305
# We disabled this usage instead as it was outputting wrong outputs.
A__ = [['HuggingFace is in ', 'Paris is in France']]
with self.assertRaises(__a ):
text_classifier(__a )
# This used to be valid for doing text pairs
# We're keeping it working because of backward compatibility
A__ = text_classifier([[['HuggingFace is in ', 'Paris is in France']]] )
self.assertEqual(
nested_simplify(__a ) , [{'label': ANY(__a ), 'score': ANY(__a )}] , )
self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() )
| 554 |
"""simple docstring"""
from __future__ import annotations
def __lowerCamelCase ( lowerCAmelCase__ ,lowerCAmelCase__ = None ):
A__ = word_bank or []
# create a table
A__ = len(lowerCAmelCase__ ) + 1
A__ = []
for _ in range(lowerCAmelCase__ ):
table.append([] )
# seed value
A__ = [[]] # because empty string has empty combination
# iterate through the indices
for i in range(lowerCAmelCase__ ):
# condition
if table[i] != []:
for word in word_bank:
# slice condition
if target[i : i + len(lowerCAmelCase__ )] == word:
A__ = [
[word, *way] for way in table[i]
]
# adds the word to every combination the current position holds
# now,push that combination to the table[i+len(word)]
table[i + len(lowerCAmelCase__ )] += new_combinations
# combinations are in reverse order so reverse for better output
for combination in table[len(lowerCAmelCase__ )]:
combination.reverse()
return table[len(lowerCAmelCase__ )]
if __name__ == "__main__":
print(all_construct('''jwajalapa''', ['''jwa''', '''j''', '''w''', '''a''', '''la''', '''lapa''']))
print(all_construct('''rajamati''', ['''s''', '''raj''', '''amat''', '''raja''', '''ma''', '''i''', '''t''']))
print(
all_construct(
'''hexagonosaurus''',
['''h''', '''ex''', '''hex''', '''ag''', '''ago''', '''ru''', '''auru''', '''rus''', '''go''', '''no''', '''o''', '''s'''],
)
)
| 554 | 1 |
"""simple docstring"""
from collections.abc import Iterable
from typing import Generic, TypeVar
snake_case_ : int = TypeVar("""_T""")
class snake_case__ ( Generic[_T] ):
def __init__( self : List[str] , lowercase : Iterable[_T] | None = None ):
'''simple docstring'''
UpperCAmelCase : list[_T] = list(iterable or [] )
UpperCAmelCase : list[_T] = []
def __len__( self : List[Any] ):
'''simple docstring'''
return len(self._stacka ) + len(self._stacka )
def __repr__( self : Optional[Any] ):
'''simple docstring'''
return f"""Queue({tuple(self._stacka[::-1] + self._stacka )})"""
def __lowerCAmelCase ( self : List[Any] , lowercase : _T ):
'''simple docstring'''
self._stacka.append(lowercase )
def __lowerCAmelCase ( self : Tuple ):
'''simple docstring'''
UpperCAmelCase : Optional[int] = self._stacka.pop
UpperCAmelCase : Dict = self._stacka.append
if not self._stacka:
while self._stacka:
stacka_append(stacka_pop() )
if not self._stacka:
raise IndexError("Queue is empty" )
return self._stacka.pop()
if __name__ == "__main__":
from doctest import testmod
testmod()
| 595 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
snake_case_ : Tuple = logging.get_logger(__name__)
snake_case_ : Union[str, Any] = {
"""naver-clova-ix/donut-base""": """https://huggingface.co/naver-clova-ix/donut-base/resolve/main/config.json""",
# See all Donut models at https://huggingface.co/models?filter=donut-swin
}
class snake_case__ ( lowerCAmelCase_ ):
SCREAMING_SNAKE_CASE__ = '''donut-swin'''
SCREAMING_SNAKE_CASE__ = {
'''num_attention_heads''': '''num_heads''',
'''num_hidden_layers''': '''num_layers''',
}
def __init__( self : str , lowercase : str=2_24 , lowercase : Optional[Any]=4 , lowercase : Optional[int]=3 , lowercase : Dict=96 , lowercase : Optional[int]=[2, 2, 6, 2] , lowercase : Optional[Any]=[3, 6, 12, 24] , lowercase : Tuple=7 , lowercase : Dict=4.0 , lowercase : Tuple=True , lowercase : Dict=0.0 , lowercase : int=0.0 , lowercase : int=0.1 , lowercase : List[Any]="gelu" , lowercase : Optional[Any]=False , lowercase : Tuple=0.0_2 , lowercase : int=1E-5 , **lowercase : str , ):
'''simple docstring'''
super().__init__(**lowercase )
UpperCAmelCase : Any = image_size
UpperCAmelCase : Any = patch_size
UpperCAmelCase : Optional[Any] = num_channels
UpperCAmelCase : Union[str, Any] = embed_dim
UpperCAmelCase : str = depths
UpperCAmelCase : Dict = len(lowercase )
UpperCAmelCase : Dict = num_heads
UpperCAmelCase : Union[str, Any] = window_size
UpperCAmelCase : Any = mlp_ratio
UpperCAmelCase : Optional[int] = qkv_bias
UpperCAmelCase : List[Any] = hidden_dropout_prob
UpperCAmelCase : Union[str, Any] = attention_probs_dropout_prob
UpperCAmelCase : Union[str, Any] = drop_path_rate
UpperCAmelCase : str = hidden_act
UpperCAmelCase : Any = use_absolute_embeddings
UpperCAmelCase : Optional[Any] = layer_norm_eps
UpperCAmelCase : List[Any] = initializer_range
# we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel
# this indicates the channel dimension after the last stage of the model
UpperCAmelCase : Dict = int(embed_dim * 2 ** (len(lowercase ) - 1) )
| 595 | 1 |
"""simple docstring"""
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
A_ = logging.get_logger(__name__)
A_ = {
'''junnyu/roformer_chinese_small''': '''https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json''',
'''junnyu/roformer_chinese_base''': '''https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json''',
'''junnyu/roformer_chinese_char_small''': (
'''https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json'''
),
'''junnyu/roformer_chinese_char_base''': (
'''https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json'''
),
'''junnyu/roformer_small_discriminator''': (
'''https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json'''
),
'''junnyu/roformer_small_generator''': (
'''https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json'''
),
# See all RoFormer models at https://huggingface.co/models?filter=roformer
}
class lowercase( __a ):
'''simple docstring'''
lowercase__ = "roformer"
def __init__( self: List[str], a_: Tuple=50_000, a_: Optional[Any]=None, a_: List[str]=768, a_: Union[str, Any]=12, a_: Optional[int]=12, a_: Optional[Any]=3_072, a_: List[str]="gelu", a_: List[str]=0.1, a_: Tuple=0.1, a_: Optional[int]=1_536, a_: Any=2, a_: Optional[int]=0.02, a_: Tuple=1E-12, a_: Dict=0, a_: str=False, a_: Dict=True, **a_: Dict, ):
'''simple docstring'''
super().__init__(pad_token_id=a_, **a_ )
_snake_case : int = vocab_size
_snake_case : int = hidden_size if embedding_size is None else embedding_size
_snake_case : Dict = hidden_size
_snake_case : Optional[int] = num_hidden_layers
_snake_case : Any = num_attention_heads
_snake_case : Dict = hidden_act
_snake_case : Optional[int] = intermediate_size
_snake_case : List[Any] = hidden_dropout_prob
_snake_case : Union[str, Any] = attention_probs_dropout_prob
_snake_case : Any = max_position_embeddings
_snake_case : Tuple = type_vocab_size
_snake_case : List[Any] = initializer_range
_snake_case : List[Any] = layer_norm_eps
_snake_case : Optional[Any] = rotary_value
_snake_case : List[str] = use_cache
class lowercase( __a ):
'''simple docstring'''
@property
def UpperCamelCase_ ( self: Dict ):
'''simple docstring'''
if self.task == "multiple-choice":
_snake_case : str = {0: """batch""", 1: """choice""", 2: """sequence"""}
else:
_snake_case : List[str] = {0: """batch""", 1: """sequence"""}
_snake_case : List[Any] = {0: """batch""", 1: """sequence"""}
return OrderedDict(
[
("""input_ids""", dynamic_axis),
("""attention_mask""", dynamic_axis),
("""token_type_ids""", dynamic_axis),
] )
| 28 |
"""simple docstring"""
import argparse
import collections
import json
from pathlib import Path
import requests
import torch
import yaml
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import (
MobileViTImageProcessor,
MobileViTVaConfig,
MobileViTVaForImageClassification,
MobileViTVaForSemanticSegmentation,
)
from transformers.utils import logging
logging.set_verbosity_info()
A_ = logging.get_logger(__name__)
def UpperCAmelCase__ (snake_case__ : Optional[int] ):
"""simple docstring"""
print("""Loading config file...""" )
def flatten_yaml_as_dict(snake_case__ : List[Any] , snake_case__ : Optional[Any]="" , snake_case__ : Tuple="." ):
_snake_case : Union[str, Any] = []
for k, v in d.items():
_snake_case : List[str] = parent_key + sep + k if parent_key else k
if isinstance(snake_case__ , collections.abc.MutableMapping ):
items.extend(flatten_yaml_as_dict(snake_case__ , snake_case__ , sep=snake_case__ ).items() )
else:
items.append((new_key, v) )
return dict(snake_case__ )
_snake_case : Dict = argparse.Namespace()
with open(snake_case__ , """r""" ) as yaml_file:
try:
_snake_case : List[Any] = yaml.load(snake_case__ , Loader=yaml.FullLoader )
_snake_case : Any = flatten_yaml_as_dict(snake_case__ )
for k, v in flat_cfg.items():
setattr(snake_case__ , snake_case__ , snake_case__ )
except yaml.YAMLError as exc:
logger.error("""Error while loading config file: {}. Error message: {}""".format(snake_case__ , str(snake_case__ ) ) )
return config
def UpperCAmelCase__ (snake_case__ : int , snake_case__ : int ):
"""simple docstring"""
_snake_case : Dict = MobileViTVaConfig()
_snake_case : Optional[int] = False
# dataset
if task_name.startswith("""imagenet1k_""" ):
_snake_case : Dict = 10_00
if int(task_name.strip().split("""_""" )[-1] ) == 3_84:
_snake_case : Union[str, Any] = 3_84
else:
_snake_case : Optional[Any] = 2_56
_snake_case : str = """imagenet-1k-id2label.json"""
elif task_name.startswith("""imagenet21k_to_1k_""" ):
_snake_case : str = 2_10_00
if int(task_name.strip().split("""_""" )[-1] ) == 3_84:
_snake_case : Dict = 3_84
else:
_snake_case : Union[str, Any] = 2_56
_snake_case : Tuple = """imagenet-22k-id2label.json"""
elif task_name.startswith("""ade20k_""" ):
_snake_case : Tuple = 1_51
_snake_case : str = 5_12
_snake_case : List[Any] = """ade20k-id2label.json"""
_snake_case : Union[str, Any] = True
elif task_name.startswith("""voc_""" ):
_snake_case : List[Any] = 21
_snake_case : List[str] = 5_12
_snake_case : int = """pascal-voc-id2label.json"""
_snake_case : int = True
# orig_config
_snake_case : int = load_orig_config_file(snake_case__ )
assert getattr(snake_case__ , """model.classification.name""" , -1 ) == "mobilevit_v2", "Invalid model"
_snake_case : str = getattr(snake_case__ , """model.classification.mitv2.width_multiplier""" , 1.0 )
assert (
getattr(snake_case__ , """model.classification.mitv2.attn_norm_layer""" , -1 ) == "layer_norm_2d"
), "Norm layers other than layer_norm_2d is not supported"
_snake_case : int = getattr(snake_case__ , """model.classification.activation.name""" , """swish""" )
# config.image_size == getattr(orig_config, 'sampler.bs.crop_size_width', 256)
if is_segmentation_model:
_snake_case : Tuple = getattr(snake_case__ , """model.segmentation.output_stride""" , 16 )
if "_deeplabv3" in task_name:
_snake_case : Any = getattr(snake_case__ , """model.segmentation.deeplabv3.aspp_rates""" , [12, 24, 36] )
_snake_case : Tuple = getattr(snake_case__ , """model.segmentation.deeplabv3.aspp_out_channels""" , 5_12 )
_snake_case : Any = getattr(snake_case__ , """model.segmentation.deeplabv3.aspp_dropout""" , 0.1 )
# id2label
_snake_case : Union[str, Any] = """huggingface/label-files"""
_snake_case : Any = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type="""dataset""" ) , """r""" ) )
_snake_case : List[Any] = {int(snake_case__ ): v for k, v in idalabel.items()}
_snake_case : Tuple = idalabel
_snake_case : Any = {v: k for k, v in idalabel.items()}
return config
def UpperCAmelCase__ (snake_case__ : Optional[Any] , snake_case__ : Tuple , snake_case__ : List[Any] ):
"""simple docstring"""
_snake_case : List[str] = dct.pop(snake_case__ )
_snake_case : List[Any] = val
def UpperCAmelCase__ (snake_case__ : Optional[Any] , snake_case__ : int=False ):
"""simple docstring"""
if base_model:
_snake_case : Any = """"""
else:
_snake_case : Union[str, Any] = """mobilevitv2."""
_snake_case : Dict = []
for k in state_dict.keys():
if k[:8] == "encoder.":
_snake_case : List[str] = k[8:]
else:
_snake_case : str = k
if ".block." in k:
_snake_case : Optional[int] = k_new.replace(""".block.""" , """.""" )
if ".conv." in k:
_snake_case : Union[str, Any] = k_new.replace(""".conv.""" , """.convolution.""" )
if ".norm." in k:
_snake_case : str = k_new.replace(""".norm.""" , """.normalization.""" )
if "conv_1." in k:
_snake_case : int = k_new.replace("""conv_1.""" , F"{model_prefix}conv_stem." )
for i in [1, 2]:
if F"layer_{i}." in k:
_snake_case : Tuple = k_new.replace(F"layer_{i}." , F"{model_prefix}encoder.layer.{i-1}.layer." )
if ".exp_1x1." in k:
_snake_case : Optional[Any] = k_new.replace(""".exp_1x1.""" , """.expand_1x1.""" )
if ".red_1x1." in k:
_snake_case : Optional[Any] = k_new.replace(""".red_1x1.""" , """.reduce_1x1.""" )
for i in [3, 4, 5]:
if F"layer_{i}.0." in k:
_snake_case : Tuple = k_new.replace(F"layer_{i}.0." , F"{model_prefix}encoder.layer.{i-1}.downsampling_layer." )
if F"layer_{i}.1.local_rep.0." in k:
_snake_case : Any = k_new.replace(F"layer_{i}.1.local_rep.0." , F"{model_prefix}encoder.layer.{i-1}.conv_kxk." )
if F"layer_{i}.1.local_rep.1." in k:
_snake_case : str = k_new.replace(F"layer_{i}.1.local_rep.1." , F"{model_prefix}encoder.layer.{i-1}.conv_1x1." )
for i in [3, 4, 5]:
if i == 3:
_snake_case : Optional[Any] = [0, 1]
elif i == 4:
_snake_case : Any = [0, 1, 2, 3]
elif i == 5:
_snake_case : List[Any] = [0, 1, 2]
for j in j_in:
if F"layer_{i}.1.global_rep.{j}." in k:
_snake_case : Any = k_new.replace(
F"layer_{i}.1.global_rep.{j}." , F"{model_prefix}encoder.layer.{i-1}.transformer.layer.{j}." )
if F"layer_{i}.1.global_rep.{j+1}." in k:
_snake_case : List[Any] = k_new.replace(
F"layer_{i}.1.global_rep.{j+1}." , F"{model_prefix}encoder.layer.{i-1}.layernorm." )
if F"layer_{i}.1.conv_proj." in k:
_snake_case : Union[str, Any] = k_new.replace(F"layer_{i}.1.conv_proj." , F"{model_prefix}encoder.layer.{i-1}.conv_projection." )
if "pre_norm_attn.0." in k:
_snake_case : List[Any] = k_new.replace("""pre_norm_attn.0.""" , """layernorm_before.""" )
if "pre_norm_attn.1." in k:
_snake_case : Optional[int] = k_new.replace("""pre_norm_attn.1.""" , """attention.""" )
if "pre_norm_ffn.0." in k:
_snake_case : List[Any] = k_new.replace("""pre_norm_ffn.0.""" , """layernorm_after.""" )
if "pre_norm_ffn.1." in k:
_snake_case : Tuple = k_new.replace("""pre_norm_ffn.1.""" , """ffn.conv1.""" )
if "pre_norm_ffn.3." in k:
_snake_case : Any = k_new.replace("""pre_norm_ffn.3.""" , """ffn.conv2.""" )
if "classifier.1." in k:
_snake_case : List[str] = k_new.replace("""classifier.1.""" , """classifier.""" )
if "seg_head." in k:
_snake_case : str = k_new.replace("""seg_head.""" , """segmentation_head.""" )
if ".aspp_layer." in k:
_snake_case : Optional[int] = k_new.replace(""".aspp_layer.""" , """.""" )
if ".aspp_pool." in k:
_snake_case : int = k_new.replace(""".aspp_pool.""" , """.""" )
rename_keys.append((k, k_new) )
return rename_keys
def UpperCAmelCase__ (snake_case__ : str ):
"""simple docstring"""
_snake_case : List[str] = []
for k in state_dict.keys():
if k.startswith("""seg_head.aux_head.""" ):
keys_to_ignore.append(snake_case__ )
for k in keys_to_ignore:
state_dict.pop(snake_case__ , snake_case__ )
def UpperCAmelCase__ ():
"""simple docstring"""
_snake_case : str = """http://images.cocodataset.org/val2017/000000039769.jpg"""
# url = "https://cdn.britannica.com/86/141086-050-9D7C75EE/Gulfstream-G450-business-jet-passengers.jpg"
_snake_case : Any = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw )
return im
@torch.no_grad()
def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Optional[int] , snake_case__ : List[str] , snake_case__ : Tuple ):
"""simple docstring"""
_snake_case : int = get_mobilevitva_config(snake_case__ , snake_case__ )
# load original state_dict
_snake_case : Optional[int] = torch.load(snake_case__ , map_location="""cpu""" )
# load huggingface model
if task_name.startswith("""ade20k_""" ) or task_name.startswith("""voc_""" ):
_snake_case : Any = MobileViTVaForSemanticSegmentation(snake_case__ ).eval()
_snake_case : List[Any] = False
else:
_snake_case : List[Any] = MobileViTVaForImageClassification(snake_case__ ).eval()
_snake_case : Optional[Any] = False
# remove and rename some keys of load the original model
_snake_case : Union[str, Any] = checkpoint
remove_unused_keys(snake_case__ )
_snake_case : List[str] = create_rename_keys(snake_case__ , base_model=snake_case__ )
for rename_key_src, rename_key_dest in rename_keys:
rename_key(snake_case__ , snake_case__ , snake_case__ )
# load modified state_dict
model.load_state_dict(snake_case__ )
# Check outputs on an image, prepared by MobileViTImageProcessor
_snake_case : Optional[int] = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 )
_snake_case : List[str] = image_processor(images=prepare_img() , return_tensors="""pt""" )
_snake_case : Optional[Any] = model(**snake_case__ )
# verify classification model
if task_name.startswith("""imagenet""" ):
_snake_case : List[str] = outputs.logits
_snake_case : Any = logits.argmax(-1 ).item()
print("""Predicted class:""" , model.config.idalabel[predicted_class_idx] )
if task_name.startswith("""imagenet1k_256""" ) and config.width_multiplier == 1.0:
# expected_logits for base variant
_snake_case : List[str] = torch.tensor([-1.6_3_3_6e0_0, -7.3_2_0_4e-0_2, -5.1_8_8_3e-0_1] )
assert torch.allclose(logits[0, :3] , snake_case__ , atol=1e-4 )
Path(snake_case__ ).mkdir(exist_ok=snake_case__ )
print(F"Saving model {task_name} to {pytorch_dump_folder_path}" )
model.save_pretrained(snake_case__ )
print(F"Saving image processor to {pytorch_dump_folder_path}" )
image_processor.save_pretrained(snake_case__ )
if __name__ == "__main__":
A_ = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--task''',
default='''imagenet1k_256''',
type=str,
help=(
'''Name of the task for which the MobileViTV2 model you\'d like to convert is trained on . '''
'''
Classification (ImageNet-1k)
- MobileViTV2 (256x256) : imagenet1k_256
- MobileViTV2 (Trained on 256x256 and Finetuned on 384x384) : imagenet1k_384
- MobileViTV2 (Trained on ImageNet-21k and Finetuned on ImageNet-1k 256x256) :
imagenet21k_to_1k_256
- MobileViTV2 (Trained on ImageNet-21k, Finetuned on ImageNet-1k 256x256, and Finetuned on
ImageNet-1k 384x384) : imagenet21k_to_1k_384
Segmentation
- ADE20K Dataset : ade20k_deeplabv3
- Pascal VOC 2012 Dataset: voc_deeplabv3
'''
),
choices=[
'''imagenet1k_256''',
'''imagenet1k_384''',
'''imagenet21k_to_1k_256''',
'''imagenet21k_to_1k_384''',
'''ade20k_deeplabv3''',
'''voc_deeplabv3''',
],
)
parser.add_argument(
'''--orig_checkpoint_path''', required=True, type=str, help='''Path to the original state dict (.pt file).'''
)
parser.add_argument('''--orig_config_path''', required=True, type=str, help='''Path to the original config file.''')
parser.add_argument(
'''--pytorch_dump_folder_path''', required=True, type=str, help='''Path to the output PyTorch model directory.'''
)
A_ = parser.parse_args()
convert_mobilevitva_checkpoint(
args.task, args.orig_checkpoint_path, args.orig_config_path, args.pytorch_dump_folder_path
)
| 28 | 1 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_torch_available,
)
lowercase__ : Dict = {
'configuration_gpt_bigcode': ['GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GPTBigCodeConfig'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase__ : int = [
'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__ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 98 |
from math import factorial
def snake_case_ ( lowerCAmelCase_ : int = 100 ):
return sum(map(lowerCAmelCase_ , str(factorial(lowerCAmelCase_ ) ) ) )
if __name__ == "__main__":
print(solution(int(input('''Enter the Number: ''').strip()))) | 149 | 0 |
'''simple docstring'''
import io
import json
import unittest
from parameterized import parameterized
from transformers import FSMTForConditionalGeneration, FSMTTokenizer
from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device
from utils import calculate_bleu
UpperCamelCase_ = get_tests_dir() + "/test_data/fsmt/fsmt_val_data.json"
with io.open(filename, "r", encoding="utf-8") as f:
UpperCamelCase_ = json.load(f)
@require_torch
class _a ( unittest.TestCase ):
'''simple docstring'''
def UpperCamelCase_ ( self, A ):
'''simple docstring'''
return FSMTTokenizer.from_pretrained(A )
def UpperCamelCase_ ( self, A ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : int = FSMTForConditionalGeneration.from_pretrained(A ).to(A )
if torch_device == "cuda":
model.half()
return model
@parameterized.expand(
[
['en-ru', 26.0],
['ru-en', 22.0],
['en-de', 22.0],
['de-en', 29.0],
] )
@slow
def UpperCamelCase_ ( self, A, A ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[Any] = F"facebook/wmt19-{pair}"
SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer(A )
SCREAMING_SNAKE_CASE : Tuple = self.get_model(A )
SCREAMING_SNAKE_CASE : List[Any] = bleu_data[pair]['src']
SCREAMING_SNAKE_CASE : Dict = bleu_data[pair]['tgt']
SCREAMING_SNAKE_CASE : str = tokenizer(A, return_tensors='pt', truncation=A, padding='longest' ).to(A )
SCREAMING_SNAKE_CASE : List[str] = model.generate(
input_ids=batch.input_ids, num_beams=8, )
SCREAMING_SNAKE_CASE : Dict = tokenizer.batch_decode(
A, skip_special_tokens=A, clean_up_tokenization_spaces=A )
SCREAMING_SNAKE_CASE : Any = calculate_bleu(A, A )
print(A )
self.assertGreaterEqual(scores['bleu'], A )
| 508 |
'''simple docstring'''
import warnings
from collections import OrderedDict
from typing import Any, Mapping, Optional
from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging
UpperCamelCase_ = logging.get_logger(__name__)
UpperCamelCase_ = {
"facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/config.json",
# See all BART models at https://huggingface.co/models?filter=bart
}
class _a ( SCREAMING_SNAKE_CASE ):
'''simple docstring'''
A : str = '''bart'''
A : Dict = ['''past_key_values''']
A : Tuple = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''}
def __init__( self, A=50_265, A=1_024, A=12, A=4_096, A=16, A=12, A=4_096, A=16, A=0.0, A=0.0, A="gelu", A=1_024, A=0.1, A=0.0, A=0.0, A=0.02, A=0.0, A=False, A=True, A=3, A=1, A=0, A=2, A=True, A=2, A=2, **A, ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Dict = vocab_size
SCREAMING_SNAKE_CASE : int = max_position_embeddings
SCREAMING_SNAKE_CASE : Dict = d_model
SCREAMING_SNAKE_CASE : int = encoder_ffn_dim
SCREAMING_SNAKE_CASE : Optional[Any] = encoder_layers
SCREAMING_SNAKE_CASE : List[Any] = encoder_attention_heads
SCREAMING_SNAKE_CASE : Optional[int] = decoder_ffn_dim
SCREAMING_SNAKE_CASE : List[Any] = decoder_layers
SCREAMING_SNAKE_CASE : str = decoder_attention_heads
SCREAMING_SNAKE_CASE : Any = dropout
SCREAMING_SNAKE_CASE : str = attention_dropout
SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout
SCREAMING_SNAKE_CASE : List[Any] = activation_function
SCREAMING_SNAKE_CASE : str = init_std
SCREAMING_SNAKE_CASE : Optional[Any] = encoder_layerdrop
SCREAMING_SNAKE_CASE : Optional[int] = decoder_layerdrop
SCREAMING_SNAKE_CASE : List[str] = classifier_dropout
SCREAMING_SNAKE_CASE : int = use_cache
SCREAMING_SNAKE_CASE : Dict = encoder_layers
SCREAMING_SNAKE_CASE : List[Any] = scale_embedding # scale factor will be sqrt(d_model) if True
super().__init__(
num_labels=A, pad_token_id=A, bos_token_id=A, eos_token_id=A, is_encoder_decoder=A, decoder_start_token_id=A, forced_eos_token_id=A, **A, )
# ensure backward compatibility for BART CNN models
if self.forced_bos_token_id is None and kwargs.get('force_bos_token_to_be_generated', A ):
SCREAMING_SNAKE_CASE : str = self.bos_token_id
warnings.warn(
F"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. "
'The config can simply be saved and uploaded again to be fixed.' )
class _a ( SCREAMING_SNAKE_CASE ):
'''simple docstring'''
@property
def UpperCamelCase_ ( self ):
'''simple docstring'''
if self.task in ["default", "seq2seq-lm"]:
SCREAMING_SNAKE_CASE : Tuple = OrderedDict(
[
('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
] )
if self.use_past:
SCREAMING_SNAKE_CASE : Union[str, Any] = {0: 'batch'}
SCREAMING_SNAKE_CASE : Any = {0: 'batch', 1: 'past_decoder_sequence + sequence'}
else:
SCREAMING_SNAKE_CASE : str = {0: 'batch', 1: 'decoder_sequence'}
SCREAMING_SNAKE_CASE : Any = {0: 'batch', 1: 'decoder_sequence'}
if self.use_past:
self.fill_with_past_key_values_(A, direction='inputs' )
elif self.task == "causal-lm":
# TODO: figure this case out.
SCREAMING_SNAKE_CASE : int = OrderedDict(
[
('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
] )
if self.use_past:
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.num_layers
for i in range(A ):
SCREAMING_SNAKE_CASE : str = {0: 'batch', 2: 'past_sequence + sequence'}
SCREAMING_SNAKE_CASE : List[Any] = {0: 'batch', 2: 'past_sequence + sequence'}
else:
SCREAMING_SNAKE_CASE : List[Any] = OrderedDict(
[
('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
('decoder_input_ids', {0: 'batch', 1: 'decoder_sequence'}),
('decoder_attention_mask', {0: 'batch', 1: 'decoder_sequence'}),
] )
return common_inputs
@property
def UpperCamelCase_ ( self ):
'''simple docstring'''
if self.task in ["default", "seq2seq-lm"]:
SCREAMING_SNAKE_CASE : List[Any] = super().outputs
else:
SCREAMING_SNAKE_CASE : Dict = super(A, self ).outputs
if self.use_past:
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.num_layers
for i in range(A ):
SCREAMING_SNAKE_CASE : List[Any] = {0: 'batch', 2: 'past_sequence + sequence'}
SCREAMING_SNAKE_CASE : Dict = {0: 'batch', 2: 'past_sequence + sequence'}
return common_outputs
def UpperCamelCase_ ( self, A, A = -1, A = -1, A = False, A = None, ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : str = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
A, A, A, A, A )
# Generate decoder inputs
SCREAMING_SNAKE_CASE : Optional[int] = seq_length if not self.use_past else 1
SCREAMING_SNAKE_CASE : str = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
A, A, A, A, A )
SCREAMING_SNAKE_CASE : List[str] = {F"decoder_{name}": tensor for name, tensor in decoder_inputs.items()}
SCREAMING_SNAKE_CASE : Optional[Any] = dict(**A, **A )
if self.use_past:
if not is_torch_available():
raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' )
else:
import torch
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = common_inputs['input_ids'].shape
SCREAMING_SNAKE_CASE : Tuple = common_inputs['decoder_input_ids'].shape[1]
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.num_attention_heads
SCREAMING_SNAKE_CASE : str = (
batch,
num_encoder_attention_heads,
encoder_seq_length,
self._config.hidden_size // num_encoder_attention_heads,
)
SCREAMING_SNAKE_CASE : Union[str, Any] = decoder_seq_length + 3
SCREAMING_SNAKE_CASE : int = (
batch,
num_decoder_attention_heads,
decoder_past_length,
self._config.hidden_size // num_decoder_attention_heads,
)
SCREAMING_SNAKE_CASE : Optional[int] = torch.cat(
[common_inputs['decoder_attention_mask'], torch.ones(A, A )], dim=1 )
SCREAMING_SNAKE_CASE : List[Any] = []
# If the number of encoder and decoder layers are present in the model configuration, both are considered
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = self.num_layers
SCREAMING_SNAKE_CASE : Dict = min(A, A )
SCREAMING_SNAKE_CASE : List[str] = max(A, A ) - min_num_layers
SCREAMING_SNAKE_CASE : Any = 'encoder' if num_encoder_layers > num_decoder_layers else 'decoder'
for _ in range(A ):
common_inputs["past_key_values"].append(
(
torch.zeros(A ),
torch.zeros(A ),
torch.zeros(A ),
torch.zeros(A ),
) )
# TODO: test this.
SCREAMING_SNAKE_CASE : Optional[int] = encoder_shape if remaining_side_name == 'encoder' else decoder_shape
for _ in range(A, A ):
common_inputs["past_key_values"].append((torch.zeros(A ), torch.zeros(A )) )
return common_inputs
def UpperCamelCase_ ( self, A, A = -1, A = -1, A = False, A = None, ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : List[str] = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
A, A, A, A, A )
if self.use_past:
if not is_torch_available():
raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' )
else:
import torch
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = common_inputs['input_ids'].shape
# Not using the same length for past_key_values
SCREAMING_SNAKE_CASE : List[str] = seqlen + 2
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = self.num_layers
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = self.num_attention_heads
SCREAMING_SNAKE_CASE : int = (
batch,
num_encoder_attention_heads,
past_key_values_length,
self._config.hidden_size // num_encoder_attention_heads,
)
SCREAMING_SNAKE_CASE : Optional[int] = common_inputs['attention_mask'].dtype
SCREAMING_SNAKE_CASE : Tuple = torch.cat(
[common_inputs['attention_mask'], torch.ones(A, A, dtype=A )], dim=1 )
SCREAMING_SNAKE_CASE : Union[str, Any] = [
(torch.zeros(A ), torch.zeros(A )) for _ in range(A )
]
return common_inputs
def UpperCamelCase_ ( self, A, A = -1, A = -1, A = False, A = None, ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : str = compute_effective_axis_dimension(
A, fixed_dimension=OnnxConfig.default_fixed_batch, num_token_to_add=0 )
# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
SCREAMING_SNAKE_CASE : List[Any] = tokenizer.num_special_tokens_to_add(A )
SCREAMING_SNAKE_CASE : int = compute_effective_axis_dimension(
A, fixed_dimension=OnnxConfig.default_fixed_sequence, num_token_to_add=A )
# Generate dummy inputs according to compute batch and sequence
SCREAMING_SNAKE_CASE : int = [' '.join([tokenizer.unk_token] ) * seq_length] * batch_size
SCREAMING_SNAKE_CASE : Tuple = dict(tokenizer(A, return_tensors=A ) )
return common_inputs
def UpperCamelCase_ ( self, A, A = -1, A = -1, A = False, A = None, ):
'''simple docstring'''
if self.task in ["default", "seq2seq-lm"]:
SCREAMING_SNAKE_CASE : List[Any] = self._generate_dummy_inputs_for_default_and_seqaseq_lm(
A, batch_size=A, seq_length=A, is_pair=A, framework=A )
elif self.task == "causal-lm":
SCREAMING_SNAKE_CASE : List[Any] = self._generate_dummy_inputs_for_causal_lm(
A, batch_size=A, seq_length=A, is_pair=A, framework=A )
else:
SCREAMING_SNAKE_CASE : Tuple = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
A, batch_size=A, seq_length=A, is_pair=A, framework=A )
return common_inputs
def UpperCamelCase_ ( self, A, A, A, A ):
'''simple docstring'''
if self.task in ["default", "seq2seq-lm"]:
SCREAMING_SNAKE_CASE : List[str] = super()._flatten_past_key_values_(A, A, A, A )
else:
SCREAMING_SNAKE_CASE : Dict = super(A, self )._flatten_past_key_values_(
A, A, A, A )
| 508 | 1 |
class A_ :
'''simple docstring'''
def __init__(self , lowercase__ , lowercase__ , lowercase__ ) -> List[Any]:
__UpperCAmelCase = None
__UpperCAmelCase = None
__UpperCAmelCase = graph
self._normalize_graph(lowercase__ , lowercase__ )
__UpperCAmelCase = len(lowercase__ )
__UpperCAmelCase = None
def lowerCAmelCase_ (self , lowercase__ , lowercase__ ) -> Any:
if sources is int:
__UpperCAmelCase = [sources]
if sinks is int:
__UpperCAmelCase = [sinks]
if len(lowercase__ ) == 0 or len(lowercase__ ) == 0:
return
__UpperCAmelCase = sources[0]
__UpperCAmelCase = sinks[0]
# make fake vertex if there are more
# than one source or sink
if len(lowercase__ ) > 1 or len(lowercase__ ) > 1:
__UpperCAmelCase = 0
for i in sources:
max_input_flow += sum(self.graph[i] )
__UpperCAmelCase = len(self.graph ) + 1
for room in self.graph:
room.insert(0 , 0 )
self.graph.insert(0 , [0] * size )
for i in sources:
__UpperCAmelCase = max_input_flow
__UpperCAmelCase = 0
__UpperCAmelCase = len(self.graph ) + 1
for room in self.graph:
room.append(0 )
self.graph.append([0] * size )
for i in sinks:
__UpperCAmelCase = max_input_flow
__UpperCAmelCase = size - 1
def lowerCAmelCase_ (self ) -> Tuple:
if self.maximum_flow_algorithm is None:
raise Exception('''You need to set maximum flow algorithm before.''' )
if self.source_index is None or self.sink_index is None:
return 0
self.maximum_flow_algorithm.execute()
return self.maximum_flow_algorithm.getMaximumFlow()
def lowerCAmelCase_ (self , lowercase__ ) -> int:
__UpperCAmelCase = algorithm(self )
class A_ :
'''simple docstring'''
def __init__(self , lowercase__ ) -> List[Any]:
__UpperCAmelCase = flow_network
__UpperCAmelCase = flow_network.verticesCount
__UpperCAmelCase = flow_network.sourceIndex
__UpperCAmelCase = flow_network.sinkIndex
# it's just a reference, so you shouldn't change
# it in your algorithms, use deep copy before doing that
__UpperCAmelCase = flow_network.graph
__UpperCAmelCase = False
def lowerCAmelCase_ (self ) -> Dict:
if not self.executed:
self._algorithm()
__UpperCAmelCase = True
def lowerCAmelCase_ (self ) -> Optional[Any]:
pass
class A_ ( _a ):
'''simple docstring'''
def __init__(self , lowercase__ ) -> List[str]:
super().__init__(lowercase__ )
# use this to save your result
__UpperCAmelCase = -1
def lowerCAmelCase_ (self ) -> Optional[Any]:
if not self.executed:
raise Exception('''You should execute algorithm before using its result!''' )
return self.maximum_flow
class A_ ( _a ):
'''simple docstring'''
def __init__(self , lowercase__ ) -> int:
super().__init__(lowercase__ )
__UpperCAmelCase = [[0] * self.verticies_count for i in range(self.verticies_count )]
__UpperCAmelCase = [0] * self.verticies_count
__UpperCAmelCase = [0] * self.verticies_count
def lowerCAmelCase_ (self ) -> Union[str, Any]:
__UpperCAmelCase = self.verticies_count
# push some substance to graph
for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ):
self.preflow[self.source_index][nextvertex_index] += bandwidth
self.preflow[nextvertex_index][self.source_index] -= bandwidth
self.excesses[nextvertex_index] += bandwidth
# Relabel-to-front selection rule
__UpperCAmelCase = [
i
for i in range(self.verticies_count )
if i != self.source_index and i != self.sink_index
]
# move through list
__UpperCAmelCase = 0
while i < len(lowercase__ ):
__UpperCAmelCase = vertices_list[i]
__UpperCAmelCase = self.heights[vertex_index]
self.process_vertex(lowercase__ )
if self.heights[vertex_index] > previous_height:
# if it was relabeled, swap elements
# and start from 0 index
vertices_list.insert(0 , vertices_list.pop(lowercase__ ) )
__UpperCAmelCase = 0
else:
i += 1
__UpperCAmelCase = sum(self.preflow[self.source_index] )
def lowerCAmelCase_ (self , lowercase__ ) -> int:
while self.excesses[vertex_index] > 0:
for neighbour_index in range(self.verticies_count ):
# if it's neighbour and current vertex is higher
if (
self.graph[vertex_index][neighbour_index]
- self.preflow[vertex_index][neighbour_index]
> 0
and self.heights[vertex_index] > self.heights[neighbour_index]
):
self.push(lowercase__ , lowercase__ )
self.relabel(lowercase__ )
def lowerCAmelCase_ (self , lowercase__ , lowercase__ ) -> Optional[Any]:
__UpperCAmelCase = min(
self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , )
self.preflow[from_index][to_index] += preflow_delta
self.preflow[to_index][from_index] -= preflow_delta
self.excesses[from_index] -= preflow_delta
self.excesses[to_index] += preflow_delta
def lowerCAmelCase_ (self , lowercase__ ) -> List[str]:
__UpperCAmelCase = None
for to_index in range(self.verticies_count ):
if (
self.graph[vertex_index][to_index]
- self.preflow[vertex_index][to_index]
> 0
) and (min_height is None or self.heights[to_index] < min_height):
__UpperCAmelCase = self.heights[to_index]
if min_height is not None:
__UpperCAmelCase = min_height + 1
if __name__ == "__main__":
A_ : Optional[Any] = [0]
A_ : str = [3]
# graph = [
# [0, 0, 4, 6, 0, 0],
# [0, 0, 5, 2, 0, 0],
# [0, 0, 0, 0, 4, 4],
# [0, 0, 0, 0, 6, 6],
# [0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0],
# ]
A_ : Tuple = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]]
# prepare our network
A_ : Optional[Any] = FlowNetwork(graph, entrances, exits)
# set algorithm
flow_network.set_maximum_flow_algorithm(PushRelabelExecutor)
# and calculate
A_ : str = flow_network.find_maximum_flow()
print(F"""maximum flow is {maximum_flow}""")
| 303 |
from __future__ import annotations
from sys import maxsize
from typing import Generic, TypeVar
A_ : int = TypeVar('T')
def __a ( SCREAMING_SNAKE_CASE ) -> int:
'''simple docstring'''
return (position - 1) // 2
def __a ( SCREAMING_SNAKE_CASE ) -> int:
'''simple docstring'''
return (2 * position) + 1
def __a ( SCREAMING_SNAKE_CASE ) -> int:
'''simple docstring'''
return (2 * position) + 2
class A_ ( Generic[T] ):
'''simple docstring'''
def __init__(self ) -> None:
__UpperCAmelCase = []
__UpperCAmelCase = {}
__UpperCAmelCase = 0
def __len__(self ) -> int:
return self.elements
def __repr__(self ) -> str:
return str(self.heap )
def lowerCAmelCase_ (self ) -> bool:
# Check if the priority queue is empty
return self.elements == 0
def lowerCAmelCase_ (self , lowercase__ , lowercase__ ) -> None:
# Add an element with given priority to the queue
self.heap.append((elem, weight) )
__UpperCAmelCase = self.elements
self.elements += 1
self._bubble_up(lowercase__ )
def lowerCAmelCase_ (self ) -> T:
# Remove and return the element with lowest weight (highest priority)
if self.elements > 1:
self._swap_nodes(0 , self.elements - 1 )
__UpperCAmelCase , __UpperCAmelCase = self.heap.pop()
del self.position_map[elem]
self.elements -= 1
if self.elements > 0:
__UpperCAmelCase , __UpperCAmelCase = self.heap[0]
self._bubble_down(lowercase__ )
return elem
def lowerCAmelCase_ (self , lowercase__ , lowercase__ ) -> None:
# Update the weight of the given key
__UpperCAmelCase = self.position_map[elem]
__UpperCAmelCase = (elem, weight)
if position > 0:
__UpperCAmelCase = get_parent_position(lowercase__ )
__UpperCAmelCase , __UpperCAmelCase = self.heap[parent_position]
if parent_weight > weight:
self._bubble_up(lowercase__ )
else:
self._bubble_down(lowercase__ )
else:
self._bubble_down(lowercase__ )
def lowerCAmelCase_ (self , lowercase__ ) -> None:
# Place a node at the proper position (upward movement) [to be used internally
# only]
__UpperCAmelCase = self.position_map[elem]
if curr_pos == 0:
return None
__UpperCAmelCase = get_parent_position(lowercase__ )
__UpperCAmelCase , __UpperCAmelCase = self.heap[curr_pos]
__UpperCAmelCase , __UpperCAmelCase = self.heap[parent_position]
if parent_weight > weight:
self._swap_nodes(lowercase__ , lowercase__ )
return self._bubble_up(lowercase__ )
return None
def lowerCAmelCase_ (self , lowercase__ ) -> None:
# Place a node at the proper position (downward movement) [to be used
# internally only]
__UpperCAmelCase = self.position_map[elem]
__UpperCAmelCase , __UpperCAmelCase = self.heap[curr_pos]
__UpperCAmelCase = get_child_left_position(lowercase__ )
__UpperCAmelCase = get_child_right_position(lowercase__ )
if child_left_position < self.elements and child_right_position < self.elements:
__UpperCAmelCase , __UpperCAmelCase = self.heap[child_left_position]
__UpperCAmelCase , __UpperCAmelCase = self.heap[child_right_position]
if child_right_weight < child_left_weight and child_right_weight < weight:
self._swap_nodes(lowercase__ , lowercase__ )
return self._bubble_down(lowercase__ )
if child_left_position < self.elements:
__UpperCAmelCase , __UpperCAmelCase = self.heap[child_left_position]
if child_left_weight < weight:
self._swap_nodes(lowercase__ , lowercase__ )
return self._bubble_down(lowercase__ )
else:
return None
if child_right_position < self.elements:
__UpperCAmelCase , __UpperCAmelCase = self.heap[child_right_position]
if child_right_weight < weight:
self._swap_nodes(lowercase__ , lowercase__ )
return self._bubble_down(lowercase__ )
return None
def lowerCAmelCase_ (self , lowercase__ , lowercase__ ) -> None:
# Swap the nodes at the given positions
__UpperCAmelCase = self.heap[nodea_pos][0]
__UpperCAmelCase = self.heap[nodea_pos][0]
__UpperCAmelCase , __UpperCAmelCase = (
self.heap[nodea_pos],
self.heap[nodea_pos],
)
__UpperCAmelCase = nodea_pos
__UpperCAmelCase = nodea_pos
class A_ ( Generic[T] ):
'''simple docstring'''
def __init__(self ) -> None:
__UpperCAmelCase = {}
__UpperCAmelCase = 0
def __repr__(self ) -> str:
return str(self.connections )
def __len__(self ) -> int:
return self.nodes
def lowerCAmelCase_ (self , lowercase__ ) -> None:
# Add a node in the graph if it is not in the graph
if node not in self.connections:
__UpperCAmelCase = {}
self.nodes += 1
def lowerCAmelCase_ (self , lowercase__ , lowercase__ , lowercase__ ) -> None:
# Add an edge between 2 nodes in the graph
self.add_node(lowercase__ )
self.add_node(lowercase__ )
__UpperCAmelCase = weight
__UpperCAmelCase = weight
def __a ( SCREAMING_SNAKE_CASE , ) -> tuple[dict[T, int], dict[T, T | None]]:
'''simple docstring'''
__UpperCAmelCase = {node: maxsize for node in graph.connections}
__UpperCAmelCase = {node: None for node in graph.connections}
__UpperCAmelCase = MinPriorityQueue()
for node, weight in dist.items():
priority_queue.push(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
if priority_queue.is_empty():
return dist, parent
# initialization
__UpperCAmelCase = priority_queue.extract_min()
__UpperCAmelCase = 0
for neighbour in graph.connections[node]:
if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:
__UpperCAmelCase = dist[node] + graph.connections[node][neighbour]
priority_queue.update_key(SCREAMING_SNAKE_CASE , dist[neighbour] )
__UpperCAmelCase = node
# running prim's algorithm
while not priority_queue.is_empty():
__UpperCAmelCase = priority_queue.extract_min()
for neighbour in graph.connections[node]:
if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:
__UpperCAmelCase = dist[node] + graph.connections[node][neighbour]
priority_queue.update_key(SCREAMING_SNAKE_CASE , dist[neighbour] )
__UpperCAmelCase = node
return dist, parent
| 303 | 1 |
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__)
UpperCAmelCase_ : str = {
"facebook/deit-base-distilled-patch16-224": (
"https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json"
),
# See all DeiT models at https://huggingface.co/models?filter=deit
}
class __A ( UpperCamelCase__ ):
UpperCamelCase = """deit"""
def __init__( self :List[Any] , __snake_case :int=7_68 , __snake_case :Tuple=12 , __snake_case :str=12 , __snake_case :List[str]=30_72 , __snake_case :Optional[Any]="gelu" , __snake_case :Optional[Any]=0.0 , __snake_case :Dict=0.0 , __snake_case :Any=0.02 , __snake_case :str=1E-12 , __snake_case :str=2_24 , __snake_case :List[str]=16 , __snake_case :Dict=3 , __snake_case :Dict=True , __snake_case :str=16 , **__snake_case :Tuple , ):
'''simple docstring'''
super().__init__(**__snake_case )
__magic_name__ : int =hidden_size
__magic_name__ : int =num_hidden_layers
__magic_name__ : Tuple =num_attention_heads
__magic_name__ : Union[str, Any] =intermediate_size
__magic_name__ : Union[str, Any] =hidden_act
__magic_name__ : Optional[int] =hidden_dropout_prob
__magic_name__ : Optional[Any] =attention_probs_dropout_prob
__magic_name__ : List[Any] =initializer_range
__magic_name__ : Tuple =layer_norm_eps
__magic_name__ : List[Any] =image_size
__magic_name__ : List[Any] =patch_size
__magic_name__ : int =num_channels
__magic_name__ : int =qkv_bias
__magic_name__ : Union[str, Any] =encoder_stride
class __A ( UpperCamelCase__ ):
UpperCamelCase = version.parse("""1.11""" )
@property
def A__ ( self :Any ):
'''simple docstring'''
return OrderedDict(
[
("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
] )
@property
def A__ ( self :Optional[int] ):
'''simple docstring'''
return 1E-4
| 367 |
import warnings
from contextlib import contextmanager
from ...processing_utils import ProcessorMixin
class __A ( UpperCamelCase__ ):
UpperCamelCase = """Speech2TextFeatureExtractor"""
UpperCamelCase = """Speech2TextTokenizer"""
def __init__( self :Any , __snake_case :int , __snake_case :Any ):
'''simple docstring'''
super().__init__(__snake_case , __snake_case )
__magic_name__ : Optional[int] =self.feature_extractor
__magic_name__ : Any =False
def __call__( self :Tuple , *__snake_case :List[str] , **__snake_case :List[str] ):
'''simple docstring'''
if self._in_target_context_manager:
return self.current_processor(*__snake_case , **__snake_case )
if "raw_speech" in kwargs:
warnings.warn("""Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.""" )
__magic_name__ : Tuple =kwargs.pop("""raw_speech""" )
else:
__magic_name__ : List[Any] =kwargs.pop("""audio""" , __snake_case )
__magic_name__ : Union[str, Any] =kwargs.pop("""sampling_rate""" , __snake_case )
__magic_name__ : Dict =kwargs.pop("""text""" , __snake_case )
if len(__snake_case ) > 0:
__magic_name__ : Union[str, Any] =args[0]
__magic_name__ : int =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 audio is not None:
__magic_name__ : List[str] =self.feature_extractor(__snake_case , *__snake_case , sampling_rate=__snake_case , **__snake_case )
if text is not None:
__magic_name__ : Any =self.tokenizer(__snake_case , **__snake_case )
if text is None:
return inputs
elif audio is None:
return encodings
else:
__magic_name__ : List[str] =encodings["""input_ids"""]
return inputs
def A__ ( self :List[Any] , *__snake_case :str , **__snake_case :List[str] ):
'''simple docstring'''
return self.tokenizer.batch_decode(*__snake_case , **__snake_case )
def A__ ( self :int , *__snake_case :int , **__snake_case :Optional[int] ):
'''simple docstring'''
return self.tokenizer.decode(*__snake_case , **__snake_case )
@contextmanager
def A__ ( self :int ):
'''simple docstring'''
warnings.warn(
"""`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """
"""labels by using the argument `text` of the regular `__call__` method (either in the same call as """
"""your audio inputs, or in a separate call.""" )
__magic_name__ : int =True
__magic_name__ : List[Any] =self.tokenizer
yield
__magic_name__ : List[Any] =self.feature_extractor
__magic_name__ : str =False
| 367 | 1 |
from __future__ import annotations
import math
import random
from collections.abc import Collection
from typing import overload
class UpperCAmelCase :
def __init__(self : List[Any] , snake_case__ : Collection[float] | None = None ) -> None:
'''simple docstring'''
if components is None:
snake_case : Optional[Any] = []
snake_case : List[Any] = list(snake_case__ )
def __len__(self : Union[str, Any] ) -> int:
'''simple docstring'''
return len(self.__components )
def __str__(self : str ) -> str:
'''simple docstring'''
return "(" + ",".join(map(snake_case__ , self.__components ) ) + ")"
def __add__(self : List[Any] , snake_case__ : Vector ) -> Vector:
'''simple docstring'''
snake_case : List[str] = len(self )
if size == len(snake_case__ ):
snake_case : Tuple = [self.__components[i] + other.component(snake_case__ ) for i in range(snake_case__ )]
return Vector(snake_case__ )
else:
raise Exception("must have the same size" )
def __sub__(self : Any , snake_case__ : Vector ) -> Vector:
'''simple docstring'''
snake_case : Tuple = len(self )
if size == len(snake_case__ ):
snake_case : Optional[int] = [self.__components[i] - other.component(snake_case__ ) for i in range(snake_case__ )]
return Vector(snake_case__ )
else: # error case
raise Exception("must have the same size" )
@overload
def __mul__(self : Union[str, Any] , snake_case__ : float ) -> Vector:
'''simple docstring'''
...
@overload
def __mul__(self : Dict , snake_case__ : Vector ) -> float:
'''simple docstring'''
...
def __mul__(self : Optional[Any] , snake_case__ : float | Vector ) -> float | Vector:
'''simple docstring'''
if isinstance(snake_case__ , (float, int) ):
snake_case : int = [c * other for c in self.__components]
return Vector(snake_case__ )
elif isinstance(snake_case__ , snake_case__ ) and len(self ) == len(snake_case__ ):
snake_case : Optional[Any] = len(self )
snake_case : Union[str, Any] = [self.__components[i] * other.component(snake_case__ ) for i in range(snake_case__ )]
return sum(snake_case__ )
else: # error case
raise Exception("invalid operand!" )
def _SCREAMING_SNAKE_CASE (self : Union[str, Any] ) -> Vector:
'''simple docstring'''
return Vector(self.__components )
def _SCREAMING_SNAKE_CASE (self : Any , snake_case__ : int ) -> float:
'''simple docstring'''
if isinstance(snake_case__ , snake_case__ ) and -len(self.__components ) <= i < len(self.__components ):
return self.__components[i]
else:
raise Exception("index out of range" )
def _SCREAMING_SNAKE_CASE (self : Optional[int] , snake_case__ : int , snake_case__ : float ) -> None:
'''simple docstring'''
assert -len(self.__components ) <= pos < len(self.__components )
snake_case : Dict = value
def _SCREAMING_SNAKE_CASE (self : int ) -> float:
'''simple docstring'''
if len(self.__components ) == 0:
raise Exception("Vector is empty" )
snake_case : Union[str, Any] = [c**2 for c in self.__components]
return math.sqrt(sum(snake_case__ ) )
def _SCREAMING_SNAKE_CASE (self : Any , snake_case__ : Vector , snake_case__ : bool = False ) -> float:
'''simple docstring'''
snake_case : Any = self * other
snake_case : List[Any] = self.euclidean_length() * other.euclidean_length()
if deg:
return math.degrees(math.acos(num / den ) )
else:
return math.acos(num / den )
def UpperCamelCase ( __lowerCamelCase : int ):
assert isinstance(__lowerCamelCase , __lowerCamelCase )
return Vector([0] * dimension )
def UpperCamelCase ( __lowerCamelCase : int , __lowerCamelCase : int ):
assert isinstance(__lowerCamelCase , __lowerCamelCase ) and (isinstance(__lowerCamelCase , __lowerCamelCase ))
snake_case : Tuple = [0] * dimension
snake_case : str = 1
return Vector(__lowerCamelCase )
def UpperCamelCase ( __lowerCamelCase : float , __lowerCamelCase : Vector , __lowerCamelCase : Vector ):
assert (
isinstance(__lowerCamelCase , __lowerCamelCase )
and isinstance(__lowerCamelCase , __lowerCamelCase )
and (isinstance(__lowerCamelCase , (int, float) ))
)
return x * scalar + y
def UpperCamelCase ( __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int ):
random.seed(__lowerCamelCase )
snake_case : Any = [random.randint(__lowerCamelCase , __lowerCamelCase ) for _ in range(__lowerCamelCase )]
return Vector(__lowerCamelCase )
class UpperCAmelCase :
def __init__(self : List[str] , snake_case__ : list[list[float]] , snake_case__ : int , snake_case__ : int ) -> None:
'''simple docstring'''
snake_case : Union[str, Any] = matrix
snake_case : Tuple = w
snake_case : Union[str, Any] = h
def __str__(self : Union[str, Any] ) -> str:
'''simple docstring'''
snake_case : Dict = ""
for i in range(self.__height ):
ans += "|"
for j in range(self.__width ):
if j < self.__width - 1:
ans += str(self.__matrix[i][j] ) + ","
else:
ans += str(self.__matrix[i][j] ) + "|\n"
return ans
def __add__(self : Union[str, Any] , snake_case__ : Matrix ) -> Matrix:
'''simple docstring'''
if self.__width == other.width() and self.__height == other.height():
snake_case : List[str] = []
for i in range(self.__height ):
snake_case : List[Any] = [
self.__matrix[i][j] + other.component(snake_case__ , snake_case__ )
for j in range(self.__width )
]
matrix.append(snake_case__ )
return Matrix(snake_case__ , self.__width , self.__height )
else:
raise Exception("matrix must have the same dimension!" )
def __sub__(self : Union[str, Any] , snake_case__ : Matrix ) -> Matrix:
'''simple docstring'''
if self.__width == other.width() and self.__height == other.height():
snake_case : Optional[int] = []
for i in range(self.__height ):
snake_case : List[Any] = [
self.__matrix[i][j] - other.component(snake_case__ , snake_case__ )
for j in range(self.__width )
]
matrix.append(snake_case__ )
return Matrix(snake_case__ , self.__width , self.__height )
else:
raise Exception("matrices must have the same dimension!" )
@overload
def __mul__(self : Dict , snake_case__ : float ) -> Matrix:
'''simple docstring'''
...
@overload
def __mul__(self : Optional[int] , snake_case__ : Vector ) -> Vector:
'''simple docstring'''
...
def __mul__(self : Any , snake_case__ : float | Vector ) -> Vector | Matrix:
'''simple docstring'''
if isinstance(snake_case__ , snake_case__ ): # matrix-vector
if len(snake_case__ ) == self.__width:
snake_case : Dict = zero_vector(self.__height )
for i in range(self.__height ):
snake_case : str = [
self.__matrix[i][j] * other.component(snake_case__ )
for j in range(self.__width )
]
ans.change_component(snake_case__ , sum(snake_case__ ) )
return ans
else:
raise Exception(
"vector must have the same size as the "
"number of columns of the matrix!" )
elif isinstance(snake_case__ , (int, float) ): # matrix-scalar
snake_case : Optional[Any] = [
[self.__matrix[i][j] * other for j in range(self.__width )]
for i in range(self.__height )
]
return Matrix(snake_case__ , self.__width , self.__height )
return None
def _SCREAMING_SNAKE_CASE (self : List[Any] ) -> int:
'''simple docstring'''
return self.__height
def _SCREAMING_SNAKE_CASE (self : int ) -> int:
'''simple docstring'''
return self.__width
def _SCREAMING_SNAKE_CASE (self : Optional[int] , snake_case__ : int , snake_case__ : int ) -> float:
'''simple docstring'''
if 0 <= x < self.__height and 0 <= y < self.__width:
return self.__matrix[x][y]
else:
raise Exception("change_component: indices out of bounds" )
def _SCREAMING_SNAKE_CASE (self : Optional[int] , snake_case__ : int , snake_case__ : int , snake_case__ : float ) -> None:
'''simple docstring'''
if 0 <= x < self.__height and 0 <= y < self.__width:
snake_case : Any = value
else:
raise Exception("change_component: indices out of bounds" )
def _SCREAMING_SNAKE_CASE (self : List[Any] , snake_case__ : int , snake_case__ : int ) -> float:
'''simple docstring'''
if self.__height != self.__width:
raise Exception("Matrix is not square" )
snake_case : Any = self.__matrix[:x] + self.__matrix[x + 1 :]
for i in range(len(snake_case__ ) ):
snake_case : int = minor[i][:y] + minor[i][y + 1 :]
return Matrix(snake_case__ , self.__width - 1 , self.__height - 1 ).determinant()
def _SCREAMING_SNAKE_CASE (self : List[str] , snake_case__ : int , snake_case__ : int ) -> float:
'''simple docstring'''
if self.__height != self.__width:
raise Exception("Matrix is not square" )
if 0 <= x < self.__height and 0 <= y < self.__width:
return (-1) ** (x + y) * self.minor(snake_case__ , snake_case__ )
else:
raise Exception("Indices out of bounds" )
def _SCREAMING_SNAKE_CASE (self : Any ) -> float:
'''simple docstring'''
if self.__height != self.__width:
raise Exception("Matrix is not square" )
if self.__height < 1:
raise Exception("Matrix has no element" )
elif self.__height == 1:
return self.__matrix[0][0]
elif self.__height == 2:
return (
self.__matrix[0][0] * self.__matrix[1][1]
- self.__matrix[0][1] * self.__matrix[1][0]
)
else:
snake_case : List[str] = [
self.__matrix[0][y] * self.cofactor(0 , snake_case__ ) for y in range(self.__width )
]
return sum(snake_case__ )
def UpperCamelCase ( __lowerCamelCase : int ):
snake_case : list[list[float]] = [[0] * n for _ in range(__lowerCamelCase )]
return Matrix(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
def UpperCamelCase ( __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int ):
random.seed(__lowerCamelCase )
snake_case : list[list[float]] = [
[random.randint(__lowerCamelCase , __lowerCamelCase ) for _ in range(__lowerCamelCase )] for _ in range(__lowerCamelCase )
]
return Matrix(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
| 204 |
import secrets
from random import shuffle
from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation
def UpperCamelCase ( __lowerCamelCase : int = 8 ):
snake_case : int = ascii_letters + digits + punctuation
return "".join(secrets.choice(__lowerCamelCase ) for _ in range(__lowerCamelCase ) )
def UpperCamelCase ( __lowerCamelCase : str , __lowerCamelCase : int ):
# Password Generator = full boot with random_number, random_letters, and
# random_character FUNCTIONS
# Put your code here...
i -= len(__lowerCamelCase )
snake_case : Any = i // 3
snake_case : Optional[int] = i % 3
# chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) +
# random_number(digits, i / 3) + random_characters(punctuation, i / 3)
snake_case : Tuple = (
chars_incl
+ random(__lowerCamelCase , quotient + remainder )
+ random(__lowerCamelCase , __lowerCamelCase )
+ random(__lowerCamelCase , __lowerCamelCase )
)
snake_case : Optional[Any] = list(__lowerCamelCase )
shuffle(__lowerCamelCase )
return "".join(__lowerCamelCase )
# random is a generalised function for letters, characters and numbers
def UpperCamelCase ( __lowerCamelCase : str , __lowerCamelCase : int ):
return "".join(secrets.choice(__lowerCamelCase ) for _ in range(__lowerCamelCase ) )
def UpperCamelCase ( __lowerCamelCase : List[str] , __lowerCamelCase : str ):
pass # Put your code here...
def UpperCamelCase ( __lowerCamelCase : Optional[int] , __lowerCamelCase : List[str] ):
pass # Put your code here...
def UpperCamelCase ( __lowerCamelCase : Any , __lowerCamelCase : List[Any] ):
pass # Put your code here...
def UpperCamelCase ( __lowerCamelCase : str , __lowerCamelCase : int = 8 ):
if len(__lowerCamelCase ) < min_length:
# Your Password must be at least 8 characters long
return False
snake_case : Dict = any(char in ascii_uppercase for char in password )
snake_case : Optional[int] = any(char in ascii_lowercase for char in password )
snake_case : str = any(char in digits for char in password )
snake_case : str = any(char in punctuation for char in password )
return upper and lower and num and spec_char
# Passwords should contain UPPERCASE, lowerase
# numbers, and special characters
def UpperCamelCase ( ):
snake_case : int = int(input("Please indicate the max length of your password: " ).strip() )
snake_case : Union[str, Any] = input(
"Please indicate the characters that must be in your password: " ).strip()
print("Password generated:" , password_generator(__lowerCamelCase ) )
print(
"Alternative Password generated:" , alternative_password_generator(__lowerCamelCase , __lowerCamelCase ) , )
print("[If you are thinking of using this passsword, You better save it.]" )
if __name__ == "__main__":
main()
| 204 | 1 |
import json
import sys
import tempfile
import unittest
from pathlib import Path
import transformers
from transformers import (
CONFIG_MAPPING,
FEATURE_EXTRACTOR_MAPPING,
AutoConfig,
AutoFeatureExtractor,
WavaVecaConfig,
WavaVecaFeatureExtractor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir
sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils'))
from test_module.custom_configuration import CustomConfig # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402
_lowerCamelCase : Tuple = get_tests_dir('fixtures')
_lowerCamelCase : Dict = get_tests_dir('fixtures/dummy_feature_extractor_config.json')
_lowerCamelCase : Dict = get_tests_dir('fixtures/dummy-config.json')
class snake_case__ ( unittest.TestCase ):
'''simple docstring'''
def UpperCamelCase ( self : Union[str, Any] ) -> str:
UpperCAmelCase_ = 0
def UpperCamelCase ( self : Union[str, Any] ) -> Tuple:
UpperCAmelCase_ = AutoFeatureExtractor.from_pretrained('''facebook/wav2vec2-base-960h''' )
self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ )
def UpperCamelCase ( self : List[str] ) -> str:
UpperCAmelCase_ = AutoFeatureExtractor.from_pretrained(lowerCAmelCase_ )
self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ )
def UpperCamelCase ( self : List[str] ) -> Tuple:
with tempfile.TemporaryDirectory() as tmpdirname:
UpperCAmelCase_ = WavaVecaConfig()
# remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
UpperCAmelCase_ = AutoFeatureExtractor.from_pretrained(lowerCAmelCase_ ).to_dict()
config_dict.pop('''feature_extractor_type''' )
UpperCAmelCase_ = WavaVecaFeatureExtractor(**lowerCAmelCase_ )
# save in new folder
model_config.save_pretrained(lowerCAmelCase_ )
config.save_pretrained(lowerCAmelCase_ )
UpperCAmelCase_ = AutoFeatureExtractor.from_pretrained(lowerCAmelCase_ )
# make sure private variable is not incorrectly saved
UpperCAmelCase_ = json.loads(config.to_json_string() )
self.assertTrue('''_processor_class''' not in dict_as_saved )
self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ )
def UpperCamelCase ( self : Optional[int] ) -> Any:
UpperCAmelCase_ = AutoFeatureExtractor.from_pretrained(lowerCAmelCase_ )
self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ )
def UpperCamelCase ( self : Dict ) -> List[Any]:
with self.assertRaisesRegex(
lowerCAmelCase_ , '''bert-base is not a local folder and is not a valid model identifier''' ):
UpperCAmelCase_ = AutoFeatureExtractor.from_pretrained('''bert-base''' )
def UpperCamelCase ( self : Tuple ) -> Optional[int]:
with self.assertRaisesRegex(
lowerCAmelCase_ , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ):
UpperCAmelCase_ = AutoFeatureExtractor.from_pretrained(lowerCAmelCase_ , revision='''aaaaaa''' )
def UpperCamelCase ( self : Union[str, Any] ) -> Dict:
with self.assertRaisesRegex(
lowerCAmelCase_ , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ):
UpperCAmelCase_ = AutoFeatureExtractor.from_pretrained('''hf-internal-testing/config-no-model''' )
def UpperCamelCase ( self : Optional[Any] ) -> int:
# If remote code is not set, we will time out when asking whether to load the model.
with self.assertRaises(lowerCAmelCase_ ):
UpperCAmelCase_ = AutoFeatureExtractor.from_pretrained(
'''hf-internal-testing/test_dynamic_feature_extractor''' )
# If remote code is disabled, we can't load this config.
with self.assertRaises(lowerCAmelCase_ ):
UpperCAmelCase_ = AutoFeatureExtractor.from_pretrained(
'''hf-internal-testing/test_dynamic_feature_extractor''' , trust_remote_code=lowerCAmelCase_ )
UpperCAmelCase_ = AutoFeatureExtractor.from_pretrained(
'''hf-internal-testing/test_dynamic_feature_extractor''' , trust_remote_code=lowerCAmelCase_ )
self.assertEqual(feature_extractor.__class__.__name__ , '''NewFeatureExtractor''' )
# Test feature extractor can be reloaded.
with tempfile.TemporaryDirectory() as tmp_dir:
feature_extractor.save_pretrained(lowerCAmelCase_ )
UpperCAmelCase_ = AutoFeatureExtractor.from_pretrained(lowerCAmelCase_ , trust_remote_code=lowerCAmelCase_ )
self.assertEqual(reloaded_feature_extractor.__class__.__name__ , '''NewFeatureExtractor''' )
def UpperCamelCase ( self : Tuple ) -> Optional[Any]:
try:
AutoConfig.register('''custom''' , lowerCAmelCase_ )
AutoFeatureExtractor.register(lowerCAmelCase_ , lowerCAmelCase_ )
# Trying to register something existing in the Transformers library will raise an error
with self.assertRaises(lowerCAmelCase_ ):
AutoFeatureExtractor.register(lowerCAmelCase_ , lowerCAmelCase_ )
# Now that the config is registered, it can be used as any other config with the auto-API
UpperCAmelCase_ = CustomFeatureExtractor.from_pretrained(lowerCAmelCase_ )
with tempfile.TemporaryDirectory() as tmp_dir:
feature_extractor.save_pretrained(lowerCAmelCase_ )
UpperCAmelCase_ = AutoFeatureExtractor.from_pretrained(lowerCAmelCase_ )
self.assertIsInstance(lowerCAmelCase_ , lowerCAmelCase_ )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
def UpperCamelCase ( self : str ) -> Optional[int]:
class snake_case__ ( __snake_case ):
'''simple docstring'''
__A = True
try:
AutoConfig.register('''custom''' , lowerCAmelCase_ )
AutoFeatureExtractor.register(lowerCAmelCase_ , lowerCAmelCase_ )
# If remote code is not set, the default is to use local
UpperCAmelCase_ = AutoFeatureExtractor.from_pretrained(
'''hf-internal-testing/test_dynamic_feature_extractor''' )
self.assertEqual(feature_extractor.__class__.__name__ , '''NewFeatureExtractor''' )
self.assertTrue(feature_extractor.is_local )
# If remote code is disabled, we load the local one.
UpperCAmelCase_ = AutoFeatureExtractor.from_pretrained(
'''hf-internal-testing/test_dynamic_feature_extractor''' , trust_remote_code=lowerCAmelCase_ )
self.assertEqual(feature_extractor.__class__.__name__ , '''NewFeatureExtractor''' )
self.assertTrue(feature_extractor.is_local )
# If remote is enabled, we load from the Hub
UpperCAmelCase_ = AutoFeatureExtractor.from_pretrained(
'''hf-internal-testing/test_dynamic_feature_extractor''' , trust_remote_code=lowerCAmelCase_ )
self.assertEqual(feature_extractor.__class__.__name__ , '''NewFeatureExtractor''' )
self.assertTrue(not hasattr(lowerCAmelCase_ , '''is_local''' ) )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
| 407 |
from math import pow, sqrt
def _lowerCAmelCase ( *__magic_name__ :float ):
UpperCAmelCase_ = len(__magic_name__ ) > 0 and all(value > 0.0 for value in values )
return result
def _lowerCAmelCase ( __magic_name__ :float , __magic_name__ :float ):
return (
round(sqrt(molar_mass_a / molar_mass_a ) , 6 )
if validate(__magic_name__ , __magic_name__ )
else ValueError('''Input Error: Molar mass values must greater than 0.''' )
)
def _lowerCAmelCase ( __magic_name__ :float , __magic_name__ :float , __magic_name__ :float ):
return (
round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 )
if validate(__magic_name__ , __magic_name__ , __magic_name__ )
else ValueError(
'''Input Error: Molar mass and effusion rate values must greater than 0.''' )
)
def _lowerCAmelCase ( __magic_name__ :float , __magic_name__ :float , __magic_name__ :float ):
return (
round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 )
if validate(__magic_name__ , __magic_name__ , __magic_name__ )
else ValueError(
'''Input Error: Molar mass and effusion rate values must greater than 0.''' )
)
def _lowerCAmelCase ( __magic_name__ :float , __magic_name__ :float , __magic_name__ :float ):
return (
round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 )
if validate(__magic_name__ , __magic_name__ , __magic_name__ )
else ValueError(
'''Input Error: Molar mass and effusion rate values must greater than 0.''' )
)
def _lowerCAmelCase ( __magic_name__ :float , __magic_name__ :float , __magic_name__ :float ):
return (
round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 )
if validate(__magic_name__ , __magic_name__ , __magic_name__ )
else ValueError(
'''Input Error: Molar mass and effusion rate values must greater than 0.''' )
)
| 407 | 1 |
from typing import Optional
from urllib.parse import quote
import huggingface_hub as hfh
from packaging import version
def A ( lowercase__ : str , lowercase__ : str , lowercase__ : Optional[str] = None ) -> str:
if version.parse(hfh.__version__ ).release < version.parse("""0.11.0""" ).release:
# old versions of hfh don't url-encode the file path
UpperCamelCase__ :str = quote(lowercase__ )
return hfh.hf_hub_url(lowercase__ , lowercase__ , repo_type="""dataset""" , revision=lowercase__ ) | 45 |
# Note: if you intend to run this script make sure you look under scripts/fsmt/
# to locate the appropriate script to do the work correctly. There is a set of scripts to:
# - download and prepare data and run the conversion script
# - perform eval to get the best hparam into the config
# - generate model_cards - useful if you have multiple models from the same paper
import argparse
import json
import os
import re
from collections import OrderedDict
from os.path import basename, dirname
import fairseq
import torch
from fairseq import hub_utils
from fairseq.data.dictionary import Dictionary
from transformers import FSMTConfig, FSMTForConditionalGeneration
from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES
from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE
from transformers.utils import WEIGHTS_NAME, logging
logging.set_verbosity_warning()
_A = 2
# based on the results of a search on a range of `num_beams`, `length_penalty` and `early_stopping`
# values against wmt19 test data to obtain the best BLEU scores, we will use the following defaults:
#
# * `num_beams`: 5 (higher scores better, but requires more memory/is slower, can be adjusted by users)
# * `early_stopping`: `False` consistently scored better
# * `length_penalty` varied, so will assign the best one depending on the model
_A = {
# fairseq:
"wmt19-ru-en": {"length_penalty": 1.1},
"wmt19-en-ru": {"length_penalty": 1.15},
"wmt19-en-de": {"length_penalty": 1.0},
"wmt19-de-en": {"length_penalty": 1.1},
# allenai:
"wmt16-en-de-dist-12-1": {"length_penalty": 0.6},
"wmt16-en-de-dist-6-1": {"length_penalty": 0.6},
"wmt16-en-de-12-1": {"length_penalty": 0.8},
"wmt19-de-en-6-6-base": {"length_penalty": 0.6},
"wmt19-de-en-6-6-big": {"length_penalty": 0.6},
}
# this remaps the different models to their organization names
_A = {}
for m in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]:
_A = "facebook"
for m in [
"wmt16-en-de-dist-12-1",
"wmt16-en-de-dist-6-1",
"wmt16-en-de-12-1",
"wmt19-de-en-6-6-base",
"wmt19-de-en-6-6-big",
]:
_A = "allenai"
def lowerCamelCase__ ( __lowerCAmelCase : Dict ):
"""simple docstring"""
lowerCAmelCase_ = dict((re.sub(r"@@$" , "" , __lowerCAmelCase ), v) if k.endswith("@@" ) else (re.sub(r"$" , "</w>" , __lowerCAmelCase ), v) for k, v in d.items() )
lowerCAmelCase_ = "<s> <pad> </s> <unk>".split()
# restore the special tokens
for k in keep_keys:
del da[F"""{k}</w>"""]
lowerCAmelCase_ = d[k] # restore
return da
def lowerCamelCase__ ( __lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[Any] ):
"""simple docstring"""
assert os.path.exists(__lowerCAmelCase )
os.makedirs(__lowerCAmelCase , exist_ok=__lowerCAmelCase )
print(F"""Writing results to {pytorch_dump_folder_path}""" )
# handle various types of models
lowerCAmelCase_ = basename(__lowerCAmelCase )
lowerCAmelCase_ = dirname(__lowerCAmelCase )
lowerCAmelCase_ = fairseq.model_parallel.models.transformer.ModelParallelTransformerModel
lowerCAmelCase_ = cls.hub_models()
lowerCAmelCase_ = {"bpe": "fastbpe", "tokenizer": "moses"}
lowerCAmelCase_ = "."
# note: since the model dump is old, fairseq has upgraded its model some
# time later, and it does a whole lot of rewrites and splits on the saved
# weights, therefore we can't use torch.load() directly on the model file.
# see: upgrade_state_dict(state_dict) in fairseq_model.py
print(F"""using checkpoint {checkpoint_file}""" )
lowerCAmelCase_ = hub_utils.from_pretrained(
__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , archive_map=__lowerCAmelCase , **__lowerCAmelCase )
lowerCAmelCase_ = vars(chkpt["args"]["model"] )
lowerCAmelCase_ = args["source_lang"]
lowerCAmelCase_ = args["target_lang"]
lowerCAmelCase_ = dirname(__lowerCAmelCase )
lowerCAmelCase_ = basename(__lowerCAmelCase )
# dicts
lowerCAmelCase_ = os.path.join(__lowerCAmelCase , F"""dict.{src_lang}.txt""" )
lowerCAmelCase_ = os.path.join(__lowerCAmelCase , F"""dict.{tgt_lang}.txt""" )
lowerCAmelCase_ = Dictionary.load(__lowerCAmelCase )
lowerCAmelCase_ = rewrite_dict_keys(src_dict.indices )
lowerCAmelCase_ = len(__lowerCAmelCase )
lowerCAmelCase_ = os.path.join(__lowerCAmelCase , "vocab-src.json" )
print(F"""Generating {src_vocab_file} of {src_vocab_size} of {src_lang} records""" )
with open(__lowerCAmelCase , "w" , encoding="utf-8" ) as f:
f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) )
# detect whether this is a do_lower_case situation, which can be derived by checking whether we
# have at least one uppercase letter in the source vocab
lowerCAmelCase_ = True
for k in src_vocab.keys():
if not k.islower():
lowerCAmelCase_ = False
break
lowerCAmelCase_ = Dictionary.load(__lowerCAmelCase )
lowerCAmelCase_ = rewrite_dict_keys(tgt_dict.indices )
lowerCAmelCase_ = len(__lowerCAmelCase )
lowerCAmelCase_ = os.path.join(__lowerCAmelCase , "vocab-tgt.json" )
print(F"""Generating {tgt_vocab_file} of {tgt_vocab_size} of {tgt_lang} records""" )
with open(__lowerCAmelCase , "w" , encoding="utf-8" ) as f:
f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) )
# merges_file (bpecodes)
lowerCAmelCase_ = os.path.join(__lowerCAmelCase , VOCAB_FILES_NAMES["merges_file"] )
for fn in ["bpecodes", "code"]: # older fairseq called the merges file "code"
lowerCAmelCase_ = os.path.join(__lowerCAmelCase , __lowerCAmelCase )
if os.path.exists(__lowerCAmelCase ):
break
with open(__lowerCAmelCase , encoding="utf-8" ) as fin:
lowerCAmelCase_ = fin.read()
lowerCAmelCase_ = re.sub(r" \d+$" , "" , __lowerCAmelCase , 0 , re.M ) # remove frequency number
print(F"""Generating {merges_file}""" )
with open(__lowerCAmelCase , "w" , encoding="utf-8" ) as fout:
fout.write(__lowerCAmelCase )
# model config
lowerCAmelCase_ = os.path.join(__lowerCAmelCase , "config.json" )
# validate bpe/tokenizer config, as currently it's hardcoded to moses+fastbpe -
# may have to modify the tokenizer if a different type is used by a future model
assert args["bpe"] == "fastbpe", F"""need to extend tokenizer to support bpe={args['bpe']}"""
assert args["tokenizer"] == "moses", F"""need to extend tokenizer to support bpe={args['tokenizer']}"""
lowerCAmelCase_ = {
"architectures": ["FSMTForConditionalGeneration"],
"model_type": "fsmt",
"activation_dropout": args["activation_dropout"],
"activation_function": "relu",
"attention_dropout": args["attention_dropout"],
"d_model": args["decoder_embed_dim"],
"dropout": args["dropout"],
"init_std": 0.02,
"max_position_embeddings": args["max_source_positions"],
"num_hidden_layers": args["encoder_layers"],
"src_vocab_size": src_vocab_size,
"tgt_vocab_size": tgt_vocab_size,
"langs": [src_lang, tgt_lang],
"encoder_attention_heads": args["encoder_attention_heads"],
"encoder_ffn_dim": args["encoder_ffn_embed_dim"],
"encoder_layerdrop": args["encoder_layerdrop"],
"encoder_layers": args["encoder_layers"],
"decoder_attention_heads": args["decoder_attention_heads"],
"decoder_ffn_dim": args["decoder_ffn_embed_dim"],
"decoder_layerdrop": args["decoder_layerdrop"],
"decoder_layers": args["decoder_layers"],
"bos_token_id": 0,
"pad_token_id": 1,
"eos_token_id": 2,
"is_encoder_decoder": True,
"scale_embedding": not args["no_scale_embedding"],
"tie_word_embeddings": args["share_all_embeddings"],
}
# good hparam defaults to start with
lowerCAmelCase_ = 5
lowerCAmelCase_ = False
if model_dir in best_score_hparams and "length_penalty" in best_score_hparams[model_dir]:
lowerCAmelCase_ = best_score_hparams[model_dir]["length_penalty"]
else:
lowerCAmelCase_ = 1.0
print(F"""Generating {fsmt_model_config_file}""" )
with open(__lowerCAmelCase , "w" , encoding="utf-8" ) as f:
f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) )
# tokenizer config
lowerCAmelCase_ = os.path.join(__lowerCAmelCase , __lowerCAmelCase )
lowerCAmelCase_ = {
"langs": [src_lang, tgt_lang],
"model_max_length": 1024,
"do_lower_case": do_lower_case,
}
print(F"""Generating {fsmt_tokenizer_config_file}""" )
with open(__lowerCAmelCase , "w" , encoding="utf-8" ) as f:
f.write(json.dumps(__lowerCAmelCase , ensure_ascii=__lowerCAmelCase , indent=__lowerCAmelCase ) )
# model
lowerCAmelCase_ = chkpt["models"][0]
lowerCAmelCase_ = model.state_dict()
# rename keys to start with 'model.'
lowerCAmelCase_ = OrderedDict(("model." + k, v) for k, v in model_state_dict.items() )
# remove unneeded keys
lowerCAmelCase_ = [
"model.model",
"model.encoder.version",
"model.decoder.version",
"model.encoder_embed_tokens.weight",
"model.decoder_embed_tokens.weight",
"model.encoder.embed_positions._float_tensor",
"model.decoder.embed_positions._float_tensor",
]
for k in ignore_keys:
model_state_dict.pop(__lowerCAmelCase , __lowerCAmelCase )
lowerCAmelCase_ = FSMTConfig.from_pretrained(__lowerCAmelCase )
lowerCAmelCase_ = FSMTForConditionalGeneration(__lowerCAmelCase )
# check that it loads ok
model_new.load_state_dict(__lowerCAmelCase , strict=__lowerCAmelCase )
# save
lowerCAmelCase_ = os.path.join(__lowerCAmelCase , __lowerCAmelCase )
print(F"""Generating {pytorch_weights_dump_path}""" )
torch.save(__lowerCAmelCase , __lowerCAmelCase )
print("Conversion is done!" )
print("\nLast step is to upload the files to s3" )
print(F"""cd {data_root}""" )
print(F"""transformers-cli upload {model_dir}""" )
if __name__ == "__main__":
_A = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--fsmt_checkpoint_path",
default=None,
type=str,
required=True,
help=(
"Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,"
" bpecodes, etc."
),
)
parser.add_argument(
"--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
)
_A = parser.parse_args()
convert_fsmt_checkpoint_to_pytorch(args.fsmt_checkpoint_path, args.pytorch_dump_folder_path)
| 290 | 0 |
'''simple docstring'''
import argparse
import math
import os
from copy import deepcopy
import torch
from audio_diffusion.models import DiffusionAttnUnetaD
from diffusion import sampling
from torch import nn
from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel
UpperCamelCase_ = {
'''gwf-440k''': {
'''url''': '''https://model-server.zqevans2.workers.dev/gwf-440k.ckpt''',
'''sample_rate''': 48000,
'''sample_size''': 65536,
},
'''jmann-small-190k''': {
'''url''': '''https://model-server.zqevans2.workers.dev/jmann-small-190k.ckpt''',
'''sample_rate''': 48000,
'''sample_size''': 65536,
},
'''jmann-large-580k''': {
'''url''': '''https://model-server.zqevans2.workers.dev/jmann-large-580k.ckpt''',
'''sample_rate''': 48000,
'''sample_size''': 131072,
},
'''maestro-uncond-150k''': {
'''url''': '''https://model-server.zqevans2.workers.dev/maestro-uncond-150k.ckpt''',
'''sample_rate''': 16000,
'''sample_size''': 65536,
},
'''unlocked-uncond-250k''': {
'''url''': '''https://model-server.zqevans2.workers.dev/unlocked-uncond-250k.ckpt''',
'''sample_rate''': 16000,
'''sample_size''': 65536,
},
'''honk-140k''': {
'''url''': '''https://model-server.zqevans2.workers.dev/honk-140k.ckpt''',
'''sample_rate''': 16000,
'''sample_size''': 65536,
},
}
def _lowerCAmelCase ( __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] ) -> List[Any]:
return torch.atana(__magic_name__ , __magic_name__ ) / math.pi * 2
def _lowerCAmelCase ( __magic_name__ : List[str] ) -> Any:
lowercase : Tuple =torch.sin(t * math.pi / 2 ) ** 2
lowercase : str =(1 - sigma**2) ** 0.5
return alpha_sigma_to_t(__magic_name__ , __magic_name__ )
class __SCREAMING_SNAKE_CASE ( UpperCamelCase__ ):
pass
class __SCREAMING_SNAKE_CASE ( nn.Module ):
def __init__( self : List[Any] , UpperCAmelCase__ : Any ):
'''simple docstring'''
super().__init__()
lowercase : str =DiffusionAttnUnetaD(UpperCAmelCase__ , n_attn_layers=4 )
lowercase : int =deepcopy(self.diffusion )
lowercase : List[Any] =torch.quasirandom.SobolEngine(1 , scramble=UpperCAmelCase__ )
def _lowerCAmelCase ( __magic_name__ : Any ) -> Optional[int]:
lowercase : int =MODELS_MAP[model_name]['''url''']
os.system(f'''wget {url} ./''' )
return f'''./{model_name}.ckpt'''
UpperCamelCase_ = {
'''1''': '''resnets.0''',
'''2''': '''attentions.0''',
'''3''': '''resnets.1''',
'''4''': '''attentions.1''',
'''5''': '''resnets.2''',
'''6''': '''attentions.2''',
}
UpperCamelCase_ = {
'''8''': '''resnets.0''',
'''9''': '''attentions.0''',
'''10''': '''resnets.1''',
'''11''': '''attentions.1''',
'''12''': '''resnets.2''',
'''13''': '''attentions.2''',
}
UpperCamelCase_ = {
'''1''': '''resnets.0''',
'''2''': '''attentions.0''',
'''3''': '''resnets.1''',
'''4''': '''attentions.1''',
'''5''': '''resnets.2''',
'''6''': '''attentions.2''',
'''8''': '''resnets.3''',
'''9''': '''attentions.3''',
'''10''': '''resnets.4''',
'''11''': '''attentions.4''',
'''12''': '''resnets.5''',
'''13''': '''attentions.5''',
}
UpperCamelCase_ = {
'''0''': '''resnets.0''',
'''1''': '''resnets.1''',
'''2''': '''resnets.2''',
'''4''': '''resnets.0''',
'''5''': '''resnets.1''',
'''6''': '''resnets.2''',
}
UpperCamelCase_ = {
'''skip''': '''conv_skip''',
'''main.0''': '''conv_1''',
'''main.1''': '''group_norm_1''',
'''main.3''': '''conv_2''',
'''main.4''': '''group_norm_2''',
}
UpperCamelCase_ = {
'''norm''': '''group_norm''',
'''qkv_proj''': ['''query''', '''key''', '''value'''],
'''out_proj''': ['''proj_attn'''],
}
def _lowerCAmelCase ( __magic_name__ : Optional[Any] ) -> Tuple:
if name.startswith('''skip''' ):
return name.replace('''skip''' , RES_CONV_MAP['''skip'''] )
# name has to be of format main.{digit}
if not name.startswith('''main.''' ):
raise ValueError(f'''ResConvBlock error with {name}''' )
return name.replace(name[:6] , RES_CONV_MAP[name[:6]] )
def _lowerCAmelCase ( __magic_name__ : str ) -> Optional[Any]:
for key, value in ATTN_MAP.items():
if name.startswith(__magic_name__ ) and not isinstance(__magic_name__ , __magic_name__ ):
return name.replace(__magic_name__ , __magic_name__ )
elif name.startswith(__magic_name__ ):
return [name.replace(__magic_name__ , __magic_name__ ) for v in value]
raise ValueError(f'''Attn error with {name}''' )
def _lowerCAmelCase ( __magic_name__ : List[Any] , __magic_name__ : Optional[int]=13 ) -> Optional[int]:
lowercase : List[Any] =input_string
if string.split('''.''' )[0] == "timestep_embed":
return string.replace('''timestep_embed''' , '''time_proj''' )
lowercase : int =0
if string.startswith('''net.3.''' ):
depth += 1
lowercase : Tuple =string[6:]
elif string.startswith('''net.''' ):
lowercase : Dict =string[4:]
while string.startswith('''main.7.''' ):
depth += 1
lowercase : Optional[Any] =string[7:]
if string.startswith('''main.''' ):
lowercase : Dict =string[5:]
# mid block
if string[:2].isdigit():
lowercase : Optional[int] =string[:2]
lowercase : Optional[int] =string[2:]
else:
lowercase : str =string[0]
lowercase : str =string[1:]
if depth == max_depth:
lowercase : Optional[int] =MID_NUM_TO_LAYER[layer_num]
lowercase : Optional[int] ='''mid_block'''
elif depth > 0 and int(__magic_name__ ) < 7:
lowercase : str =DOWN_NUM_TO_LAYER[layer_num]
lowercase : List[str] =f'''down_blocks.{depth}'''
elif depth > 0 and int(__magic_name__ ) > 7:
lowercase : List[Any] =UP_NUM_TO_LAYER[layer_num]
lowercase : Dict =f'''up_blocks.{max_depth - depth - 1}'''
elif depth == 0:
lowercase : Tuple =DEPTH_0_TO_LAYER[layer_num]
lowercase : List[str] =f'''up_blocks.{max_depth - 1}''' if int(__magic_name__ ) > 3 else '''down_blocks.0'''
if not string_left.startswith('''.''' ):
raise ValueError(f'''Naming error with {input_string} and string_left: {string_left}.''' )
lowercase : Tuple =string_left[1:]
if "resnets" in new_layer:
lowercase : List[str] =convert_resconv_naming(__magic_name__ )
elif "attentions" in new_layer:
lowercase : Union[str, Any] =convert_attn_naming(__magic_name__ )
lowercase : Optional[int] =new_string_left
if not isinstance(__magic_name__ , __magic_name__ ):
lowercase : Optional[Any] =prefix + '''.''' + new_layer + '''.''' + string_left
else:
lowercase : Union[str, Any] =[prefix + '''.''' + new_layer + '''.''' + s for s in string_left]
return new_string
def _lowerCAmelCase ( __magic_name__ : List[Any] ) -> Optional[Any]:
lowercase : Optional[Any] ={}
for k, v in state_dict.items():
if k.endswith('''kernel''' ):
# up- and downsample layers, don't have trainable weights
continue
lowercase : Dict =rename(__magic_name__ )
# check if we need to transform from Conv => Linear for attention
if isinstance(__magic_name__ , __magic_name__ ):
lowercase : int =transform_conv_attns(__magic_name__ , __magic_name__ , __magic_name__ )
else:
lowercase : Optional[Any] =v
return new_state_dict
def _lowerCAmelCase ( __magic_name__ : Dict , __magic_name__ : int , __magic_name__ : int ) -> List[Any]:
if len(__magic_name__ ) == 1:
if len(v.shape ) == 3:
# weight
lowercase : List[Any] =v[:, :, 0]
else:
# bias
lowercase : Optional[Any] =v
else:
# qkv matrices
lowercase : Dict =v.shape[0]
lowercase : str =trippled_shape // 3
for i in range(3 ):
if len(v.shape ) == 3:
lowercase : List[str] =v[i * single_shape : (i + 1) * single_shape, :, 0]
else:
lowercase : Optional[int] =v[i * single_shape : (i + 1) * single_shape]
return new_state_dict
def _lowerCAmelCase ( __magic_name__ : Dict ) -> str:
lowercase : List[str] =torch.device('''cuda''' if torch.cuda.is_available() else '''cpu''' )
lowercase : str =args.model_path.split('''/''' )[-1].split('''.''' )[0]
if not os.path.isfile(args.model_path ):
assert (
model_name == args.model_path
), f'''Make sure to provide one of the official model names {MODELS_MAP.keys()}'''
lowercase : int =download(__magic_name__ )
lowercase : Optional[Any] =MODELS_MAP[model_name]['''sample_rate''']
lowercase : List[Any] =MODELS_MAP[model_name]['''sample_size''']
lowercase : Union[str, Any] =Object()
lowercase : Tuple =sample_size
lowercase : Tuple =sample_rate
lowercase : Optional[int] =0
lowercase : List[Any] =UNetaDModel(sample_size=__magic_name__ , sample_rate=__magic_name__ )
lowercase : Optional[Any] =diffusers_model.state_dict()
lowercase : Tuple =DiffusionUncond(__magic_name__ )
orig_model.load_state_dict(torch.load(args.model_path , map_location=__magic_name__ )['''state_dict'''] )
lowercase : Tuple =orig_model.diffusion_ema.eval()
lowercase : str =orig_model.state_dict()
lowercase : str =rename_orig_weights(__magic_name__ )
lowercase : Dict =set(renamed_state_dict.keys() ) - set(diffusers_state_dict.keys() )
lowercase : Optional[Any] =set(diffusers_state_dict.keys() ) - set(renamed_state_dict.keys() )
assert len(__magic_name__ ) == 0, f'''Problem with {renamed_minus_diffusers}'''
assert all(k.endswith('''kernel''' ) for k in list(__magic_name__ ) ), f'''Problem with {diffusers_minus_renamed}'''
for key, value in renamed_state_dict.items():
assert (
diffusers_state_dict[key].squeeze().shape == value.squeeze().shape
), f'''Shape for {key} doesn\'t match. Diffusers: {diffusers_state_dict[key].shape} vs. {value.shape}'''
if key == "time_proj.weight":
lowercase : Any =value.squeeze()
lowercase : Dict =value
diffusers_model.load_state_dict(__magic_name__ )
lowercase : Any =100
lowercase : Optional[Any] =33
lowercase : List[str] =IPNDMScheduler(num_train_timesteps=__magic_name__ )
lowercase : Tuple =torch.manual_seed(__magic_name__ )
lowercase : Tuple =torch.randn([1, 2, config.sample_size] , generator=__magic_name__ ).to(__magic_name__ )
lowercase : Union[str, Any] =torch.linspace(1 , 0 , steps + 1 , device=__magic_name__ )[:-1]
lowercase : int =get_crash_schedule(__magic_name__ )
lowercase : Any =DanceDiffusionPipeline(unet=__magic_name__ , scheduler=__magic_name__ )
lowercase : Optional[int] =torch.manual_seed(33 )
lowercase : int =pipe(num_inference_steps=__magic_name__ , generator=__magic_name__ ).audios
lowercase : int =sampling.iplms_sample(__magic_name__ , __magic_name__ , __magic_name__ , {} )
lowercase : str =generated.clamp(-1 , 1 )
lowercase : List[str] =(generated - audio).abs().sum()
lowercase : Optional[Any] =(generated - audio).abs().max()
if args.save:
pipe.save_pretrained(args.checkpoint_path )
print('''Diff sum''' , __magic_name__ )
print('''Diff max''' , __magic_name__ )
assert diff_max < 1E-3, f'''Diff max: {diff_max} is too much :-/'''
print(f'''Conversion for {model_name} successful!''' )
if __name__ == "__main__":
UpperCamelCase_ = argparse.ArgumentParser()
parser.add_argument("""--model_path""", default=None, type=str, required=True, help="""Path to the model to convert.""")
parser.add_argument(
"""--save""", default=True, type=bool, required=False, help="""Whether to save the converted model or not."""
)
parser.add_argument("""--checkpoint_path""", default=None, type=str, required=True, help="""Path to the output model.""")
UpperCamelCase_ = parser.parse_args()
main(args)
| 717 |
'''simple docstring'''
import copy
from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto.configuration_auto import AutoConfig
if TYPE_CHECKING:
from ... import PreTrainedTokenizerBase, TensorType
UpperCamelCase_ = logging.get_logger(__name__)
class __SCREAMING_SNAKE_CASE ( lowercase__ ):
lowerCamelCase_ = 'vision-encoder-decoder'
lowerCamelCase_ = True
def __init__( self : Optional[int] , **UpperCAmelCase__ : Tuple ):
'''simple docstring'''
super().__init__(**UpperCAmelCase__ )
if "encoder" not in kwargs or "decoder" not in kwargs:
raise ValueError(
F'''A configuraton of type {self.model_type} cannot be instantiated because '''
F'''not both `encoder` and `decoder` sub-configurations are passed, but only {kwargs}''' )
lowercase : Optional[Any] =kwargs.pop('''encoder''' )
lowercase : List[Any] =encoder_config.pop('''model_type''' )
lowercase : List[str] =kwargs.pop('''decoder''' )
lowercase : Dict =decoder_config.pop('''model_type''' )
lowercase : Union[str, Any] =AutoConfig.for_model(UpperCAmelCase__ , **UpperCAmelCase__ )
lowercase : List[str] =AutoConfig.for_model(UpperCAmelCase__ , **UpperCAmelCase__ )
lowercase : str =True
@classmethod
def lowerCamelCase_ ( cls : List[str] , UpperCAmelCase__ : PretrainedConfig , UpperCAmelCase__ : PretrainedConfig , **UpperCAmelCase__ : Optional[int] ):
'''simple docstring'''
logger.info('''Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config''' )
lowercase : int =True
lowercase : Optional[Any] =True
return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **UpperCAmelCase__ )
def lowerCamelCase_ ( self : Union[str, Any] ):
'''simple docstring'''
lowercase : int =copy.deepcopy(self.__dict__ )
lowercase : Union[str, Any] =self.encoder.to_dict()
lowercase : Union[str, Any] =self.decoder.to_dict()
lowercase : int =self.__class__.model_type
return output
class __SCREAMING_SNAKE_CASE ( lowercase__ ):
lowerCamelCase_ = version.parse('1.11' )
@property
def lowerCamelCase_ ( self : Dict ):
'''simple docstring'''
return OrderedDict(
[
('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
] )
@property
def lowerCamelCase_ ( self : str ):
'''simple docstring'''
return 1E-4
@property
def lowerCamelCase_ ( self : List[str] ):
'''simple docstring'''
return OrderedDict({'''last_hidden_state''': {0: '''batch''', 1: '''encoder_sequence'''}} )
class __SCREAMING_SNAKE_CASE ( lowercase__ ):
@property
def lowerCamelCase_ ( self : int ):
'''simple docstring'''
lowercase : List[str] =OrderedDict()
lowercase : Tuple ={0: '''batch''', 1: '''past_decoder_sequence + sequence'''}
lowercase : Optional[int] ={0: '''batch''', 1: '''past_decoder_sequence + sequence'''}
lowercase : int ={0: '''batch''', 1: '''encoder_sequence'''}
return common_inputs
def lowerCamelCase_ ( self : Optional[int] , UpperCAmelCase__ : "PreTrainedTokenizerBase" , UpperCAmelCase__ : int = -1 , UpperCAmelCase__ : int = -1 , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Optional["TensorType"] = None , ):
'''simple docstring'''
import torch
lowercase : Optional[Any] =OrderedDict()
lowercase : List[Any] =super().generate_dummy_inputs(
UpperCAmelCase__ , batch_size=UpperCAmelCase__ , seq_length=UpperCAmelCase__ , is_pair=UpperCAmelCase__ , framework=UpperCAmelCase__ )
lowercase , lowercase : Optional[int] =dummy_input['''input_ids'''].shape
lowercase : Union[str, Any] =(batch, encoder_sequence, self._config.encoder_hidden_size)
lowercase : List[str] =dummy_input.pop('''input_ids''' )
lowercase : Tuple =dummy_input.pop('''attention_mask''' )
lowercase : Union[str, Any] =torch.zeros(UpperCAmelCase__ )
return common_inputs
class __SCREAMING_SNAKE_CASE ( lowercase__ ):
@property
def lowerCamelCase_ ( self : int ):
'''simple docstring'''
pass
def lowerCamelCase_ ( self : List[Any] , UpperCAmelCase__ : PretrainedConfig ):
'''simple docstring'''
return VisionEncoderDecoderEncoderOnnxConfig(UpperCAmelCase__ )
def lowerCamelCase_ ( self : Optional[int] , UpperCAmelCase__ : PretrainedConfig , UpperCAmelCase__ : PretrainedConfig , UpperCAmelCase__ : str = "default" ):
'''simple docstring'''
lowercase : List[Any] =encoder_config.hidden_size
return VisionEncoderDecoderDecoderOnnxConfig(UpperCAmelCase__ , UpperCAmelCase__ )
| 88 | 0 |
"""simple docstring"""
# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING, Dict, Optional
import numpy as np
import pyarrow as pa
from .. import config
from ..utils.logging import get_logger
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter
if TYPE_CHECKING:
import jax
import jaxlib
a : List[str] = get_logger()
a : Any = None
class a_ ( TensorFormatter[Mapping, 'jax.Array', Mapping] ):
def __init__( self : Tuple , __UpperCamelCase : str=None , __UpperCamelCase : Dict=None , **__UpperCamelCase : Optional[Any] ) ->List[str]:
'''simple docstring'''
super().__init__(features=__lowerCAmelCase )
import jax
from jaxlib.xla_client import Device
if isinstance(__lowerCAmelCase , __lowerCAmelCase ):
raise ValueError(
f"""Expected {device} to be a `str` not {type(__lowerCAmelCase )}, as `jaxlib.xla_extension.Device` """
"""is not serializable neither with `pickle` nor with `dill`. Instead you can surround """
"""the device with `str()` to get its string identifier that will be internally mapped """
"""to the actual `jaxlib.xla_extension.Device`.""" )
_UpperCAmelCase = device if isinstance(__lowerCAmelCase , __lowerCAmelCase ) else str(jax.devices()[0] )
# using global variable since `jaxlib.xla_extension.Device` is not serializable neither
# with `pickle` nor with `dill`, so we need to use a global variable instead
global DEVICE_MAPPING
if DEVICE_MAPPING is None:
_UpperCAmelCase = self._map_devices_to_str()
if self.device not in list(DEVICE_MAPPING.keys() ):
logger.warning(
f"""Device with string identifier {self.device} not listed among the available """
f"""devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default """
f"""device: {str(jax.devices()[0] )}.""" )
_UpperCAmelCase = str(jax.devices()[0] )
_UpperCAmelCase = jnp_array_kwargs
@staticmethod
def _snake_case ( ) ->Tuple:
'''simple docstring'''
import jax
return {str(__lowerCAmelCase ): device for device in jax.devices()}
def _snake_case ( self : Union[str, Any] , __UpperCamelCase : List[Any] ) ->Tuple:
'''simple docstring'''
import jax
import jax.numpy as jnp
if isinstance(__lowerCAmelCase , __lowerCAmelCase ) and column:
if all(
isinstance(__lowerCAmelCase , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ):
return jnp.stack(__lowerCAmelCase , axis=0 )
return column
def _snake_case ( self : str , __UpperCamelCase : Union[str, Any] ) ->str:
'''simple docstring'''
import jax
import jax.numpy as jnp
if isinstance(__lowerCAmelCase , (str, bytes, type(__lowerCAmelCase )) ):
return value
elif isinstance(__lowerCAmelCase , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ):
return value.tolist()
_UpperCAmelCase = {}
if isinstance(__lowerCAmelCase , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ):
# the default int precision depends on the jax config
# see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
if jax.config.jax_enable_xaa:
_UpperCAmelCase = {"""dtype""": jnp.intaa}
else:
_UpperCAmelCase = {"""dtype""": jnp.intaa}
elif isinstance(__lowerCAmelCase , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ):
_UpperCAmelCase = {"""dtype""": jnp.floataa}
elif config.PIL_AVAILABLE and "PIL" in sys.modules:
import PIL.Image
if isinstance(__lowerCAmelCase , PIL.Image.Image ):
_UpperCAmelCase = np.asarray(__lowerCAmelCase )
# using global variable since `jaxlib.xla_extension.Device` is not serializable neither
# with `pickle` nor with `dill`, so we need to use a global variable instead
global DEVICE_MAPPING
if DEVICE_MAPPING is None:
_UpperCAmelCase = self._map_devices_to_str()
with jax.default_device(DEVICE_MAPPING[self.device] ):
# calling jnp.array on a np.ndarray does copy the data
# see https://github.com/google/jax/issues/4486
return jnp.array(__lowerCAmelCase , **{**default_dtype, **self.jnp_array_kwargs} )
def _snake_case ( self : Union[str, Any] , __UpperCamelCase : List[str] ) ->Union[str, Any]:
'''simple docstring'''
import jax
# support for torch, tf, jax etc.
if config.TORCH_AVAILABLE and "torch" in sys.modules:
import torch
if isinstance(__lowerCAmelCase , torch.Tensor ):
return self._tensorize(data_struct.detach().cpu().numpy()[()] )
if hasattr(__lowerCAmelCase , """__array__""" ) and not isinstance(__lowerCAmelCase , jax.Array ):
_UpperCAmelCase = data_struct.__array__()
# support for nested types like struct of list of struct
if isinstance(__lowerCAmelCase , np.ndarray ):
if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects
return self._consolidate([self.recursive_tensorize(__lowerCAmelCase ) for substruct in data_struct] )
elif isinstance(__lowerCAmelCase , (list, tuple) ):
return self._consolidate([self.recursive_tensorize(__lowerCAmelCase ) for substruct in data_struct] )
return self._tensorize(__lowerCAmelCase )
def _snake_case ( self : List[Any] , __UpperCamelCase : int ) ->int:
'''simple docstring'''
return map_nested(self._recursive_tensorize , __lowerCAmelCase , map_list=__lowerCAmelCase )
def _snake_case ( self : List[str] , __UpperCamelCase : Optional[int] ) ->str:
'''simple docstring'''
_UpperCAmelCase = self.numpy_arrow_extractor().extract_row(__lowerCAmelCase )
_UpperCAmelCase = self.python_features_decoder.decode_row(__lowerCAmelCase )
return self.recursive_tensorize(__lowerCAmelCase )
def _snake_case ( self : List[str] , __UpperCamelCase : List[str] ) ->Any:
'''simple docstring'''
_UpperCAmelCase = self.numpy_arrow_extractor().extract_column(__lowerCAmelCase )
_UpperCAmelCase = self.python_features_decoder.decode_column(__lowerCAmelCase , pa_table.column_names[0] )
_UpperCAmelCase = self.recursive_tensorize(__lowerCAmelCase )
_UpperCAmelCase = self._consolidate(__lowerCAmelCase )
return column
def _snake_case ( self : Dict , __UpperCamelCase : int ) ->Optional[Any]:
'''simple docstring'''
_UpperCAmelCase = self.numpy_arrow_extractor().extract_batch(__lowerCAmelCase )
_UpperCAmelCase = self.python_features_decoder.decode_batch(__lowerCAmelCase )
_UpperCAmelCase = self.recursive_tensorize(__lowerCAmelCase )
for column_name in batch:
_UpperCAmelCase = self._consolidate(batch[column_name] )
return batch | 555 |
import collections.abc
from typing import Optional, Tuple, Union
import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithNoAttention, 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_poolformer import PoolFormerConfig
_a = logging.get_logger(__name__)
# General docstring
_a = "PoolFormerConfig"
# Base docstring
_a = "sail/poolformer_s12"
_a = [1, 512, 7, 7]
# Image classification docstring
_a = "sail/poolformer_s12"
_a = "tabby, tabby cat"
_a = [
"sail/poolformer_s12",
# See all PoolFormer models at https://huggingface.co/models?filter=poolformer
]
def lowerCAmelCase__(__snake_case ,__snake_case = 0.0 ,__snake_case = False ) -> Tuple:
'''simple docstring'''
if drop_prob == 0.0 or not training:
return input
lowerCamelCase__ = 1 - drop_prob
lowerCamelCase__ = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
lowerCamelCase__ = keep_prob + torch.rand(__snake_case ,dtype=input.dtype ,device=input.device )
random_tensor.floor_() # binarize
lowerCamelCase__ = input.div(__snake_case ) * random_tensor
return output
class __A ( nn.Module ):
'''simple docstring'''
def __init__( self , __lowerCAmelCase = None ):
'''simple docstring'''
super().__init__()
lowerCamelCase__ = drop_prob
def __lowerCamelCase ( self , __lowerCAmelCase ):
'''simple docstring'''
return drop_path(__lowerCAmelCase , self.drop_prob , self.training )
def __lowerCamelCase ( self ):
'''simple docstring'''
return "p={}".format(self.drop_prob )
class __A ( nn.Module ):
'''simple docstring'''
def __init__( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=None ):
'''simple docstring'''
super().__init__()
lowerCamelCase__ = patch_size if isinstance(__lowerCAmelCase , collections.abc.Iterable ) else (patch_size, patch_size)
lowerCamelCase__ = stride if isinstance(__lowerCAmelCase , collections.abc.Iterable ) else (stride, stride)
lowerCamelCase__ = padding if isinstance(__lowerCAmelCase , collections.abc.Iterable ) else (padding, padding)
lowerCamelCase__ = nn.Convad(__lowerCAmelCase , __lowerCAmelCase , kernel_size=__lowerCAmelCase , stride=__lowerCAmelCase , padding=__lowerCAmelCase )
lowerCamelCase__ = norm_layer(__lowerCAmelCase ) if norm_layer else nn.Identity()
def __lowerCamelCase ( self , __lowerCAmelCase ):
'''simple docstring'''
lowerCamelCase__ = self.projection(__lowerCAmelCase )
lowerCamelCase__ = self.norm(__lowerCAmelCase )
return embeddings
class __A ( nn.GroupNorm ):
'''simple docstring'''
def __init__( self , __lowerCAmelCase , **__lowerCAmelCase ):
'''simple docstring'''
super().__init__(1 , __lowerCAmelCase , **__lowerCAmelCase )
class __A ( nn.Module ):
'''simple docstring'''
def __init__( self , __lowerCAmelCase ):
'''simple docstring'''
super().__init__()
lowerCamelCase__ = nn.AvgPoolad(__lowerCAmelCase , stride=1 , padding=pool_size // 2 , count_include_pad=__lowerCAmelCase )
def __lowerCamelCase ( self , __lowerCAmelCase ):
'''simple docstring'''
return self.pool(__lowerCAmelCase ) - hidden_states
class __A ( nn.Module ):
'''simple docstring'''
def __init__( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ):
'''simple docstring'''
super().__init__()
lowerCamelCase__ = nn.Convad(__lowerCAmelCase , __lowerCAmelCase , 1 )
lowerCamelCase__ = nn.Convad(__lowerCAmelCase , __lowerCAmelCase , 1 )
lowerCamelCase__ = PoolFormerDropPath(__lowerCAmelCase )
if isinstance(config.hidden_act , __lowerCAmelCase ):
lowerCamelCase__ = ACTaFN[config.hidden_act]
else:
lowerCamelCase__ = config.hidden_act
def __lowerCamelCase ( self , __lowerCAmelCase ):
'''simple docstring'''
lowerCamelCase__ = self.conva(__lowerCAmelCase )
lowerCamelCase__ = self.act_fn(__lowerCAmelCase )
lowerCamelCase__ = self.drop(__lowerCAmelCase )
lowerCamelCase__ = self.conva(__lowerCAmelCase )
lowerCamelCase__ = self.drop(__lowerCAmelCase )
return hidden_states
class __A ( nn.Module ):
'''simple docstring'''
def __init__( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ):
'''simple docstring'''
super().__init__()
lowerCamelCase__ = PoolFormerPooling(__lowerCAmelCase )
lowerCamelCase__ = PoolFormerOutput(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
lowerCamelCase__ = PoolFormerGroupNorm(__lowerCAmelCase )
lowerCamelCase__ = PoolFormerGroupNorm(__lowerCAmelCase )
# Useful for training neural nets
lowerCamelCase__ = PoolFormerDropPath(__lowerCAmelCase ) if drop_path > 0.0 else nn.Identity()
lowerCamelCase__ = config.use_layer_scale
if config.use_layer_scale:
lowerCamelCase__ = nn.Parameter(
config.layer_scale_init_value * torch.ones((__lowerCAmelCase) ) , requires_grad=__lowerCAmelCase )
lowerCamelCase__ = nn.Parameter(
config.layer_scale_init_value * torch.ones((__lowerCAmelCase) ) , requires_grad=__lowerCAmelCase )
def __lowerCamelCase ( self , __lowerCAmelCase ):
'''simple docstring'''
if self.use_layer_scale:
lowerCamelCase__ = self.pooling(self.before_norm(__lowerCAmelCase ) )
lowerCamelCase__ = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output
# First residual connection
lowerCamelCase__ = hidden_states + self.drop_path(__lowerCAmelCase )
lowerCamelCase__ = ()
lowerCamelCase__ = self.output(self.after_norm(__lowerCAmelCase ) )
lowerCamelCase__ = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output
# Second residual connection
lowerCamelCase__ = hidden_states + self.drop_path(__lowerCAmelCase )
lowerCamelCase__ = (output,) + outputs
return outputs
else:
lowerCamelCase__ = self.drop_path(self.pooling(self.before_norm(__lowerCAmelCase ) ) )
# First residual connection
lowerCamelCase__ = pooling_output + hidden_states
lowerCamelCase__ = ()
# Second residual connection inside the PoolFormerOutput block
lowerCamelCase__ = self.drop_path(self.output(self.after_norm(__lowerCAmelCase ) ) )
lowerCamelCase__ = hidden_states + layer_output
lowerCamelCase__ = (output,) + outputs
return outputs
class __A ( nn.Module ):
'''simple docstring'''
def __init__( self , __lowerCAmelCase ):
'''simple docstring'''
super().__init__()
lowerCamelCase__ = config
# stochastic depth decay rule
lowerCamelCase__ = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )]
# patch embeddings
lowerCamelCase__ = []
for i in range(config.num_encoder_blocks ):
embeddings.append(
PoolFormerEmbeddings(
patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) )
lowerCamelCase__ = nn.ModuleList(__lowerCAmelCase )
# Transformer blocks
lowerCamelCase__ = []
lowerCamelCase__ = 0
for i in range(config.num_encoder_blocks ):
# each block consists of layers
lowerCamelCase__ = []
if i != 0:
cur += config.depths[i - 1]
for j in range(config.depths[i] ):
layers.append(
PoolFormerLayer(
__lowerCAmelCase , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) )
blocks.append(nn.ModuleList(__lowerCAmelCase ) )
lowerCamelCase__ = nn.ModuleList(__lowerCAmelCase )
def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase=False , __lowerCAmelCase=True ):
'''simple docstring'''
lowerCamelCase__ = () if output_hidden_states else None
lowerCamelCase__ = pixel_values
for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ):
lowerCamelCase__ , lowerCamelCase__ = layers
# Get patch embeddings from hidden_states
lowerCamelCase__ = embedding_layer(__lowerCAmelCase )
# Send the embeddings through the blocks
for _, blk in enumerate(__lowerCAmelCase ):
lowerCamelCase__ = blk(__lowerCAmelCase )
lowerCamelCase__ = layer_outputs[0]
if output_hidden_states:
lowerCamelCase__ = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(v for v in [hidden_states, all_hidden_states] if v is not None )
return BaseModelOutputWithNoAttention(last_hidden_state=__lowerCAmelCase , hidden_states=__lowerCAmelCase )
class __A ( lowerCAmelCase ):
'''simple docstring'''
lowerCAmelCase_ = PoolFormerConfig
lowerCAmelCase_ = """poolformer"""
lowerCAmelCase_ = """pixel_values"""
lowerCAmelCase_ = True
def __lowerCamelCase ( self , __lowerCAmelCase ):
'''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.LayerNorm ):
module.bias.data.zero_()
module.weight.data.fill_(1.0 )
def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase=False ):
'''simple docstring'''
if isinstance(__lowerCAmelCase , __lowerCAmelCase ):
lowerCamelCase__ = value
_a = r"\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n"
_a = r"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`PoolFormerImageProcessor.__call__`] for details.\n"
@add_start_docstrings(
"""The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.""" , lowerCAmelCase , )
class __A ( lowerCAmelCase ):
'''simple docstring'''
def __init__( self , __lowerCAmelCase ):
'''simple docstring'''
super().__init__(__lowerCAmelCase )
lowerCamelCase__ = config
lowerCamelCase__ = PoolFormerEncoder(__lowerCAmelCase )
# Initialize weights and apply final processing
self.post_init()
def __lowerCamelCase ( self ):
'''simple docstring'''
return self.embeddings.patch_embeddings
@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 , __lowerCAmelCase = None , __lowerCAmelCase = None , __lowerCAmelCase = None , ):
'''simple docstring'''
lowerCamelCase__ = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
lowerCamelCase__ = return_dict if return_dict is not None else self.config.use_return_dict
if pixel_values is None:
raise ValueError('''You have to specify pixel_values''' )
lowerCamelCase__ = self.encoder(
__lowerCAmelCase , output_hidden_states=__lowerCAmelCase , return_dict=__lowerCAmelCase , )
lowerCamelCase__ = encoder_outputs[0]
if not return_dict:
return (sequence_output, None) + encoder_outputs[1:]
return BaseModelOutputWithNoAttention(
last_hidden_state=__lowerCAmelCase , hidden_states=encoder_outputs.hidden_states , )
class __A ( nn.Module ):
'''simple docstring'''
def __init__( self , __lowerCAmelCase ):
'''simple docstring'''
super().__init__()
lowerCamelCase__ = nn.Linear(config.hidden_size , config.hidden_size )
def __lowerCamelCase ( self , __lowerCAmelCase ):
'''simple docstring'''
lowerCamelCase__ = self.dense(__lowerCAmelCase )
return output
@add_start_docstrings(
"""
PoolFormer Model transformer with an image classification head on top
""" , lowerCAmelCase , )
class __A ( lowerCAmelCase ):
'''simple docstring'''
def __init__( self , __lowerCAmelCase ):
'''simple docstring'''
super().__init__(__lowerCAmelCase )
lowerCamelCase__ = config.num_labels
lowerCamelCase__ = PoolFormerModel(__lowerCAmelCase )
# Final norm
lowerCamelCase__ = PoolFormerGroupNorm(config.hidden_sizes[-1] )
# Classifier head
lowerCamelCase__ = (
nn.Linear(config.hidden_sizes[-1] , 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 , __lowerCAmelCase = None , __lowerCAmelCase = None , __lowerCAmelCase = None , __lowerCAmelCase = None , ):
'''simple docstring'''
lowerCamelCase__ = return_dict if return_dict is not None else self.config.use_return_dict
lowerCamelCase__ = self.poolformer(
__lowerCAmelCase , output_hidden_states=__lowerCAmelCase , return_dict=__lowerCAmelCase , )
lowerCamelCase__ = outputs[0]
lowerCamelCase__ = self.classifier(self.norm(__lowerCAmelCase ).mean([-2, -1] ) )
lowerCamelCase__ = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
lowerCamelCase__ = '''regression'''
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
lowerCamelCase__ = '''single_label_classification'''
else:
lowerCamelCase__ = '''multi_label_classification'''
if self.config.problem_type == "regression":
lowerCamelCase__ = MSELoss()
if self.num_labels == 1:
lowerCamelCase__ = loss_fct(logits.squeeze() , labels.squeeze() )
else:
lowerCamelCase__ = loss_fct(__lowerCAmelCase , __lowerCAmelCase )
elif self.config.problem_type == "single_label_classification":
lowerCamelCase__ = CrossEntropyLoss()
lowerCamelCase__ = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) )
elif self.config.problem_type == "multi_label_classification":
lowerCamelCase__ = BCEWithLogitsLoss()
lowerCamelCase__ = loss_fct(__lowerCAmelCase , __lowerCAmelCase )
if not return_dict:
lowerCamelCase__ = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return ImageClassifierOutputWithNoAttention(loss=__lowerCAmelCase , logits=__lowerCAmelCase , hidden_states=outputs.hidden_states )
| 481 | 0 |
'''simple docstring'''
from abc import ABC, abstractmethod
from argparse import ArgumentParser
class UpperCamelCase__ ( lowerCamelCase__ ):
"""simple docstring"""
@staticmethod
@abstractmethod
def snake_case ( __A : ArgumentParser ):
"""simple docstring"""
raise NotImplementedError()
@abstractmethod
def snake_case ( self : List[Any] ):
"""simple docstring"""
raise NotImplementedError()
| 602 |
'''simple docstring'''
import re
import string
import numpy as np
import datasets
__magic_name__ : Optional[Any] = '''
Returns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.
'''
__magic_name__ : Tuple = '''
Args:
predictions: List of predicted texts.
references: List of reference texts.
regexes_to_ignore: List, defaults to None. Regex expressions of characters to
ignore when calculating the exact matches. Note: these regexes are removed
from the input data before the changes based on the options below (e.g. ignore_case,
ignore_punctuation, ignore_numbers) are applied.
ignore_case: Boolean, defaults to False. If true, turns everything
to lowercase so that capitalization differences are ignored.
ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before
comparing predictions and references.
ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before
comparing predictions and references.
Returns:
exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.
Examples:
>>> exact_match = datasets.load_metric("exact_match")
>>> refs = ["the cat", "theater", "YELLING", "agent007"]
>>> preds = ["cat?", "theater", "yelling", "agent"]
>>> results = exact_match.compute(references=refs, predictions=preds)
>>> print(round(results["exact_match"], 1))
25.0
>>> exact_match = datasets.load_metric("exact_match")
>>> refs = ["the cat", "theater", "YELLING", "agent007"]
>>> preds = ["cat?", "theater", "yelling", "agent"]
>>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)
>>> print(round(results["exact_match"], 1))
50.0
>>> exact_match = datasets.load_metric("exact_match")
>>> refs = ["the cat", "theater", "YELLING", "agent007"]
>>> preds = ["cat?", "theater", "yelling", "agent"]
>>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)
>>> print(round(results["exact_match"], 1))
75.0
>>> exact_match = datasets.load_metric("exact_match")
>>> refs = ["the cat", "theater", "YELLING", "agent007"]
>>> preds = ["cat?", "theater", "yelling", "agent"]
>>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)
>>> print(round(results["exact_match"], 1))
100.0
>>> exact_match = datasets.load_metric("exact_match")
>>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]
>>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]
>>> results = exact_match.compute(references=refs, predictions=preds)
>>> print(round(results["exact_match"], 1))
33.3
'''
__magic_name__ : Any = '''
'''
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class UpperCamelCase__ ( datasets.Metric ):
"""simple docstring"""
def snake_case ( self : Union[str, Any] ):
"""simple docstring"""
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"predictions": datasets.Value("string" , id="sequence" ),
"references": datasets.Value("string" , id="sequence" ),
} ) , reference_urls=[] , )
def snake_case ( self : List[Any] , __A : int , __A : List[Any] , __A : List[str]=None , __A : Tuple=False , __A : Dict=False , __A : Optional[int]=False , ):
"""simple docstring"""
if regexes_to_ignore is not None:
for s in regexes_to_ignore:
_lowercase = np.array([re.sub(__A , "" , __A ) for x in predictions] )
_lowercase = np.array([re.sub(__A , "" , __A ) for x in references] )
else:
_lowercase = np.asarray(__A )
_lowercase = np.asarray(__A )
if ignore_case:
_lowercase = np.char.lower(__A )
_lowercase = np.char.lower(__A )
if ignore_punctuation:
_lowercase = string.punctuation.maketrans("" , "" , string.punctuation )
_lowercase = np.char.translate(__A , table=__A )
_lowercase = np.char.translate(__A , table=__A )
if ignore_numbers:
_lowercase = string.digits.maketrans("" , "" , string.digits )
_lowercase = np.char.translate(__A , table=__A )
_lowercase = np.char.translate(__A , table=__A )
_lowercase = predictions == references
return {"exact_match": np.mean(__A ) * 1_0_0}
| 602 | 1 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
_lowerCamelCase : Union[str, Any] = logging.get_logger(__name__)
_lowerCamelCase : Any = {
"""facebook/convnextv2-tiny-1k-224""": """https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json""",
}
class UpperCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ ):
'''simple docstring'''
UpperCAmelCase__ = '''convnextv2'''
def __init__( self : Optional[int] , UpperCAmelCase__ : Optional[int]=3 , UpperCAmelCase__ : List[Any]=4 , UpperCAmelCase__ : int=4 , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : str=None , UpperCAmelCase__ : Optional[Any]="gelu" , UpperCAmelCase__ : Optional[int]=0.02 , UpperCAmelCase__ : int=1e-12 , UpperCAmelCase__ : List[str]=0.0 , UpperCAmelCase__ : int=224 , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Any=None , **UpperCAmelCase__ : Optional[int] , ) ->Any:
'''simple docstring'''
super().__init__(**UpperCAmelCase__)
A__ = num_channels
A__ = patch_size
A__ = num_stages
A__ = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes
A__ = [3, 3, 9, 3] if depths is None else depths
A__ = hidden_act
A__ = initializer_range
A__ = layer_norm_eps
A__ = drop_path_rate
A__ = image_size
A__ = ['''stem'''] + [f"""stage{idx}""" for idx in range(1 , len(self.depths) + 1)]
A__ , A__ = get_aligned_output_features_output_indices(
out_features=UpperCAmelCase__ , out_indices=UpperCAmelCase__ , stage_names=self.stage_names)
| 87 |
"""simple docstring"""
import argparse
import os
import shutil
from pathlib import Path
import onnx
import torch
from packaging import version
from torch.onnx import export
from diffusers import OnnxRuntimeModel, OnnxStableDiffusionPipeline, StableDiffusionPipeline
__A = version.parse(version.parse(torch.__version__).base_version) < version.parse("""1.11""")
def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , ) ->Tuple:
"""simple docstring"""
output_path.parent.mkdir(parents=_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE )
# PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11,
# so we check the torch version for backwards compatibility
if is_torch_less_than_1_11:
export(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , f=output_path.as_posix() , input_names=_SCREAMING_SNAKE_CASE , output_names=_SCREAMING_SNAKE_CASE , dynamic_axes=_SCREAMING_SNAKE_CASE , do_constant_folding=_SCREAMING_SNAKE_CASE , use_external_data_format=_SCREAMING_SNAKE_CASE , enable_onnx_checker=_SCREAMING_SNAKE_CASE , opset_version=_SCREAMING_SNAKE_CASE , )
else:
export(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , f=output_path.as_posix() , input_names=_SCREAMING_SNAKE_CASE , output_names=_SCREAMING_SNAKE_CASE , dynamic_axes=_SCREAMING_SNAKE_CASE , do_constant_folding=_SCREAMING_SNAKE_CASE , opset_version=_SCREAMING_SNAKE_CASE , )
@torch.no_grad()
def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = False ) ->List[Any]:
"""simple docstring"""
lowerCAmelCase__ :List[Any] = torch.floataa if fpaa else torch.floataa
if fpaa and torch.cuda.is_available():
lowerCAmelCase__ :Tuple = 'cuda'
elif fpaa and not torch.cuda.is_available():
raise ValueError('`float16` model export is only supported on GPUs with CUDA' )
else:
lowerCAmelCase__ :List[Any] = 'cpu'
lowerCAmelCase__ :List[str] = StableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE , torch_dtype=_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE )
lowerCAmelCase__ :Dict = Path(_SCREAMING_SNAKE_CASE )
# TEXT ENCODER
lowerCAmelCase__ :str = pipeline.text_encoder.config.max_position_embeddings
lowerCAmelCase__ :Dict = pipeline.text_encoder.config.hidden_size
lowerCAmelCase__ :List[Any] = pipeline.tokenizer(
'A sample prompt' , padding='max_length' , max_length=pipeline.tokenizer.model_max_length , truncation=_SCREAMING_SNAKE_CASE , return_tensors='pt' , )
onnx_export(
pipeline.text_encoder , model_args=(text_input.input_ids.to(device=_SCREAMING_SNAKE_CASE , dtype=torch.intaa )) , output_path=output_path / 'text_encoder' / 'model.onnx' , ordered_input_names=['input_ids'] , output_names=['last_hidden_state', 'pooler_output'] , dynamic_axes={
'input_ids': {0: 'batch', 1: 'sequence'},
} , opset=_SCREAMING_SNAKE_CASE , )
del pipeline.text_encoder
# UNET
lowerCAmelCase__ :int = pipeline.unet.config.in_channels
lowerCAmelCase__ :Optional[Any] = pipeline.unet.config.sample_size
lowerCAmelCase__ :Dict = output_path / 'unet' / 'model.onnx'
onnx_export(
pipeline.unet , model_args=(
torch.randn(2 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ),
torch.randn(2 ).to(device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ),
torch.randn(2 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ),
False,
) , output_path=_SCREAMING_SNAKE_CASE , ordered_input_names=['sample', 'timestep', 'encoder_hidden_states', 'return_dict'] , output_names=['out_sample'] , dynamic_axes={
'sample': {0: 'batch', 1: 'channels', 2: 'height', 3: 'width'},
'timestep': {0: 'batch'},
'encoder_hidden_states': {0: 'batch', 1: 'sequence'},
} , opset=_SCREAMING_SNAKE_CASE , use_external_data_format=_SCREAMING_SNAKE_CASE , )
lowerCAmelCase__ :List[Any] = str(unet_path.absolute().as_posix() )
lowerCAmelCase__ :int = os.path.dirname(_SCREAMING_SNAKE_CASE )
lowerCAmelCase__ :str = onnx.load(_SCREAMING_SNAKE_CASE )
# clean up existing tensor files
shutil.rmtree(_SCREAMING_SNAKE_CASE )
os.mkdir(_SCREAMING_SNAKE_CASE )
# collate external tensor files into one
onnx.save_model(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , save_as_external_data=_SCREAMING_SNAKE_CASE , all_tensors_to_one_file=_SCREAMING_SNAKE_CASE , location='weights.pb' , convert_attribute=_SCREAMING_SNAKE_CASE , )
del pipeline.unet
# VAE ENCODER
lowerCAmelCase__ :int = pipeline.vae
lowerCAmelCase__ :Optional[Any] = vae_encoder.config.in_channels
lowerCAmelCase__ :int = vae_encoder.config.sample_size
# need to get the raw tensor output (sample) from the encoder
lowerCAmelCase__ :str = lambda _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : vae_encoder.encode(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )[0].sample()
onnx_export(
_SCREAMING_SNAKE_CASE , model_args=(
torch.randn(1 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ),
False,
) , output_path=output_path / 'vae_encoder' / 'model.onnx' , ordered_input_names=['sample', 'return_dict'] , output_names=['latent_sample'] , dynamic_axes={
'sample': {0: 'batch', 1: 'channels', 2: 'height', 3: 'width'},
} , opset=_SCREAMING_SNAKE_CASE , )
# VAE DECODER
lowerCAmelCase__ :int = pipeline.vae
lowerCAmelCase__ :List[Any] = vae_decoder.config.latent_channels
lowerCAmelCase__ :Optional[int] = vae_decoder.config.out_channels
# forward only through the decoder part
lowerCAmelCase__ :Any = vae_encoder.decode
onnx_export(
_SCREAMING_SNAKE_CASE , model_args=(
torch.randn(1 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ),
False,
) , output_path=output_path / 'vae_decoder' / 'model.onnx' , ordered_input_names=['latent_sample', 'return_dict'] , output_names=['sample'] , dynamic_axes={
'latent_sample': {0: 'batch', 1: 'channels', 2: 'height', 3: 'width'},
} , opset=_SCREAMING_SNAKE_CASE , )
del pipeline.vae
# SAFETY CHECKER
if pipeline.safety_checker is not None:
lowerCAmelCase__ :Optional[int] = pipeline.safety_checker
lowerCAmelCase__ :Optional[int] = safety_checker.config.vision_config.num_channels
lowerCAmelCase__ :Any = safety_checker.config.vision_config.image_size
lowerCAmelCase__ :List[str] = safety_checker.forward_onnx
onnx_export(
pipeline.safety_checker , model_args=(
torch.randn(
1 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ).to(device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ),
torch.randn(1 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to(device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ),
) , output_path=output_path / 'safety_checker' / 'model.onnx' , ordered_input_names=['clip_input', 'images'] , output_names=['out_images', 'has_nsfw_concepts'] , dynamic_axes={
'clip_input': {0: 'batch', 1: 'channels', 2: 'height', 3: 'width'},
'images': {0: 'batch', 1: 'height', 2: 'width', 3: 'channels'},
} , opset=_SCREAMING_SNAKE_CASE , )
del pipeline.safety_checker
lowerCAmelCase__ :Union[str, Any] = OnnxRuntimeModel.from_pretrained(output_path / 'safety_checker' )
lowerCAmelCase__ :Dict = pipeline.feature_extractor
else:
lowerCAmelCase__ :Tuple = None
lowerCAmelCase__ :Optional[int] = None
lowerCAmelCase__ :List[str] = OnnxStableDiffusionPipeline(
vae_encoder=OnnxRuntimeModel.from_pretrained(output_path / 'vae_encoder' ) , vae_decoder=OnnxRuntimeModel.from_pretrained(output_path / 'vae_decoder' ) , text_encoder=OnnxRuntimeModel.from_pretrained(output_path / 'text_encoder' ) , tokenizer=pipeline.tokenizer , unet=OnnxRuntimeModel.from_pretrained(output_path / 'unet' ) , scheduler=pipeline.scheduler , safety_checker=_SCREAMING_SNAKE_CASE , feature_extractor=_SCREAMING_SNAKE_CASE , requires_safety_checker=safety_checker is not None , )
onnx_pipeline.save_pretrained(_SCREAMING_SNAKE_CASE )
print('ONNX pipeline saved to' , _SCREAMING_SNAKE_CASE )
del pipeline
del onnx_pipeline
lowerCAmelCase__ :Dict = OnnxStableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE , provider='CPUExecutionProvider' )
print('ONNX pipeline is loadable' )
if __name__ == "__main__":
__A = argparse.ArgumentParser()
parser.add_argument(
"""--model_path""",
type=str,
required=True,
help="""Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).""",
)
parser.add_argument("""--output_path""", type=str, required=True, help="""Path to the output model.""")
parser.add_argument(
"""--opset""",
default=14,
type=int,
help="""The version of the ONNX operator set to use.""",
)
parser.add_argument("""--fp16""", action="""store_true""", default=False, help="""Export the models in `float16` mode""")
__A = parser.parse_args()
convert_models(args.model_path, args.output_path, args.opset, args.fpaa)
| 93 | 0 |
'''simple docstring'''
def lowerCAmelCase__ ( a_ : Dict ) -> str:
UpperCAmelCase__ : Any = int(lowerCamelCase__ )
if decimal in (0, 1): # Exit cases for the recursion
return str(lowerCamelCase__ )
UpperCAmelCase__ : List[str] = divmod(lowerCamelCase__ , 2 )
return binary_recursive(lowerCamelCase__ ) + str(lowerCamelCase__ )
def lowerCAmelCase__ ( a_ : List[str] ) -> str:
UpperCAmelCase__ : str = str(lowerCamelCase__ ).strip()
if not number:
raise ValueError('''No input value was provided''' )
UpperCAmelCase__ : List[str] = "-" if number.startswith('''-''' ) else ""
UpperCAmelCase__ : List[Any] = number.lstrip('''-''' )
if not number.isnumeric():
raise ValueError('''Input value is not an integer''' )
return f"""{negative}0b{binary_recursive(int(lowerCamelCase__ ) )}"""
if __name__ == "__main__":
from doctest import testmod
testmod() | 710 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
UpperCamelCase_ = {
"configuration_convbert": ["CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConvBertConfig", "ConvBertOnnxConfig"],
"tokenization_convbert": ["ConvBertTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase_ = ["ConvBertTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase_ = [
"CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
"ConvBertForMaskedLM",
"ConvBertForMultipleChoice",
"ConvBertForQuestionAnswering",
"ConvBertForSequenceClassification",
"ConvBertForTokenClassification",
"ConvBertLayer",
"ConvBertModel",
"ConvBertPreTrainedModel",
"load_tf_weights_in_convbert",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase_ = [
"TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFConvBertForMaskedLM",
"TFConvBertForMultipleChoice",
"TFConvBertForQuestionAnswering",
"TFConvBertForSequenceClassification",
"TFConvBertForTokenClassification",
"TFConvBertLayer",
"TFConvBertModel",
"TFConvBertPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig
from .tokenization_convbert import ConvBertTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_convbert_fast import ConvBertTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_convbert import (
CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
ConvBertForMaskedLM,
ConvBertForMultipleChoice,
ConvBertForQuestionAnswering,
ConvBertForSequenceClassification,
ConvBertForTokenClassification,
ConvBertLayer,
ConvBertModel,
ConvBertPreTrainedModel,
load_tf_weights_in_convbert,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_convbert import (
TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFConvBertForMaskedLM,
TFConvBertForMultipleChoice,
TFConvBertForQuestionAnswering,
TFConvBertForSequenceClassification,
TFConvBertForTokenClassification,
TFConvBertLayer,
TFConvBertModel,
TFConvBertPreTrainedModel,
)
else:
import sys
UpperCamelCase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__) | 599 | 0 |
'''simple docstring'''
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__snake_case = {
"""configuration_xmod""": [
"""XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP""",
"""XmodConfig""",
"""XmodOnnxConfig""",
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__snake_case = [
"""XMOD_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""XmodForCausalLM""",
"""XmodForMaskedLM""",
"""XmodForMultipleChoice""",
"""XmodForQuestionAnswering""",
"""XmodForSequenceClassification""",
"""XmodForTokenClassification""",
"""XmodModel""",
"""XmodPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_xmod import (
XMOD_PRETRAINED_MODEL_ARCHIVE_LIST,
XmodForCausalLM,
XmodForMaskedLM,
XmodForMultipleChoice,
XmodForQuestionAnswering,
XmodForSequenceClassification,
XmodForTokenClassification,
XmodModel,
XmodPreTrainedModel,
)
else:
import sys
__snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 451 | '''simple docstring'''
import csv
from collections import defaultdict
from dataclasses import dataclass, field
from typing import List, Optional
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import ScalarFormatter
from transformers import HfArgumentParser
def A_ ( SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None ) ->str:
return field(default_factory=lambda: default , metadata=SCREAMING_SNAKE_CASE_ )
@dataclass
class _a :
"""simple docstring"""
A_ = field(
metadata={'''help''': '''The csv file to plot.'''} , )
A_ = field(
default=__a , metadata={'''help''': '''Whether to plot along batch size or sequence length. Defaults to sequence length.'''} , )
A_ = field(
default=__a , metadata={'''help''': '''Whether the csv file has time results or memory results. Defaults to memory results.'''} , )
A_ = field(
default=__a , metadata={'''help''': '''Disable logarithmic scale when plotting'''} , )
A_ = field(
default=__a , metadata={
'''help''': '''Whether the csv file has training results or inference results. Defaults to inference results.'''
} , )
A_ = field(
default=__a , metadata={'''help''': '''Filename under which the plot will be saved. If unused no plot is saved.'''} , )
A_ = list_field(
default=__a , metadata={'''help''': '''List of model names that are used instead of the ones in the csv file.'''} )
def A_ ( SCREAMING_SNAKE_CASE_ ) ->Dict:
try:
int(SCREAMING_SNAKE_CASE_ )
return True
except ValueError:
return False
def A_ ( SCREAMING_SNAKE_CASE_ ) ->int:
try:
float(SCREAMING_SNAKE_CASE_ )
return True
except ValueError:
return False
class _a :
"""simple docstring"""
def __init__( self : str , lowercase_ : List[str] ):
'''simple docstring'''
lowercase_ = args
lowercase_ = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} )
with open(self.args.csv_file , newline="""""" ) as csv_file:
lowercase_ = csv.DictReader(lowercase_ )
for row in reader:
lowercase_ = row["""model"""]
self.result_dict[model_name]["bsz"].append(int(row["""batch_size"""] ) )
self.result_dict[model_name]["seq_len"].append(int(row["""sequence_length"""] ) )
if can_convert_to_int(row["""result"""] ):
# value is not None
lowercase_ = int(row["""result"""] )
elif can_convert_to_float(row["""result"""] ):
# value is not None
lowercase_ = float(row["""result"""] )
def lowerCamelCase__ ( self : str ):
'''simple docstring'''
lowercase_ , lowercase_ = plt.subplots()
lowercase_ = """Time usage""" if self.args.is_time else """Memory usage"""
lowercase_ = title_str + """ for training""" if self.args.is_train else title_str + """ for inference"""
if not self.args.no_log_scale:
# set logarithm scales
ax.set_xscale("""log""" )
ax.set_yscale("""log""" )
for axis in [ax.xaxis, ax.yaxis]:
axis.set_major_formatter(ScalarFormatter() )
for model_name_idx, model_name in enumerate(self.result_dict.keys() ):
lowercase_ = sorted(set(self.result_dict[model_name]["""bsz"""] ) )
lowercase_ = sorted(set(self.result_dict[model_name]["""seq_len"""] ) )
lowercase_ = self.result_dict[model_name]["""result"""]
((lowercase_) , (lowercase_)) = (
(batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes)
)
lowercase_ = (
model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx]
)
for inner_loop_value in inner_loop_array:
if self.args.plot_along_batch:
lowercase_ = np.asarray(
[results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] , dtype=lowercase_ , )
else:
lowercase_ = np.asarray(
[results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] , dtype=np.floataa , )
((lowercase_) , (lowercase_)) = (
("""batch_size""", """len""") if self.args.plot_along_batch else ("""in #tokens""", """bsz""")
)
lowercase_ = np.asarray(lowercase_ , lowercase_ )[: len(lowercase_ )]
plt.scatter(
lowercase_ , lowercase_ , label=F"""{label_model_name} - {inner_loop_label}: {inner_loop_value}""" )
plt.plot(lowercase_ , lowercase_ , """--""" )
title_str += F""" {label_model_name} vs."""
lowercase_ = title_str[:-4]
lowercase_ = """Time in s""" if self.args.is_time else """Memory in MB"""
# plot
plt.title(lowercase_ )
plt.xlabel(lowercase_ )
plt.ylabel(lowercase_ )
plt.legend()
if self.args.figure_png_file is not None:
plt.savefig(self.args.figure_png_file )
else:
plt.show()
def A_ ( ) ->Tuple:
lowercase_ = HfArgumentParser(SCREAMING_SNAKE_CASE_ )
lowercase_ = parser.parse_args_into_dataclasses()[0]
lowercase_ = Plot(args=SCREAMING_SNAKE_CASE_ )
plot.plot()
if __name__ == "__main__":
main()
| 451 | 1 |
"""simple docstring"""
import gc
import random
import unittest
import numpy as np
import torch
from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel
from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import floats_tensor, load_image, load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
class lowerCAmelCase__ ( _UpperCAmelCase , unittest.TestCase ):
"""simple docstring"""
__UpperCAmelCase : Union[str, Any] = ShapEImgaImgPipeline
__UpperCAmelCase : Dict = ["image"]
__UpperCAmelCase : Tuple = ["image"]
__UpperCAmelCase : List[Any] = [
"num_images_per_prompt",
"num_inference_steps",
"generator",
"latents",
"guidance_scale",
"frame_size",
"output_type",
"return_dict",
]
__UpperCAmelCase : Dict = False
@property
def snake_case ( self : List[str] ):
return 3_2
@property
def snake_case ( self : int ):
return 3_2
@property
def snake_case ( self : Optional[int] ):
return self.time_input_dim * 4
@property
def snake_case ( self : Any ):
return 8
@property
def snake_case ( self : Any ):
torch.manual_seed(0 )
__lowercase : Tuple = CLIPVisionConfig(
hidden_size=self.text_embedder_hidden_size , image_size=6_4 , projection_dim=self.text_embedder_hidden_size , intermediate_size=3_7 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , )
__lowercase : Tuple = CLIPVisionModel(lowercase_ )
return model
@property
def snake_case ( self : List[Any] ):
__lowercase : Optional[int] = CLIPImageProcessor(
crop_size=2_2_4 , do_center_crop=lowercase_ , do_normalize=lowercase_ , do_resize=lowercase_ , 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] , resample=3 , size=2_2_4 , )
return image_processor
@property
def snake_case ( self : Optional[Any] ):
torch.manual_seed(0 )
__lowercase : Optional[Any] = {
"""num_attention_heads""": 2,
"""attention_head_dim""": 1_6,
"""embedding_dim""": self.time_input_dim,
"""num_embeddings""": 3_2,
"""embedding_proj_dim""": self.text_embedder_hidden_size,
"""time_embed_dim""": self.time_embed_dim,
"""num_layers""": 1,
"""clip_embed_dim""": self.time_input_dim * 2,
"""additional_embeddings""": 0,
"""time_embed_act_fn""": """gelu""",
"""norm_in_type""": """layer""",
"""embedding_proj_norm_type""": """layer""",
"""encoder_hid_proj_type""": None,
"""added_emb_type""": None,
}
__lowercase : Union[str, Any] = PriorTransformer(**lowercase_ )
return model
@property
def snake_case ( self : List[Any] ):
torch.manual_seed(0 )
__lowercase : str = {
"""param_shapes""": (
(self.renderer_dim, 9_3),
(self.renderer_dim, 8),
(self.renderer_dim, 8),
(self.renderer_dim, 8),
),
"""d_latent""": self.time_input_dim,
"""d_hidden""": self.renderer_dim,
"""n_output""": 1_2,
"""background""": (
0.1,
0.1,
0.1,
),
}
__lowercase : int = ShapERenderer(**lowercase_ )
return model
def snake_case ( self : Tuple ):
__lowercase : List[str] = self.dummy_prior
__lowercase : Union[str, Any] = self.dummy_image_encoder
__lowercase : Union[str, Any] = self.dummy_image_processor
__lowercase : List[Any] = self.dummy_renderer
__lowercase : List[str] = HeunDiscreteScheduler(
beta_schedule="exp" , num_train_timesteps=1_0_2_4 , prediction_type="sample" , use_karras_sigmas=lowercase_ , clip_sample=lowercase_ , clip_sample_range=1.0 , )
__lowercase : int = {
"""prior""": prior,
"""image_encoder""": image_encoder,
"""image_processor""": image_processor,
"""renderer""": renderer,
"""scheduler""": scheduler,
}
return components
def snake_case ( self : Optional[int] , lowercase__ : List[Any] , lowercase__ : List[str]=0 ):
__lowercase : str = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(lowercase_ ) ).to(lowercase_ )
if str(lowercase_ ).startswith("mps" ):
__lowercase : int = torch.manual_seed(lowercase_ )
else:
__lowercase : Dict = torch.Generator(device=lowercase_ ).manual_seed(lowercase_ )
__lowercase : int = {
"""image""": input_image,
"""generator""": generator,
"""num_inference_steps""": 1,
"""frame_size""": 3_2,
"""output_type""": """np""",
}
return inputs
def snake_case ( self : int ):
__lowercase : Optional[Any] = """cpu"""
__lowercase : Union[str, Any] = self.get_dummy_components()
__lowercase : Optional[Any] = self.pipeline_class(**lowercase_ )
__lowercase : Tuple = pipe.to(lowercase_ )
pipe.set_progress_bar_config(disable=lowercase_ )
__lowercase : int = pipe(**self.get_dummy_inputs(lowercase_ ) )
__lowercase : Union[str, Any] = output.images[0]
__lowercase : Tuple = image[0, -3:, -3:, -1]
assert image.shape == (2_0, 3_2, 3_2, 3)
__lowercase : Any = np.array(
[
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def snake_case ( self : str ):
# NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
self._test_inference_batch_consistent(batch_sizes=[1, 2] )
def snake_case ( self : str ):
__lowercase : Union[str, Any] = torch_device == """cpu"""
__lowercase : int = True
self._test_inference_batch_single_identical(
batch_size=2 , test_max_difference=lowercase_ , relax_max_difference=lowercase_ , )
def snake_case ( self : List[Any] ):
__lowercase : Optional[int] = self.get_dummy_components()
__lowercase : Any = self.pipeline_class(**lowercase_ )
__lowercase : Optional[int] = pipe.to(lowercase_ )
pipe.set_progress_bar_config(disable=lowercase_ )
__lowercase : List[str] = 1
__lowercase : Optional[Any] = 2
__lowercase : Optional[Any] = self.get_dummy_inputs(lowercase_ )
for key in inputs.keys():
if key in self.batch_params:
__lowercase : Tuple = batch_size * [inputs[key]]
__lowercase : List[Any] = pipe(**lowercase_ , num_images_per_prompt=lowercase_ )[0]
assert images.shape[0] == batch_size * num_images_per_prompt
@slow
@require_torch_gpu
class lowerCAmelCase__ ( unittest.TestCase ):
"""simple docstring"""
def snake_case ( self : str ):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def snake_case ( self : Optional[int] ):
__lowercase : Tuple = load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/shap_e/corgi.png" )
__lowercase : str = load_numpy(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
"/shap_e/test_shap_e_img2img_out.npy" )
__lowercase : Union[str, Any] = ShapEImgaImgPipeline.from_pretrained("openai/shap-e-img2img" )
__lowercase : List[Any] = pipe.to(lowercase_ )
pipe.set_progress_bar_config(disable=lowercase_ )
__lowercase : Optional[Any] = torch.Generator(device=lowercase_ ).manual_seed(0 )
__lowercase : List[Any] = pipe(
lowercase_ , generator=lowercase_ , guidance_scale=3.0 , num_inference_steps=6_4 , frame_size=6_4 , output_type="np" , ).images[0]
assert images.shape == (2_0, 6_4, 6_4, 3)
assert_mean_pixel_difference(lowercase_ , lowercase_ )
| 708 |
"""simple docstring"""
import numpy as np
import torch
from torch.nn import CrossEntropyLoss
from transformers import AutoModelForCausalLM, AutoTokenizer
import datasets
from datasets import logging
__A : str = '\\n\n'
__A : int = '\nPerplexity (PPL) is one of the most common metrics for evaluating language models.\nIt is defined as the exponentiated average negative log-likelihood of a sequence.\n\nFor more information, see https://huggingface.co/docs/transformers/perplexity\n'
__A : Optional[Any] = '\nArgs:\n model_id (str): model used for calculating Perplexity\n NOTE: Perplexity can only be calculated for causal language models.\n This includes models such as gpt2, causal variations of bert,\n causal versions of t5, and more (the full list can be found\n in the AutoModelForCausalLM documentation here:\n https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )\n\n input_texts (list of str): input text, each separate text snippet\n is one list entry.\n batch_size (int): the batch size to run texts through the model. Defaults to 16.\n add_start_token (bool): whether to add the start token to the texts,\n so the perplexity can include the probability of the first word. Defaults to True.\n device (str): device to run on, defaults to \'cuda\' when available\nReturns:\n perplexity: dictionary containing the perplexity scores for the texts\n in the input list, as well as the mean perplexity. If one of the input texts is\n longer than the max input length of the model, then it is truncated to the\n max length for the perplexity computation.\nExamples:\n Example 1:\n >>> perplexity = datasets.load_metric("perplexity")\n >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"]\n >>> results = perplexity.compute(model_id=\'gpt2\',\n ... add_start_token=False,\n ... input_texts=input_texts) # doctest:+ELLIPSIS\n >>> print(list(results.keys()))\n [\'perplexities\', \'mean_perplexity\']\n >>> print(round(results["mean_perplexity"], 2))\n 78.22\n >>> print(round(results["perplexities"][0], 2))\n 11.11\n\n Example 2:\n >>> perplexity = datasets.load_metric("perplexity")\n >>> input_texts = datasets.load_dataset("wikitext",\n ... "wikitext-2-raw-v1",\n ... split="test")["text"][:50] # doctest:+ELLIPSIS\n [...]\n >>> input_texts = [s for s in input_texts if s!=\'\']\n >>> results = perplexity.compute(model_id=\'gpt2\',\n ... input_texts=input_texts) # doctest:+ELLIPSIS\n >>> print(list(results.keys()))\n [\'perplexities\', \'mean_perplexity\']\n >>> print(round(results["mean_perplexity"], 2))\n 60.35\n >>> print(round(results["perplexities"][0], 2))\n 81.12\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class lowerCAmelCase__ ( datasets.Metric ):
"""simple docstring"""
def snake_case ( self : Dict ):
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"input_texts": datasets.Value("string" ),
} ) , reference_urls=["https://huggingface.co/docs/transformers/perplexity"] , )
def snake_case ( self : Optional[Any] , lowercase__ : int , lowercase__ : str , lowercase__ : int = 1_6 , lowercase__ : bool = True , lowercase__ : List[Any]=None ):
if device is not None:
assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
if device == "gpu":
__lowercase : Optional[Any] = "cuda"
else:
__lowercase : Optional[Any] = "cuda" if torch.cuda.is_available() else "cpu"
__lowercase : List[str] = AutoModelForCausalLM.from_pretrained(lowercase__ )
__lowercase : str = model.to(lowercase__ )
__lowercase : Any = AutoTokenizer.from_pretrained(lowercase__ )
# if batch_size > 1 (which generally leads to padding being required), and
# if there is not an already assigned pad_token, assign an existing
# special token to also be the padding token
if tokenizer.pad_token is None and batch_size > 1:
__lowercase : Any = list(tokenizer.special_tokens_map_extended.values() )
# check that the model already has at least one special token defined
assert (
len(lowercase__ ) > 0
), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1."
# assign one of the special tokens to also be the pad token
tokenizer.add_special_tokens({"pad_token": existing_special_tokens[0]} )
if add_start_token:
# leave room for <BOS> token to be added:
assert (
tokenizer.bos_token is not None
), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False"
__lowercase : Any = model.config.max_length - 1
else:
__lowercase : Union[str, Any] = model.config.max_length
__lowercase : List[Any] = tokenizer(
lowercase__ , add_special_tokens=lowercase__ , padding=lowercase__ , truncation=lowercase__ , max_length=lowercase__ , return_tensors="pt" , return_attention_mask=lowercase__ , ).to(lowercase__ )
__lowercase : Tuple = encodings["input_ids"]
__lowercase : Tuple = encodings["attention_mask"]
# check that each input is long enough:
if add_start_token:
assert torch.all(torch.ge(attn_masks.sum(1 ) , 1 ) ), "Each input text must be at least one token long."
else:
assert torch.all(
torch.ge(attn_masks.sum(1 ) , 2 ) ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings."
__lowercase : Optional[int] = []
__lowercase : List[Any] = CrossEntropyLoss(reduction="none" )
for start_index in logging.tqdm(range(0 , len(lowercase__ ) , lowercase__ ) ):
__lowercase : List[str] = min(start_index + batch_size , len(lowercase__ ) )
__lowercase : Any = encoded_texts[start_index:end_index]
__lowercase : Dict = attn_masks[start_index:end_index]
if add_start_token:
__lowercase : str = torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0 ) ).to(lowercase__ )
__lowercase : Optional[Any] = torch.cat([bos_tokens_tensor, encoded_batch] , dim=1 )
__lowercase : Union[str, Any] = torch.cat(
[torch.ones(bos_tokens_tensor.size() , dtype=torch.intaa ).to(lowercase__ ), attn_mask] , dim=1 )
__lowercase : Optional[int] = encoded_batch
with torch.no_grad():
__lowercase : Any = model(lowercase__ , attention_mask=lowercase__ ).logits
__lowercase : Any = out_logits[..., :-1, :].contiguous()
__lowercase : Tuple = labels[..., 1:].contiguous()
__lowercase : str = attn_mask[..., 1:].contiguous()
__lowercase : Optional[int] = torch.expa(
(loss_fct(shift_logits.transpose(1 , 2 ) , lowercase__ ) * shift_attention_mask_batch).sum(1 )
/ shift_attention_mask_batch.sum(1 ) )
ppls += perplexity_batch.tolist()
return {"perplexities": ppls, "mean_perplexity": np.mean(lowercase__ )}
| 281 | 0 |
'''simple docstring'''
def lowercase__ ( __UpperCamelCase : list ):
'''simple docstring'''
if len(__UpperCamelCase ) <= 1:
return lst
__lowercase = 1
while i < len(__UpperCamelCase ):
if lst[i - 1] <= lst[i]:
i += 1
else:
__lowercase , __lowercase = lst[i], lst[i - 1]
i -= 1
if i == 0:
__lowercase = 1
return lst
if __name__ == "__main__":
snake_case : Union[str, Any] = input('Enter numbers separated by a comma:\n').strip()
snake_case : List[str] = [int(item) for item in user_input.split(',')]
print(gnome_sort(unsorted))
| 566 |
'''simple docstring'''
from manim import *
class lowerCamelCase__( snake_case_ ):
def __magic_name__ ( self ):
"""simple docstring"""
__lowercase = Rectangle(height=0.5 , width=0.5 )
__lowercase = Rectangle(height=0.25 , width=0.25 )
__lowercase = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 )
__lowercase = [mem.copy() for i in range(6 )]
__lowercase = [mem.copy() for i in range(6 )]
__lowercase = VGroup(*__UpperCAmelCase ).arrange(__UpperCAmelCase , buff=0 )
__lowercase = VGroup(*__UpperCAmelCase ).arrange(__UpperCAmelCase , buff=0 )
__lowercase = VGroup(__UpperCAmelCase , __UpperCAmelCase ).arrange(__UpperCAmelCase , buff=0 )
__lowercase = Text("""CPU""" , font_size=2_4 )
__lowercase = Group(__UpperCAmelCase , __UpperCAmelCase ).arrange(__UpperCAmelCase , buff=0.5 , aligned_edge=__UpperCAmelCase )
cpu.move_to([-2.5, -0.5, 0] )
self.add(__UpperCAmelCase )
__lowercase = [mem.copy() for i in range(4 )]
__lowercase = VGroup(*__UpperCAmelCase ).arrange(__UpperCAmelCase , buff=0 )
__lowercase = Text("""GPU""" , font_size=2_4 )
__lowercase = Group(__UpperCAmelCase , __UpperCAmelCase ).arrange(__UpperCAmelCase , buff=0.5 , aligned_edge=__UpperCAmelCase )
gpu.move_to([-1, -1, 0] )
self.add(__UpperCAmelCase )
__lowercase = [mem.copy() for i in range(6 )]
__lowercase = VGroup(*__UpperCAmelCase ).arrange(__UpperCAmelCase , buff=0 )
__lowercase = Text("""Model""" , font_size=2_4 )
__lowercase = Group(__UpperCAmelCase , __UpperCAmelCase ).arrange(__UpperCAmelCase , buff=0.5 , aligned_edge=__UpperCAmelCase )
model.move_to([3, -1.0, 0] )
self.add(__UpperCAmelCase )
__lowercase = []
__lowercase = []
__lowercase = []
for i, rect in enumerate(__UpperCAmelCase ):
rect.set_stroke(__UpperCAmelCase )
__lowercase = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(__UpperCAmelCase , opacity=0.7 )
if i == 0:
cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=__UpperCAmelCase )
cpu_target.set_x(cpu_target.get_x() + 0.1 )
elif i == 3:
cpu_target.next_to(model_cpu_arr[0] , direction=__UpperCAmelCase , buff=0.0 )
else:
cpu_target.next_to(model_cpu_arr[i - 1] , direction=__UpperCAmelCase , buff=0.0 )
self.add(__UpperCAmelCase )
model_cpu_arr.append(__UpperCAmelCase )
self.add(*__UpperCAmelCase , *__UpperCAmelCase , *__UpperCAmelCase )
__lowercase = [mem.copy() for i in range(6 )]
__lowercase = VGroup(*__UpperCAmelCase ).arrange(__UpperCAmelCase , buff=0 )
__lowercase = Text("""Loaded Checkpoint""" , font_size=2_4 )
__lowercase = Group(__UpperCAmelCase , __UpperCAmelCase ).arrange(__UpperCAmelCase , buff=0.5 , aligned_edge=__UpperCAmelCase )
checkpoint.move_to([3, 0.5, 0] )
self.add(__UpperCAmelCase )
__lowercase = []
__lowercase = []
for i, rect in enumerate(__UpperCAmelCase ):
__lowercase = fill.copy().set_fill(__UpperCAmelCase , opacity=0.7 )
target.move_to(__UpperCAmelCase )
ckpt_arr.append(__UpperCAmelCase )
__lowercase = target.copy()
if i < 5:
cpu_target.move_to(cpu_left_col_base[i + 1] )
else:
cpu_target.move_to(cpu_right_col_base[i - 5] )
ckpt_cpu_arr.append(__UpperCAmelCase )
self.add(*__UpperCAmelCase , *__UpperCAmelCase )
__lowercase = Square(side_length=2.2 )
key.move_to([-5, 2, 0] )
__lowercase = MarkupText(
F'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''' , font_size=1_8 , )
key_text.move_to([-5, 2.4, 0] )
self.add(__UpperCAmelCase , __UpperCAmelCase )
__lowercase = MarkupText(
F'''<span fgcolor=\'{BLUE}\'>●</span> Checkpoint''' , font_size=1_8 , )
blue_text.next_to(__UpperCAmelCase , DOWN * 2.4 , aligned_edge=key_text.get_left() )
self.add(__UpperCAmelCase )
__lowercase = MarkupText(
F'''Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.''' , font_size=2_4 , )
step_a.move_to([2, 2, 0] )
__lowercase = [meta_mem.copy() for i in range(6 )]
__lowercase = [meta_mem.copy() for i in range(6 )]
__lowercase = VGroup(*__UpperCAmelCase ).arrange(__UpperCAmelCase , buff=0 )
__lowercase = VGroup(*__UpperCAmelCase ).arrange(__UpperCAmelCase , buff=0 )
__lowercase = VGroup(__UpperCAmelCase , __UpperCAmelCase ).arrange(__UpperCAmelCase , buff=0 )
__lowercase = Text("""Disk""" , font_size=2_4 )
__lowercase = Group(__UpperCAmelCase , __UpperCAmelCase ).arrange(__UpperCAmelCase , buff=0.5 , aligned_edge=__UpperCAmelCase )
disk.move_to([-4.0, -1.25, 0] )
self.play(Write(__UpperCAmelCase , run_time=3 ) , Write(__UpperCAmelCase , run_time=1 ) , Create(__UpperCAmelCase , run_time=1 ) )
__lowercase = []
for i, rect in enumerate(__UpperCAmelCase ):
__lowercase = rect.copy()
target.generate_target()
target.target.move_to(disk_left_col_base[i] ).scale(0.5 )
animations.append(MoveToTarget(__UpperCAmelCase , run_time=1.5 ) )
self.play(*__UpperCAmelCase )
self.play(FadeOut(__UpperCAmelCase ) )
__lowercase = MarkupText(F'''Then, the checkpoint is removed from memory\nthrough garbage collection.''' , font_size=2_4 )
step_a.move_to([2, 2, 0] )
self.play(Write(__UpperCAmelCase , run_time=3 ) )
self.play(
FadeOut(__UpperCAmelCase , __UpperCAmelCase , *__UpperCAmelCase , *__UpperCAmelCase ) , )
self.wait()
| 566 | 1 |
'''simple docstring'''
import qiskit
def lowercase ( __magic_name__ = 2 ):
'''simple docstring'''
UpperCAmelCase : Optional[Any] = qubits
# Using Aer's simulator
UpperCAmelCase : Tuple = qiskit.Aer.get_backend("aer_simulator" )
# Creating a Quantum Circuit acting on the q register
UpperCAmelCase : int = qiskit.QuantumCircuit(__magic_name__ , __magic_name__ )
# Adding a H gate on qubit 0 (now q0 in superposition)
circuit.h(0 )
for i in range(1 , __magic_name__ ):
# Adding CX (CNOT) gate
circuit.cx(i - 1 , __magic_name__ )
# Mapping the quantum measurement to the classical bits
circuit.measure(list(range(__magic_name__ ) ) , list(range(__magic_name__ ) ) )
# Now measuring any one qubit would affect other qubits to collapse
# their super position and have same state as the measured one.
# Executing the circuit on the simulator
UpperCAmelCase : Optional[Any] = qiskit.execute(__magic_name__ , __magic_name__ , shots=1000 )
return job.result().get_counts(__magic_name__ )
if __name__ == "__main__":
print(F'Total count for various states are: {quantum_entanglement(3)}')
| 718 |
'''simple docstring'''
import os
import warnings
from typing import List, Optional
from ...tokenization_utils_base import BatchEncoding
from ...utils import logging
from .configuration_rag import RagConfig
a : Any = logging.get_logger(__name__)
class UpperCamelCase__ :
"""simple docstring"""
def __init__( self , snake_case , snake_case ):
'''simple docstring'''
UpperCAmelCase : List[Any] = question_encoder
UpperCAmelCase : Tuple = generator
UpperCAmelCase : int = self.question_encoder
def A_ ( self , snake_case ):
'''simple docstring'''
if os.path.isfile(snake_case ):
raise ValueError(f"Provided path ({save_directory}) should be a directory, not a file" )
os.makedirs(snake_case , exist_ok=snake_case )
UpperCAmelCase : Union[str, Any] = os.path.join(snake_case , "question_encoder_tokenizer" )
UpperCAmelCase : Dict = os.path.join(snake_case , "generator_tokenizer" )
self.question_encoder.save_pretrained(snake_case )
self.generator.save_pretrained(snake_case )
@classmethod
def A_ ( cls , snake_case , **snake_case ):
'''simple docstring'''
from ..auto.tokenization_auto import AutoTokenizer
UpperCAmelCase : Dict = kwargs.pop("config" , snake_case )
if config is None:
UpperCAmelCase : int = RagConfig.from_pretrained(snake_case )
UpperCAmelCase : List[Any] = AutoTokenizer.from_pretrained(
snake_case , config=config.question_encoder , subfolder="question_encoder_tokenizer" )
UpperCAmelCase : Union[str, Any] = AutoTokenizer.from_pretrained(
snake_case , config=config.generator , subfolder="generator_tokenizer" )
return cls(question_encoder=snake_case , generator=snake_case )
def __call__( self , *snake_case , **snake_case ):
'''simple docstring'''
return self.current_tokenizer(*snake_case , **snake_case )
def A_ ( self , *snake_case , **snake_case ):
'''simple docstring'''
return self.generator.batch_decode(*snake_case , **snake_case )
def A_ ( self , *snake_case , **snake_case ):
'''simple docstring'''
return self.generator.decode(*snake_case , **snake_case )
def A_ ( self ):
'''simple docstring'''
UpperCAmelCase : Optional[Any] = self.question_encoder
def A_ ( self ):
'''simple docstring'''
UpperCAmelCase : Dict = self.generator
def A_ ( self , snake_case , snake_case = None , snake_case = None , snake_case = None , snake_case = "longest" , snake_case = None , snake_case = True , **snake_case , ):
'''simple docstring'''
warnings.warn(
"`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the "
"regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` "
"context manager to prepare your targets. See the documentation of your specific tokenizer for more "
"details" , snake_case , )
if max_length is None:
UpperCAmelCase : Dict = self.current_tokenizer.model_max_length
UpperCAmelCase : List[str] = self(
snake_case , add_special_tokens=snake_case , return_tensors=snake_case , max_length=snake_case , padding=snake_case , truncation=snake_case , **snake_case , )
if tgt_texts is None:
return model_inputs
# Process tgt_texts
if max_target_length is None:
UpperCAmelCase : Optional[int] = self.current_tokenizer.model_max_length
UpperCAmelCase : Union[str, Any] = self(
text_target=snake_case , add_special_tokens=snake_case , return_tensors=snake_case , padding=snake_case , max_length=snake_case , truncation=snake_case , **snake_case , )
UpperCAmelCase : Optional[Any] = labels["input_ids"]
return model_inputs
| 609 | 0 |
"""simple docstring"""
import argparse
import math
import os
import torch
from neural_compressor.utils.pytorch import load
from PIL import Image
from transformers import CLIPTextModel, CLIPTokenizer
from diffusers import AutoencoderKL, StableDiffusionPipeline, UNetaDConditionModel
def lowerCamelCase_ ( ) ->Any:
"""simple docstring"""
__UpperCAmelCase : str = argparse.ArgumentParser()
parser.add_argument(
'''-m''' , '''--pretrained_model_name_or_path''' , type=UpperCAmelCase_ , default=UpperCAmelCase_ , required=UpperCAmelCase_ , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , )
parser.add_argument(
'''-c''' , '''--caption''' , type=UpperCAmelCase_ , default='''robotic cat with wings''' , help='''Text used to generate images.''' , )
parser.add_argument(
'''-n''' , '''--images_num''' , type=UpperCAmelCase_ , default=4 , help='''How much images to generate.''' , )
parser.add_argument(
'''-s''' , '''--seed''' , type=UpperCAmelCase_ , default=42 , help='''Seed for random process.''' , )
parser.add_argument(
'''-ci''' , '''--cuda_id''' , type=UpperCAmelCase_ , default=0 , help='''cuda_id.''' , )
__UpperCAmelCase : Union[str, Any] = parser.parse_args()
return args
def lowerCamelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) ->Dict:
"""simple docstring"""
if not len(UpperCAmelCase_ ) == rows * cols:
raise ValueError('''The specified number of rows and columns are not correct.''' )
__UpperCAmelCase , __UpperCAmelCase : int = imgs[0].size
__UpperCAmelCase : List[str] = Image.new('''RGB''' , size=(cols * w, rows * h) )
__UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = grid.size
for i, img in enumerate(UpperCAmelCase_ ):
grid.paste(UpperCAmelCase_ , box=(i % cols * w, i // cols * h) )
return grid
def lowerCamelCase_ ( UpperCAmelCase_ , UpperCAmelCase_="robotic cat with wings" , UpperCAmelCase_=7.5 , UpperCAmelCase_=50 , UpperCAmelCase_=1 , UpperCAmelCase_=42 , ) ->str:
"""simple docstring"""
__UpperCAmelCase : List[str] = torch.Generator(pipeline.device ).manual_seed(UpperCAmelCase_ )
__UpperCAmelCase : List[Any] = pipeline(
UpperCAmelCase_ , guidance_scale=UpperCAmelCase_ , num_inference_steps=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_images_per_prompt=UpperCAmelCase_ , ).images
__UpperCAmelCase : List[Any] = int(math.sqrt(UpperCAmelCase_ ) )
__UpperCAmelCase : List[Any] = image_grid(UpperCAmelCase_ , rows=_rows , cols=num_images_per_prompt // _rows )
return grid, images
lowercase__ :Optional[Any] = parse_args()
# Load models and create wrapper for stable diffusion
lowercase__ :Optional[Any] = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder='tokenizer')
lowercase__ :Union[str, Any] = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder='text_encoder')
lowercase__ :Optional[Any] = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder='vae')
lowercase__ :str = UNetaDConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder='unet')
lowercase__ :Dict = StableDiffusionPipeline.from_pretrained(
args.pretrained_model_name_or_path, text_encoder=text_encoder, vae=vae, unet=unet, tokenizer=tokenizer
)
lowercase__ :Tuple = lambda images, clip_input: (images, False)
if os.path.exists(os.path.join(args.pretrained_model_name_or_path, 'best_model.pt')):
lowercase__ :List[Any] = load(args.pretrained_model_name_or_path, model=unet)
unet.eval()
setattr(pipeline, 'unet', unet)
else:
lowercase__ :str = unet.to(torch.device('cuda', args.cuda_id))
lowercase__ :Dict = pipeline.to(unet.device)
lowercase__ , lowercase__ :Optional[int] = generate_images(pipeline, prompt=args.caption, num_images_per_prompt=args.images_num, seed=args.seed)
grid.save(os.path.join(args.pretrained_model_name_or_path, '{}.png'.format('_'.join(args.caption.split()))))
lowercase__ :Union[str, Any] = os.path.join(args.pretrained_model_name_or_path, '_'.join(args.caption.split()))
os.makedirs(dirname, exist_ok=True)
for idx, image in enumerate(images):
image.save(os.path.join(dirname, '{}.png'.format(idx + 1))) | 522 |
"""simple docstring"""
import copy
import os
from typing import Union
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowercase__ :List[str] = logging.get_logger(__name__)
lowercase__ :List[str] = {
'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 snake_case ( __UpperCAmelCase ):
'''simple docstring'''
_A : int = 'bridgetower_vision_model'
def __init__( self : str , __lowercase : Optional[Any]=768 , __lowercase : Tuple=12 , __lowercase : List[str]=3 , __lowercase : Any=16 , __lowercase : int=288 , __lowercase : List[Any]=1 , __lowercase : Any=1e-05 , __lowercase : int=False , __lowercase : Any=True , __lowercase : Any=False , **__lowercase : Union[str, Any] , ):
'''simple docstring'''
super().__init__(**__lowercase )
__UpperCAmelCase : Optional[Any] = hidden_size
__UpperCAmelCase : int = num_hidden_layers
__UpperCAmelCase : int = num_channels
__UpperCAmelCase : Optional[int] = patch_size
__UpperCAmelCase : List[str] = image_size
__UpperCAmelCase : Union[str, Any] = initializer_factor
__UpperCAmelCase : List[str] = layer_norm_eps
__UpperCAmelCase : Optional[int] = stop_gradient
__UpperCAmelCase : List[str] = share_layernorm
__UpperCAmelCase : int = remove_last_layer
@classmethod
def A_ ( cls : Optional[int] , __lowercase : Union[str, os.PathLike] , **__lowercase : Dict ):
'''simple docstring'''
__UpperCAmelCase , __UpperCAmelCase : Optional[Any] = cls.get_config_dict(__lowercase , **__lowercase )
if config_dict.get('''model_type''' ) == "bridgetower":
__UpperCAmelCase : Optional[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 snake_case ( __UpperCAmelCase ):
'''simple docstring'''
_A : str = 'bridgetower_text_model'
def __init__( self : Any , __lowercase : Dict=50_265 , __lowercase : int=768 , __lowercase : str=12 , __lowercase : Union[str, Any]=12 , __lowercase : str=1 , __lowercase : List[Any]=3_072 , __lowercase : Optional[Any]="gelu" , __lowercase : str=0.1 , __lowercase : Dict=0.1 , __lowercase : List[str]=514 , __lowercase : List[str]=1 , __lowercase : Any=1e-05 , __lowercase : Tuple=1 , __lowercase : str=0 , __lowercase : Optional[Any]=2 , __lowercase : Optional[int]="absolute" , __lowercase : Tuple=True , **__lowercase : str , ):
'''simple docstring'''
super().__init__(**__lowercase )
__UpperCAmelCase : Tuple = vocab_size
__UpperCAmelCase : int = hidden_size
__UpperCAmelCase : Dict = num_hidden_layers
__UpperCAmelCase : Any = num_attention_heads
__UpperCAmelCase : str = hidden_act
__UpperCAmelCase : List[Any] = initializer_factor
__UpperCAmelCase : List[Any] = intermediate_size
__UpperCAmelCase : Tuple = hidden_dropout_prob
__UpperCAmelCase : Optional[Any] = attention_probs_dropout_prob
__UpperCAmelCase : Any = max_position_embeddings
__UpperCAmelCase : Dict = type_vocab_size
__UpperCAmelCase : List[Any] = layer_norm_eps
__UpperCAmelCase : Dict = position_embedding_type
__UpperCAmelCase : List[Any] = use_cache
__UpperCAmelCase : Optional[Any] = pad_token_id
__UpperCAmelCase : Dict = bos_token_id
__UpperCAmelCase : Tuple = eos_token_id
@classmethod
def A_ ( cls : str , __lowercase : Union[str, os.PathLike] , **__lowercase : List[str] ):
'''simple docstring'''
__UpperCAmelCase , __UpperCAmelCase : Dict = cls.get_config_dict(__lowercase , **__lowercase )
if config_dict.get('''model_type''' ) == "bridgetower":
__UpperCAmelCase : List[str] = 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 snake_case ( __UpperCAmelCase ):
'''simple docstring'''
_A : Optional[int] = 'bridgetower'
def __init__( self : int , __lowercase : Any=True , __lowercase : List[Any]="gelu" , __lowercase : int=768 , __lowercase : Tuple=1 , __lowercase : List[Any]=1e-05 , __lowercase : Optional[Any]=False , __lowercase : str="add" , __lowercase : int=12 , __lowercase : Optional[int]=6 , __lowercase : List[str]=False , __lowercase : Union[str, Any]=False , __lowercase : Tuple=None , __lowercase : str=None , **__lowercase : List[str] , ):
'''simple docstring'''
__UpperCAmelCase : List[Any] = kwargs.pop('''text_config_dict''' , __lowercase )
__UpperCAmelCase : Any = kwargs.pop('''vision_config_dict''' , __lowercase )
super().__init__(**__lowercase )
__UpperCAmelCase : Optional[Any] = share_cross_modal_transformer_layers
__UpperCAmelCase : List[str] = hidden_act
__UpperCAmelCase : Tuple = hidden_size
__UpperCAmelCase : List[Any] = initializer_factor
__UpperCAmelCase : Optional[Any] = layer_norm_eps
__UpperCAmelCase : Dict = share_link_tower_layers
__UpperCAmelCase : Any = link_tower_type
__UpperCAmelCase : Tuple = num_attention_heads
__UpperCAmelCase : List[str] = num_hidden_layers
__UpperCAmelCase : Optional[int] = tie_word_embeddings
__UpperCAmelCase : Union[str, Any] = init_layernorm_from_vision_encoder
if text_config is None:
__UpperCAmelCase : List[str] = {}
logger.info('''`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values.''' )
if vision_config is None:
__UpperCAmelCase : Optional[Any] = {}
logger.info('''`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.''' )
__UpperCAmelCase : List[str] = BridgeTowerTextConfig(**__lowercase )
__UpperCAmelCase : List[Any] = BridgeTowerVisionConfig(**__lowercase )
@classmethod
def A_ ( cls : Any , __lowercase : BridgeTowerTextConfig , __lowercase : BridgeTowerVisionConfig , **__lowercase : Optional[Any] ):
'''simple docstring'''
return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__lowercase )
def A_ ( self : List[Any] ):
'''simple docstring'''
__UpperCAmelCase : Optional[int] = copy.deepcopy(self.__dict__ )
__UpperCAmelCase : Union[str, Any] = self.text_config.to_dict()
__UpperCAmelCase : int = self.vision_config.to_dict()
__UpperCAmelCase : Union[str, Any] = self.__class__.model_type
return output | 522 | 1 |
from sympy import diff, lambdify, symbols
from sympy.functions import * # noqa: F403
def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case = "x" ,__snake_case = 10**-10 ,__snake_case = 1 ,) -> complex:
'''simple docstring'''
lowerCamelCase__ = symbols(__snake_case )
lowerCamelCase__ = lambdify(__snake_case ,__snake_case )
lowerCamelCase__ = lambdify(__snake_case ,diff(__snake_case ,__snake_case ) )
lowerCamelCase__ = starting_point
while True:
if diff_function(__snake_case ) != 0:
lowerCamelCase__ = prev_guess - multiplicity * func(__snake_case ) / diff_function(
__snake_case )
else:
raise ZeroDivisionError('''Could not find root''' ) from None
# Precision is checked by comparing the difference of consecutive guesses
if abs(next_guess - prev_guess ) < precision:
return next_guess
lowerCamelCase__ = next_guess
# Let's Execute
if __name__ == "__main__":
# Find root of trigonometric function
# Find value of pi
print(f"""The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}""")
# Find root of polynomial
# Find fourth Root of 5
print(f"""The root of x**4 - 5 = 0 is {newton_raphson('x**4 -5', 0.4 +5j)}""")
# Find value of e
print(
"The root of log(y) - 1 = 0 is ",
f"""{newton_raphson('log(y) - 1', 2, variable='y')}""",
)
# Exponential Roots
print(
"The root of exp(x) - 1 = 0 is",
f"""{newton_raphson('exp(x) - 1', 10, precision=0.005)}""",
)
# Find root of cos(x)
print(f"""The root of cos(x) = 0 is {newton_raphson('cos(x)', 0)}""")
| 715 |
from dataclasses import dataclass
from typing import Optional
import torch
from torch import nn
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .attention import BasicTransformerBlock
from .modeling_utils import ModelMixin
@dataclass
class __A ( lowerCAmelCase ):
'''simple docstring'''
lowerCAmelCase_ = 42
class __A ( lowerCAmelCase , lowerCAmelCase ):
'''simple docstring'''
@register_to_config
def __init__( self , __lowerCAmelCase = 1_6 , __lowerCAmelCase = 8_8 , __lowerCAmelCase = None , __lowerCAmelCase = None , __lowerCAmelCase = 1 , __lowerCAmelCase = 0.0 , __lowerCAmelCase = 3_2 , __lowerCAmelCase = None , __lowerCAmelCase = False , __lowerCAmelCase = None , __lowerCAmelCase = "geglu" , __lowerCAmelCase = True , __lowerCAmelCase = True , ):
'''simple docstring'''
super().__init__()
lowerCamelCase__ = num_attention_heads
lowerCamelCase__ = attention_head_dim
lowerCamelCase__ = num_attention_heads * attention_head_dim
lowerCamelCase__ = in_channels
lowerCamelCase__ = torch.nn.GroupNorm(num_groups=__lowerCAmelCase , num_channels=__lowerCAmelCase , eps=1E-6 , affine=__lowerCAmelCase )
lowerCamelCase__ = nn.Linear(__lowerCAmelCase , __lowerCAmelCase )
# 3. Define transformers blocks
lowerCamelCase__ = nn.ModuleList(
[
BasicTransformerBlock(
__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , dropout=__lowerCAmelCase , cross_attention_dim=__lowerCAmelCase , activation_fn=__lowerCAmelCase , attention_bias=__lowerCAmelCase , double_self_attention=__lowerCAmelCase , norm_elementwise_affine=__lowerCAmelCase , )
for d in range(__lowerCAmelCase )
] )
lowerCamelCase__ = nn.Linear(__lowerCAmelCase , __lowerCAmelCase )
def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=1 , __lowerCAmelCase=None , __lowerCAmelCase = True , ):
'''simple docstring'''
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = hidden_states.shape
lowerCamelCase__ = batch_frames // num_frames
lowerCamelCase__ = hidden_states
lowerCamelCase__ = hidden_states[None, :].reshape(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
lowerCamelCase__ = hidden_states.permute(0 , 2 , 1 , 3 , 4 )
lowerCamelCase__ = self.norm(__lowerCAmelCase )
lowerCamelCase__ = hidden_states.permute(0 , 3 , 4 , 2 , 1 ).reshape(batch_size * height * width , __lowerCAmelCase , __lowerCAmelCase )
lowerCamelCase__ = self.proj_in(__lowerCAmelCase )
# 2. Blocks
for block in self.transformer_blocks:
lowerCamelCase__ = block(
__lowerCAmelCase , encoder_hidden_states=__lowerCAmelCase , timestep=__lowerCAmelCase , cross_attention_kwargs=__lowerCAmelCase , class_labels=__lowerCAmelCase , )
# 3. Output
lowerCamelCase__ = self.proj_out(__lowerCAmelCase )
lowerCamelCase__ = (
hidden_states[None, None, :]
.reshape(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
.permute(0 , 3 , 4 , 1 , 2 )
.contiguous()
)
lowerCamelCase__ = hidden_states.reshape(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
lowerCamelCase__ = hidden_states + residual
if not return_dict:
return (output,)
return TransformerTemporalModelOutput(sample=__lowerCAmelCase )
| 29 | 0 |
"""simple docstring"""
from itertools import product
from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey
from numpy import dot, exp, mgrid, pi, ravel, square, uinta, zeros
def __UpperCAmelCase ( snake_case_ : Dict , snake_case_ : Dict ) -> int:
"""simple docstring"""
_lowerCAmelCase = k_size // 2
_lowerCAmelCase , _lowerCAmelCase = mgrid[0 - center : k_size - center, 0 - center : k_size - center]
_lowerCAmelCase = 1 / (2 * pi * sigma) * exp(-(square(snake_case_ ) + square(snake_case_ )) / (2 * square(snake_case_ )) )
return g
def __UpperCAmelCase ( snake_case_ : List[Any] , snake_case_ : Any , snake_case_ : Optional[Any] ) -> str:
"""simple docstring"""
_lowerCAmelCase , _lowerCAmelCase = image.shape[0], image.shape[1]
# dst image height and width
_lowerCAmelCase = height - k_size + 1
_lowerCAmelCase = width - k_size + 1
# im2col, turn the k_size*k_size pixels into a row and np.vstack all rows
_lowerCAmelCase = zeros((dst_height * dst_width, k_size * k_size) )
_lowerCAmelCase = 0
for i, j in product(range(snake_case_ ) , range(snake_case_ ) ):
_lowerCAmelCase = ravel(image[i : i + k_size, j : j + k_size] )
_lowerCAmelCase = window
row += 1
# turn the kernel into shape(k*k, 1)
_lowerCAmelCase = gen_gaussian_kernel(snake_case_ , snake_case_ )
_lowerCAmelCase = ravel(snake_case_ )
# reshape and get the dst image
_lowerCAmelCase = dot(snake_case_ , snake_case_ ).reshape(snake_case_ , snake_case_ ).astype(snake_case_ )
return dst
if __name__ == "__main__":
# read original image
SCREAMING_SNAKE_CASE : Optional[int] = imread(R'''../image_data/lena.jpg''')
# turn image in gray scale value
SCREAMING_SNAKE_CASE : str = cvtColor(img, COLOR_BGR2GRAY)
# get values with two different mask size
SCREAMING_SNAKE_CASE : Union[str, Any] = gaussian_filter(gray, 3, sigma=1)
SCREAMING_SNAKE_CASE : Dict = gaussian_filter(gray, 5, sigma=0.8)
# show result images
imshow('''gaussian filter with 3x3 mask''', gaussianaxa)
imshow('''gaussian filter with 5x5 mask''', gaussianaxa)
waitKey() | 156 |
import random
def lowerCamelCase__ ( snake_case_ : int ) -> bool:
__snake_case = num - 1
__snake_case = 0
while s % 2 == 0:
__snake_case = s // 2
t += 1
for _ in range(5 ):
__snake_case = random.randrange(2 , num - 1 )
__snake_case = pow(snake_case_ , snake_case_ , snake_case_ )
if v != 1:
__snake_case = 0
while v != (num - 1):
if i == t - 1:
return False
else:
__snake_case = i + 1
__snake_case = (v**2) % num
return True
def lowerCamelCase__ ( snake_case_ : int ) -> bool:
if num < 2:
return False
__snake_case = [
2,
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97,
101,
103,
107,
109,
113,
127,
131,
137,
139,
149,
151,
157,
163,
167,
173,
179,
181,
191,
193,
197,
199,
211,
223,
227,
229,
233,
239,
241,
251,
257,
263,
269,
271,
277,
281,
283,
293,
307,
311,
313,
317,
331,
337,
347,
349,
353,
359,
367,
373,
379,
383,
389,
397,
401,
409,
419,
421,
431,
433,
439,
443,
449,
457,
461,
463,
467,
479,
487,
491,
499,
503,
509,
521,
523,
541,
547,
557,
563,
569,
571,
577,
587,
593,
599,
601,
607,
613,
617,
619,
631,
641,
643,
647,
653,
659,
661,
673,
677,
683,
691,
701,
709,
719,
727,
733,
739,
743,
751,
757,
761,
769,
773,
787,
797,
809,
811,
821,
823,
827,
829,
839,
853,
857,
859,
863,
877,
881,
883,
887,
907,
911,
919,
929,
937,
941,
947,
953,
967,
971,
977,
983,
991,
997,
]
if num in low_primes:
return True
for prime in low_primes:
if (num % prime) == 0:
return False
return rabin_miller(snake_case_ )
def lowerCamelCase__ ( snake_case_ : int = 1024 ) -> int:
while True:
__snake_case = random.randrange(2 ** (keysize - 1) , 2 ** (keysize) )
if is_prime_low_num(snake_case_ ):
return num
if __name__ == "__main__":
snake_case_ = generate_large_prime()
print(('Prime number:', num))
print(('is_prime_low_num:', is_prime_low_num(num)))
| 592 | 0 |
import requests
from bsa import BeautifulSoup
def _lowerCAmelCase( __A , __A ):
UpperCAmelCase = BeautifulSoup(requests.get(__A , params=__A ).content , "html.parser" )
UpperCAmelCase = soup.find("div" , attrs={"class": "gs_ri"} )
UpperCAmelCase = div.find("div" , attrs={"class": "gs_fl"} ).find_all("a" )
return anchors[2].get_text()
if __name__ == "__main__":
lowerCAmelCase__ = {
"title": (
"Precisely geometry controlled microsupercapacitors for ultrahigh areal "
"capacitance, volumetric capacitance, and energy density"
),
"journal": "Chem. Mater.",
"volume": 30,
"pages": "3979-3990",
"year": 2018,
"hl": "en",
}
print(get_citation("https://scholar.google.com/scholar_lookup", params=params))
| 1 |
import argparse
import os
import re
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_dummies.py
lowerCAmelCase__ = "src/diffusers"
# Matches is_xxx_available()
lowerCAmelCase__ = re.compile(r"is\_([a-z_]*)_available\(\)")
# Matches from xxx import bla
lowerCAmelCase__ = re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n")
lowerCAmelCase__ = "\n{0} = None\n"
lowerCAmelCase__ = "\nclass {0}(metaclass=DummyObject):\n _backends = {1}\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, {1})\n\n @classmethod\n def from_config(cls, *args, **kwargs):\n requires_backends(cls, {1})\n\n @classmethod\n def from_pretrained(cls, *args, **kwargs):\n requires_backends(cls, {1})\n"
lowerCAmelCase__ = "\ndef {0}(*args, **kwargs):\n requires_backends({0}, {1})\n"
def _lowerCAmelCase( __A ):
UpperCAmelCase = _re_backend.findall(__A )
if len(__A ) == 0:
return None
return "_and_".join(__A )
def _lowerCAmelCase( ):
with open(os.path.join(__A , "__init__.py" ) , "r" , encoding="utf-8" , newline="\n" ) as f:
UpperCAmelCase = f.readlines()
# Get to the point we do the actual imports for type checking
UpperCAmelCase = 0
UpperCAmelCase = {}
# Go through the end of the file
while line_index < len(__A ):
# If the line contains is_backend_available, we grab all objects associated with the `else` block
UpperCAmelCase = find_backend(lines[line_index] )
if backend is not None:
while not lines[line_index].startswith("else:" ):
line_index += 1
line_index += 1
UpperCAmelCase = []
# Until we unindent, add backend objects to the list
while line_index < len(__A ) and len(lines[line_index] ) > 1:
UpperCAmelCase = lines[line_index]
UpperCAmelCase = _re_single_line_import.search(__A )
if single_line_import_search is not None:
objects.extend(single_line_import_search.groups()[0].split(", " ) )
elif line.startswith(" " * 8 ):
objects.append(line[8:-2] )
line_index += 1
if len(__A ) > 0:
UpperCAmelCase = objects
else:
line_index += 1
return backend_specific_objects
def _lowerCAmelCase( __A , __A ):
if name.isupper():
return DUMMY_CONSTANT.format(__A )
elif name.islower():
return DUMMY_FUNCTION.format(__A , __A )
else:
return DUMMY_CLASS.format(__A , __A )
def _lowerCAmelCase( __A=None ):
if backend_specific_objects is None:
UpperCAmelCase = read_init()
# For special correspondence backend to module name as used in the function requires_modulename
UpperCAmelCase = {}
for backend, objects in backend_specific_objects.items():
UpperCAmelCase = "[" + ", ".join(F"\"{b}\"" for b in backend.split("_and_" ) ) + "]"
UpperCAmelCase = "# This file is autogenerated by the command `make fix-copies`, do not edit.\n"
dummy_file += "from ..utils import DummyObject, requires_backends\n\n"
dummy_file += "\n".join([create_dummy_object(__A , __A ) for o in objects] )
UpperCAmelCase = dummy_file
return dummy_files
def _lowerCAmelCase( __A=False ):
UpperCAmelCase = create_dummy_files()
# For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py
UpperCAmelCase = {"torch": "pt"}
# Locate actual dummy modules and read their content.
UpperCAmelCase = os.path.join(__A , "utils" )
UpperCAmelCase = {
backend: os.path.join(__A , F"dummy_{short_names.get(__A , __A )}_objects.py" )
for backend in dummy_files.keys()
}
UpperCAmelCase = {}
for backend, file_path in dummy_file_paths.items():
if os.path.isfile(__A ):
with open(__A , "r" , encoding="utf-8" , newline="\n" ) as f:
UpperCAmelCase = f.read()
else:
UpperCAmelCase = ""
for backend in dummy_files.keys():
if dummy_files[backend] != actual_dummies[backend]:
if overwrite:
print(
F"Updating diffusers.utils.dummy_{short_names.get(__A , __A )}_objects.py as the main "
"__init__ has new objects." )
with open(dummy_file_paths[backend] , "w" , encoding="utf-8" , newline="\n" ) as f:
f.write(dummy_files[backend] )
else:
raise ValueError(
"The main __init__ has objects that are not present in "
F"diffusers.utils.dummy_{short_names.get(__A , __A )}_objects.py. Run `make fix-copies` "
"to fix this." )
if __name__ == "__main__":
lowerCAmelCase__ = argparse.ArgumentParser()
parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.")
lowerCAmelCase__ = parser.parse_args()
check_dummies(args.fix_and_overwrite)
| 1 | 1 |
'''simple docstring'''
import unittest
import numpy as np
from transformers.testing_utils import is_flaky, require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import DonutImageProcessor
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase):
def __init__( self , A_ , A_=7 , A_=3 , A_=18 , A_=30 , A_=400 , A_=True , A_=None , A_=True , A_=False , A_=True , A_=True , A_=[0.5, 0.5, 0.5] , A_=[0.5, 0.5, 0.5] , )-> Dict:
'''simple docstring'''
UpperCamelCase = parent
UpperCamelCase = batch_size
UpperCamelCase = num_channels
UpperCamelCase = image_size
UpperCamelCase = min_resolution
UpperCamelCase = max_resolution
UpperCamelCase = do_resize
UpperCamelCase = size if size is not None else {'height': 18, 'width': 20}
UpperCamelCase = do_thumbnail
UpperCamelCase = do_align_axis
UpperCamelCase = do_pad
UpperCamelCase = do_normalize
UpperCamelCase = image_mean
UpperCamelCase = image_std
def UpperCAmelCase_ ( self )-> List[Any]:
'''simple docstring'''
return {
"do_resize": self.do_resize,
"size": self.size,
"do_thumbnail": self.do_thumbnail,
"do_align_long_axis": self.do_align_axis,
"do_pad": self.do_pad,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
}
@require_torch
@require_vision
class SCREAMING_SNAKE_CASE__ ( snake_case_ , unittest.TestCase):
lowerCAmelCase_ = DonutImageProcessor if is_vision_available() else None
def UpperCAmelCase_ ( self )-> str:
'''simple docstring'''
UpperCamelCase = DonutImageProcessingTester(self )
@property
def UpperCAmelCase_ ( self )-> str:
'''simple docstring'''
return self.image_processor_tester.prepare_image_processor_dict()
def UpperCAmelCase_ ( self )-> Optional[int]:
'''simple docstring'''
UpperCamelCase = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(A_ , 'do_resize' ) )
self.assertTrue(hasattr(A_ , 'size' ) )
self.assertTrue(hasattr(A_ , 'do_thumbnail' ) )
self.assertTrue(hasattr(A_ , 'do_align_long_axis' ) )
self.assertTrue(hasattr(A_ , 'do_pad' ) )
self.assertTrue(hasattr(A_ , 'do_normalize' ) )
self.assertTrue(hasattr(A_ , 'image_mean' ) )
self.assertTrue(hasattr(A_ , 'image_std' ) )
def UpperCAmelCase_ ( self )-> Optional[int]:
'''simple docstring'''
UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'height': 18, 'width': 20} )
UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 )
self.assertEqual(image_processor.size , {'height': 42, 'width': 42} )
# Previous config had dimensions in (width, height) order
UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=(42, 84) )
self.assertEqual(image_processor.size , {'height': 84, 'width': 42} )
def UpperCAmelCase_ ( self )-> Tuple:
'''simple docstring'''
pass
@is_flaky()
def UpperCAmelCase_ ( self )-> Any:
'''simple docstring'''
UpperCamelCase = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=A_ )
for image in image_inputs:
self.assertIsInstance(A_ , Image.Image )
# Test not batched input
UpperCamelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
# Test batched
UpperCamelCase = image_processing(A_ , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
@is_flaky()
def UpperCAmelCase_ ( self )-> Optional[int]:
'''simple docstring'''
UpperCamelCase = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=A_ , numpify=A_ )
for image in image_inputs:
self.assertIsInstance(A_ , np.ndarray )
# Test not batched input
UpperCamelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
# Test batched
UpperCamelCase = image_processing(A_ , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
@is_flaky()
def UpperCAmelCase_ ( self )-> Dict:
'''simple docstring'''
UpperCamelCase = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=A_ , torchify=A_ )
for image in image_inputs:
self.assertIsInstance(A_ , torch.Tensor )
# Test not batched input
UpperCamelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
# Test batched
UpperCamelCase = image_processing(A_ , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
| 3 |
'''simple docstring'''
import copy
import os
import cva
import numpy as np
from matplotlib import pyplot as plt
class SCREAMING_SNAKE_CASE__ :
def __init__( self )-> Dict:
'''simple docstring'''
UpperCamelCase = ''
UpperCamelCase = ''
UpperCamelCase = []
UpperCamelCase = 0
UpperCamelCase = 256
UpperCamelCase = 0
UpperCamelCase = 0
UpperCamelCase = 0
UpperCamelCase = 0
def UpperCAmelCase_ ( self , A_ )-> str:
'''simple docstring'''
UpperCamelCase = cva.imread(A_ , 0 )
UpperCamelCase = copy.deepcopy(self.img )
UpperCamelCase , UpperCamelCase , UpperCamelCase = plt.hist(self.img.ravel() , 256 , [0, 256] , label='x' )
UpperCamelCase = np.sum(A_ )
for i in range(len(A_ ) ):
UpperCamelCase = x[i] / self.k
self.sk += prk
UpperCamelCase = (self.L - 1) * self.sk
if self.rem != 0:
UpperCamelCase = int(last % last )
UpperCamelCase = int(last + 1 if self.rem >= 0.5 else last )
self.last_list.append(A_ )
UpperCamelCase = int(np.ma.count(self.img ) / self.img[1].size )
UpperCamelCase = self.img[1].size
for i in range(self.number_of_cols ):
for j in range(self.number_of_rows ):
UpperCamelCase = self.img[j][i]
if num != self.last_list[num]:
UpperCamelCase = self.last_list[num]
cva.imwrite('output_data/output.jpg' , self.img )
def UpperCAmelCase_ ( self )-> Any:
'''simple docstring'''
plt.hist(self.img.ravel() , 256 , [0, 256] )
def UpperCAmelCase_ ( self )-> Optional[Any]:
'''simple docstring'''
cva.imshow('Output-Image' , self.img )
cva.imshow('Input-Image' , self.original_image )
cva.waitKey(5000 )
cva.destroyAllWindows()
if __name__ == "__main__":
lowerCAmelCase : Union[str, Any] = os.path.join(os.path.basename(__file__), 'image_data/input.jpg')
lowerCAmelCase : str = ConstantStretch()
stretcher.stretch(file_path)
stretcher.plot_histogram()
stretcher.show_image()
| 3 | 1 |
import requests
a = 'https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey='
def UpperCAmelCase_ ( UpperCAmelCase__ ):
# fetching a list of articles in json format
lowercase_ = requests.get(_NEWS_API + bbc_news_api_key ).json()
# each article in the list is a dict
for i, article in enumerate(bbc_news_page["""articles"""] , 1 ):
print(F'''{i}.) {article["title"]}''' )
if __name__ == "__main__":
fetch_bbc_news(bbc_news_api_key='<Your BBC News API key goes here>')
| 650 |
import torch
from diffusers import UnCLIPScheduler
from .test_schedulers import SchedulerCommonTest
class UpperCamelCase__ ( __magic_name__ ):
__SCREAMING_SNAKE_CASE : str = (UnCLIPScheduler,)
def UpperCAmelCase__ ( self : int , **UpperCamelCase__ : int ):
'''simple docstring'''
lowercase_ = {
"""num_train_timesteps""": 1_000,
"""variance_type""": """fixed_small_log""",
"""clip_sample""": True,
"""clip_sample_range""": 1.0,
"""prediction_type""": """epsilon""",
}
config.update(**UpperCamelCase__ )
return config
def UpperCAmelCase__ ( self : Tuple ):
'''simple docstring'''
for timesteps in [1, 5, 100, 1_000]:
self.check_over_configs(num_train_timesteps=UpperCamelCase__ )
def UpperCAmelCase__ ( self : Optional[Any] ):
'''simple docstring'''
for variance in ["fixed_small_log", "learned_range"]:
self.check_over_configs(variance_type=UpperCamelCase__ )
def UpperCAmelCase__ ( self : List[str] ):
'''simple docstring'''
for clip_sample in [True, False]:
self.check_over_configs(clip_sample=UpperCamelCase__ )
def UpperCAmelCase__ ( self : Any ):
'''simple docstring'''
for clip_sample_range in [1, 5, 10, 20]:
self.check_over_configs(clip_sample_range=UpperCamelCase__ )
def UpperCAmelCase__ ( self : Tuple ):
'''simple docstring'''
for prediction_type in ["epsilon", "sample"]:
self.check_over_configs(prediction_type=UpperCamelCase__ )
def UpperCAmelCase__ ( self : Optional[int] ):
'''simple docstring'''
for time_step in [0, 500, 999]:
for prev_timestep in [None, 5, 100, 250, 500, 750]:
if prev_timestep is not None and prev_timestep >= time_step:
continue
self.check_over_forward(time_step=UpperCamelCase__ , prev_timestep=UpperCamelCase__ )
def UpperCAmelCase__ ( self : Union[str, Any] ):
'''simple docstring'''
lowercase_ = self.scheduler_classes[0]
lowercase_ = self.get_scheduler_config(variance_type="""fixed_small_log""" )
lowercase_ = scheduler_class(**UpperCamelCase__ )
assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 1.0000e-10 ) ) < 1e-5
assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.0_549_625 ) ) < 1e-5
assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.9_994_987 ) ) < 1e-5
def UpperCAmelCase__ ( self : str ):
'''simple docstring'''
lowercase_ = self.scheduler_classes[0]
lowercase_ = self.get_scheduler_config(variance_type="""learned_range""" )
lowercase_ = scheduler_class(**UpperCamelCase__ )
lowercase_ = 0.5
assert scheduler._get_variance(1 , predicted_variance=UpperCamelCase__ ) - -10.1_712_790 < 1e-5
assert scheduler._get_variance(487 , predicted_variance=UpperCamelCase__ ) - -5.7_998_052 < 1e-5
assert scheduler._get_variance(999 , predicted_variance=UpperCamelCase__ ) - -0.0_010_011 < 1e-5
def UpperCAmelCase__ ( self : Optional[Any] ):
'''simple docstring'''
lowercase_ = self.scheduler_classes[0]
lowercase_ = self.get_scheduler_config()
lowercase_ = scheduler_class(**UpperCamelCase__ )
lowercase_ = scheduler.timesteps
lowercase_ = self.dummy_model()
lowercase_ = self.dummy_sample_deter
lowercase_ = torch.manual_seed(0 )
for i, t in enumerate(UpperCamelCase__ ):
# 1. predict noise residual
lowercase_ = model(UpperCamelCase__ , UpperCamelCase__ )
# 2. predict previous mean of sample x_t-1
lowercase_ = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , generator=UpperCamelCase__ ).prev_sample
lowercase_ = pred_prev_sample
lowercase_ = torch.sum(torch.abs(UpperCamelCase__ ) )
lowercase_ = torch.mean(torch.abs(UpperCamelCase__ ) )
assert abs(result_sum.item() - 252.2_682_495 ) < 1e-2
assert abs(result_mean.item() - 0.3_284_743 ) < 1e-3
def UpperCAmelCase__ ( self : int ):
'''simple docstring'''
lowercase_ = self.scheduler_classes[0]
lowercase_ = self.get_scheduler_config()
lowercase_ = scheduler_class(**UpperCamelCase__ )
scheduler.set_timesteps(25 )
lowercase_ = scheduler.timesteps
lowercase_ = self.dummy_model()
lowercase_ = self.dummy_sample_deter
lowercase_ = torch.manual_seed(0 )
for i, t in enumerate(UpperCamelCase__ ):
# 1. predict noise residual
lowercase_ = model(UpperCamelCase__ , UpperCamelCase__ )
if i + 1 == timesteps.shape[0]:
lowercase_ = None
else:
lowercase_ = timesteps[i + 1]
# 2. predict previous mean of sample x_t-1
lowercase_ = scheduler.step(
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , prev_timestep=UpperCamelCase__ , generator=UpperCamelCase__ ).prev_sample
lowercase_ = pred_prev_sample
lowercase_ = torch.sum(torch.abs(UpperCamelCase__ ) )
lowercase_ = torch.mean(torch.abs(UpperCamelCase__ ) )
assert abs(result_sum.item() - 258.2_044_983 ) < 1e-2
assert abs(result_mean.item() - 0.3_362_038 ) < 1e-3
def UpperCAmelCase__ ( self : List[str] ):
'''simple docstring'''
pass
def UpperCAmelCase__ ( self : int ):
'''simple docstring'''
pass
| 650 | 1 |
import argparse
import os
import re
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_dummies.py
_UpperCAmelCase : Tuple = "src/diffusers"
# Matches is_xxx_available()
_UpperCAmelCase : List[Any] = re.compile(r"is\_([a-z_]*)_available\(\)")
# Matches from xxx import bla
_UpperCAmelCase : int = re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n")
_UpperCAmelCase : List[Any] = "\n{0} = None\n"
_UpperCAmelCase : Tuple = "\nclass {0}(metaclass=DummyObject):\n _backends = {1}\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, {1})\n\n @classmethod\n def from_config(cls, *args, **kwargs):\n requires_backends(cls, {1})\n\n @classmethod\n def from_pretrained(cls, *args, **kwargs):\n requires_backends(cls, {1})\n"
_UpperCAmelCase : str = "\ndef {0}(*args, **kwargs):\n requires_backends({0}, {1})\n"
def lowerCAmelCase_ (lowercase__ : Optional[Any] ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase__ = _re_backend.findall(lowercase__ )
if len(lowercase__ ) == 0:
return None
return "_and_".join(lowercase__ )
def lowerCAmelCase_ () -> Union[str, Any]:
'''simple docstring'''
with open(os.path.join(lowercase__ , '''__init__.py''' ) , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f:
lowerCAmelCase__ = f.readlines()
# Get to the point we do the actual imports for type checking
lowerCAmelCase__ = 0
lowerCAmelCase__ = {}
# Go through the end of the file
while line_index < len(lowercase__ ):
# If the line contains is_backend_available, we grab all objects associated with the `else` block
lowerCAmelCase__ = find_backend(lines[line_index] )
if backend is not None:
while not lines[line_index].startswith('''else:''' ):
line_index += 1
line_index += 1
lowerCAmelCase__ = []
# Until we unindent, add backend objects to the list
while line_index < len(lowercase__ ) and len(lines[line_index] ) > 1:
lowerCAmelCase__ = lines[line_index]
lowerCAmelCase__ = _re_single_line_import.search(lowercase__ )
if single_line_import_search is not None:
objects.extend(single_line_import_search.groups()[0].split(''', ''' ) )
elif line.startswith(''' ''' * 8 ):
objects.append(line[8:-2] )
line_index += 1
if len(lowercase__ ) > 0:
lowerCAmelCase__ = objects
else:
line_index += 1
return backend_specific_objects
def lowerCAmelCase_ (lowercase__ : Optional[int] , lowercase__ : List[str] ) -> Optional[Any]:
'''simple docstring'''
if name.isupper():
return DUMMY_CONSTANT.format(lowercase__ )
elif name.islower():
return DUMMY_FUNCTION.format(lowercase__ , lowercase__ )
else:
return DUMMY_CLASS.format(lowercase__ , lowercase__ )
def lowerCAmelCase_ (lowercase__ : Tuple=None ) -> Any:
'''simple docstring'''
if backend_specific_objects is None:
lowerCAmelCase__ = read_init()
# For special correspondence backend to module name as used in the function requires_modulename
lowerCAmelCase__ = {}
for backend, objects in backend_specific_objects.items():
lowerCAmelCase__ = '''[''' + ''', '''.join(f'"{b}"' for b in backend.split('''_and_''' ) ) + ''']'''
lowerCAmelCase__ = '''# This file is autogenerated by the command `make fix-copies`, do not edit.\n'''
dummy_file += "from ..utils import DummyObject, requires_backends\n\n"
dummy_file += "\n".join([create_dummy_object(lowercase__ , lowercase__ ) for o in objects] )
lowerCAmelCase__ = dummy_file
return dummy_files
def lowerCAmelCase_ (lowercase__ : Dict=False ) -> Optional[Any]:
'''simple docstring'''
lowerCAmelCase__ = create_dummy_files()
# For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py
lowerCAmelCase__ = {'''torch''': '''pt'''}
# Locate actual dummy modules and read their content.
lowerCAmelCase__ = os.path.join(lowercase__ , '''utils''' )
lowerCAmelCase__ = {
backend: os.path.join(lowercase__ , f'dummy_{short_names.get(lowercase__ , lowercase__ )}_objects.py' )
for backend in dummy_files.keys()
}
lowerCAmelCase__ = {}
for backend, file_path in dummy_file_paths.items():
if os.path.isfile(lowercase__ ):
with open(lowercase__ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f:
lowerCAmelCase__ = f.read()
else:
lowerCAmelCase__ = ''''''
for backend in dummy_files.keys():
if dummy_files[backend] != actual_dummies[backend]:
if overwrite:
print(
f'Updating diffusers.utils.dummy_{short_names.get(lowercase__ , lowercase__ )}_objects.py as the main '
'''__init__ has new objects.''' )
with open(dummy_file_paths[backend] , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f:
f.write(dummy_files[backend] )
else:
raise ValueError(
'''The main __init__ has objects that are not present in '''
f'diffusers.utils.dummy_{short_names.get(lowercase__ , lowercase__ )}_objects.py. Run `make fix-copies` '
'''to fix this.''' )
if __name__ == "__main__":
_UpperCAmelCase : Optional[Any] = argparse.ArgumentParser()
parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.")
_UpperCAmelCase : Optional[int] = parser.parse_args()
check_dummies(args.fix_and_overwrite)
| 668 |
from collections import namedtuple
_UpperCAmelCase : Dict = namedtuple("from_to", "from_ to")
_UpperCAmelCase : str = {
"cubicmeter": from_to(1, 1),
"litre": from_to(0.001, 1_000),
"kilolitre": from_to(1, 1),
"gallon": from_to(0.00454, 264.172),
"cubicyard": from_to(0.76455, 1.30795),
"cubicfoot": from_to(0.028, 35.3147),
"cup": from_to(0.000236588, 4226.75),
}
def lowerCAmelCase_ (lowercase__ : float , lowercase__ : str , lowercase__ : str ) -> float:
'''simple docstring'''
if from_type not in METRIC_CONVERSION:
raise ValueError(
f'Invalid \'from_type\' value: {from_type!r} Supported values are:\n'
+ ''', '''.join(lowercase__ ) )
if to_type not in METRIC_CONVERSION:
raise ValueError(
f'Invalid \'to_type\' value: {to_type!r}. Supported values are:\n'
+ ''', '''.join(lowercase__ ) )
return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to
if __name__ == "__main__":
import doctest
doctest.testmod()
| 668 | 1 |
"""simple docstring"""
def lowercase ( _SCREAMING_SNAKE_CASE : Any = 10 , _SCREAMING_SNAKE_CASE : Tuple = 22 ):
'''simple docstring'''
_UpperCAmelCase = range(1 , __SCREAMING_SNAKE_CASE )
_UpperCAmelCase = range(1 , __SCREAMING_SNAKE_CASE )
return sum(
1 for power in powers for base in bases if len(str(base**power ) ) == power )
if __name__ == "__main__":
print(f'''{solution(10, 22) = }''')
| 701 |
"""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 _a ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase):
"""simple docstring"""
UpperCamelCase__ = StableDiffusionXLImgaImgPipeline
UpperCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""}
UpperCamelCase__ = PipelineTesterMixin.required_optional_params - {"""latents"""}
UpperCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
UpperCamelCase__ = IMAGE_TO_IMAGE_IMAGE_PARAMS
UpperCamelCase__ = IMAGE_TO_IMAGE_IMAGE_PARAMS
def lowercase__ ( self : Tuple )->int:
torch.manual_seed(0 )
_UpperCAmelCase = 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=__UpperCamelCase , 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 , )
_UpperCAmelCase = EulerDiscreteScheduler(
beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , steps_offset=1 , beta_schedule='''scaled_linear''' , timestep_spacing='''leading''' , )
torch.manual_seed(0 )
_UpperCAmelCase = 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 )
_UpperCAmelCase = 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 , )
_UpperCAmelCase = CLIPTextModel(__UpperCamelCase )
_UpperCAmelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' , local_files_only=__UpperCamelCase )
_UpperCAmelCase = CLIPTextModelWithProjection(__UpperCamelCase )
_UpperCAmelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' , local_files_only=__UpperCamelCase )
_UpperCAmelCase = {
'''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 lowercase__ ( self : int , __UpperCamelCase : Optional[int] , __UpperCamelCase : int=0 )->Any:
_UpperCAmelCase = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__UpperCamelCase ) ).to(__UpperCamelCase )
_UpperCAmelCase = image / 2 + 0.5
if str(__UpperCamelCase ).startswith('''mps''' ):
_UpperCAmelCase = torch.manual_seed(__UpperCamelCase )
else:
_UpperCAmelCase = torch.Generator(device=__UpperCamelCase ).manual_seed(__UpperCamelCase )
_UpperCAmelCase = {
'''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.7_5,
}
return inputs
def lowercase__ ( self : Any )->int:
_UpperCAmelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator
_UpperCAmelCase = self.get_dummy_components()
_UpperCAmelCase = StableDiffusionXLImgaImgPipeline(**__UpperCamelCase )
_UpperCAmelCase = sd_pipe.to(__UpperCamelCase )
sd_pipe.set_progress_bar_config(disable=__UpperCamelCase )
_UpperCAmelCase = self.get_dummy_inputs(__UpperCamelCase )
_UpperCAmelCase = sd_pipe(**__UpperCamelCase ).images
_UpperCAmelCase = image[0, -3:, -3:, -1]
assert image.shape == (1, 3_2, 3_2, 3)
_UpperCAmelCase = np.array([0.4_6_5_6, 0.4_8_4_0, 0.4_4_3_9, 0.6_6_9_8, 0.5_5_7_4, 0.4_5_2_4, 0.5_7_9_9, 0.5_9_4_3, 0.5_1_6_5] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def lowercase__ ( self : Optional[Any] )->Optional[int]:
super().test_attention_slicing_forward_pass(expected_max_diff=3e-3 )
def lowercase__ ( self : Optional[Any] )->List[Any]:
super().test_inference_batch_single_identical(expected_max_diff=3e-3 )
def lowercase__ ( self : List[str] )->str:
pass
def lowercase__ ( self : Dict )->List[str]:
_UpperCAmelCase = self.get_dummy_components()
_UpperCAmelCase = StableDiffusionXLImgaImgPipeline(**__UpperCamelCase )
_UpperCAmelCase = sd_pipe.to(__UpperCamelCase )
_UpperCAmelCase = sd_pipe.to(__UpperCamelCase )
sd_pipe.set_progress_bar_config(disable=__UpperCamelCase )
# forward without prompt embeds
_UpperCAmelCase = self.get_dummy_inputs(__UpperCamelCase )
_UpperCAmelCase = 3 * ['''this is a negative prompt''']
_UpperCAmelCase = negative_prompt
_UpperCAmelCase = 3 * [inputs['''prompt''']]
_UpperCAmelCase = sd_pipe(**__UpperCamelCase )
_UpperCAmelCase = output.images[0, -3:, -3:, -1]
# forward with prompt embeds
_UpperCAmelCase = self.get_dummy_inputs(__UpperCamelCase )
_UpperCAmelCase = 3 * ['''this is a negative prompt''']
_UpperCAmelCase = 3 * [inputs.pop('''prompt''' )]
(
(
_UpperCAmelCase
) , (
_UpperCAmelCase
) , (
_UpperCAmelCase
) , (
_UpperCAmelCase
) ,
) = sd_pipe.encode_prompt(__UpperCamelCase , negative_prompt=__UpperCamelCase )
_UpperCAmelCase = sd_pipe(
**__UpperCamelCase , prompt_embeds=__UpperCamelCase , negative_prompt_embeds=__UpperCamelCase , pooled_prompt_embeds=__UpperCamelCase , negative_pooled_prompt_embeds=__UpperCamelCase , )
_UpperCAmelCase = 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 _a ( unittest.TestCase):
"""simple docstring"""
def lowercase__ ( self : Union[str, Any] )->Any:
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def lowercase__ ( self : Optional[Any] , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : Dict="cpu" , __UpperCamelCase : int=torch.floataa , __UpperCamelCase : Optional[Any]=0 )->Union[str, Any]:
_UpperCAmelCase = torch.Generator(device=__UpperCamelCase ).manual_seed(__UpperCamelCase )
_UpperCAmelCase = np.random.RandomState(__UpperCamelCase ).standard_normal((1, 4, 6_4, 6_4) )
_UpperCAmelCase = torch.from_numpy(__UpperCamelCase ).to(device=__UpperCamelCase , dtype=__UpperCamelCase )
_UpperCAmelCase = {
'''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 lowercase__ ( self : Optional[Any] )->Optional[Any]:
_UpperCAmelCase = DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base''' )
pipe.to(__UpperCamelCase )
pipe.set_progress_bar_config(disable=__UpperCamelCase )
_UpperCAmelCase = self.get_inputs(__UpperCamelCase )
_UpperCAmelCase = pipe(**__UpperCamelCase ).images
_UpperCAmelCase = image[0, -3:, -3:, -1].flatten()
assert image.shape == (1, 5_1_2, 5_1_2, 3)
_UpperCAmelCase = np.array([0.4_9_4_9_3, 0.4_7_8_9_6, 0.4_0_7_9_8, 0.5_4_2_1_4, 0.5_3_2_1_2, 0.4_8_2_0_2, 0.4_7_6_5_6, 0.4_6_3_2_9, 0.4_8_5_0_6] )
assert np.abs(image_slice - expected_slice ).max() < 7e-3
| 95 | 0 |
"""simple docstring"""
import requests
from bsa import BeautifulSoup
def __UpperCAmelCase ( lowercase ,lowercase ):
"""simple docstring"""
_UpperCAmelCase = BeautifulSoup(requests.get(UpperCAmelCase_ ,params=UpperCAmelCase_ ).content ,"""html.parser""" )
_UpperCAmelCase = soup.find("""div""" ,attrs={"""class""": """gs_ri"""} )
_UpperCAmelCase = div.find("""div""" ,attrs={"""class""": """gs_fl"""} ).find_all("""a""" )
return anchors[2].get_text()
if __name__ == "__main__":
UpperCAmelCase__ = {
"""title""": (
"""Precisely geometry controlled microsupercapacitors for ultrahigh areal """
"""capacitance, volumetric capacitance, and energy density"""
),
"""journal""": """Chem. Mater.""",
"""volume""": 3_0,
"""pages""": """3979-3990""",
"""year""": 2_0_1_8,
"""hl""": """en""",
}
print(get_citation("""https://scholar.google.com/scholar_lookup""", params=params))
| 277 |
"""simple docstring"""
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import logging
if TYPE_CHECKING:
from ...processing_utils import ProcessorMixin
from ...utils import TensorType
UpperCamelCase = logging.get_logger(__name__)
UpperCamelCase = {
"""microsoft/layoutlmv3-base""": """https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json""",
}
class UpperCamelCase__ ( _lowerCAmelCase ):
"""simple docstring"""
A__ : int = "layoutlmv3"
def __init__( self , SCREAMING_SNAKE_CASE__=50265 , SCREAMING_SNAKE_CASE__=768 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=3072 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=512 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=0.0_2 , SCREAMING_SNAKE_CASE__=1e-5 , SCREAMING_SNAKE_CASE__=1 , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=1024 , SCREAMING_SNAKE_CASE__=128 , SCREAMING_SNAKE_CASE__=128 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=32 , SCREAMING_SNAKE_CASE__=128 , SCREAMING_SNAKE_CASE__=64 , SCREAMING_SNAKE_CASE__=256 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=224 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=None , **SCREAMING_SNAKE_CASE__ , ) -> Any:
super().__init__(
vocab_size=SCREAMING_SNAKE_CASE__ , hidden_size=SCREAMING_SNAKE_CASE__ , num_hidden_layers=SCREAMING_SNAKE_CASE__ , num_attention_heads=SCREAMING_SNAKE_CASE__ , intermediate_size=SCREAMING_SNAKE_CASE__ , hidden_act=SCREAMING_SNAKE_CASE__ , hidden_dropout_prob=SCREAMING_SNAKE_CASE__ , attention_probs_dropout_prob=SCREAMING_SNAKE_CASE__ , max_position_embeddings=SCREAMING_SNAKE_CASE__ , type_vocab_size=SCREAMING_SNAKE_CASE__ , initializer_range=SCREAMING_SNAKE_CASE__ , layer_norm_eps=SCREAMING_SNAKE_CASE__ , pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
A__ = max_ad_position_embeddings
A__ = coordinate_size
A__ = shape_size
A__ = has_relative_attention_bias
A__ = rel_pos_bins
A__ = max_rel_pos
A__ = has_spatial_attention_bias
A__ = rel_ad_pos_bins
A__ = max_rel_ad_pos
A__ = text_embed
A__ = visual_embed
A__ = input_size
A__ = num_channels
A__ = patch_size
A__ = classifier_dropout
class UpperCamelCase__ ( _lowerCAmelCase ):
"""simple docstring"""
A__ : Union[str, Any] = version.parse("1.12" )
@property
def snake_case__ ( self ) -> Mapping[str, Mapping[int, str]]:
# The order of inputs is different for question answering and sequence classification
if self.task in ["question-answering", "sequence-classification"]:
return OrderedDict(
[
("input_ids", {0: "batch", 1: "sequence"}),
("attention_mask", {0: "batch", 1: "sequence"}),
("bbox", {0: "batch", 1: "sequence"}),
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
] )
else:
return OrderedDict(
[
("input_ids", {0: "batch", 1: "sequence"}),
("bbox", {0: "batch", 1: "sequence"}),
("attention_mask", {0: "batch", 1: "sequence"}),
("pixel_values", {0: "batch", 1: "num_channels"}),
] )
@property
def snake_case__ ( self ) -> float:
return 1e-5
@property
def snake_case__ ( self ) -> int:
return 12
def snake_case__ ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = -1 , SCREAMING_SNAKE_CASE__ = -1 , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 3 , SCREAMING_SNAKE_CASE__ = 40 , SCREAMING_SNAKE_CASE__ = 40 , ) -> Mapping[str, Any]:
setattr(processor.image_processor , "apply_ocr" , SCREAMING_SNAKE_CASE__ )
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
A__ = compute_effective_axis_dimension(
SCREAMING_SNAKE_CASE__ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 )
# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
A__ = processor.tokenizer.num_special_tokens_to_add(SCREAMING_SNAKE_CASE__ )
A__ = compute_effective_axis_dimension(
SCREAMING_SNAKE_CASE__ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=SCREAMING_SNAKE_CASE__ )
# Generate dummy inputs according to compute batch and sequence
A__ = [[" ".join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size
# Generate dummy bounding boxes
A__ = [[[48, 84, 73, 128]]] * batch_size
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
# batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch)
A__ = self._generate_dummy_images(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
A__ = dict(
processor(
SCREAMING_SNAKE_CASE__ , text=SCREAMING_SNAKE_CASE__ , boxes=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , ) )
return inputs
| 104 | 0 |
"""simple docstring"""
import os
def lowerCamelCase_ ( ):
with open(os.path.dirname(_lowerCamelCase ) + '/p022_names.txt' ) as file:
lowerCamelCase__ : Union[str, Any] = str(file.readlines()[0] )
lowerCamelCase__ : int = names.replace('"' , '' ).split(',' )
names.sort()
lowerCamelCase__ : Tuple = 0
lowerCamelCase__ : str = 0
for i, name in enumerate(_lowerCamelCase ):
for letter in name:
name_score += ord(_lowerCamelCase ) - 64
total_score += (i + 1) * name_score
lowerCamelCase__ : Dict = 0
return total_score
if __name__ == "__main__":
print(solution())
| 696 |
"""simple docstring"""
import unittest
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory
from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline
from transformers.convert_graph_to_onnx import (
convert,
ensure_valid_input,
generate_identified_filename,
infer_shapes,
quantize,
)
from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow
class a_ :
'''simple docstring'''
def a__ (self, lowerCamelCase_, lowerCamelCase_, lowerCamelCase_ ):
'''simple docstring'''
return None
class a_ :
'''simple docstring'''
def a__ (self, lowerCamelCase_, lowerCamelCase_, lowerCamelCase_, lowerCamelCase_ ):
'''simple docstring'''
return None
class a_ ( unittest.TestCase ):
'''simple docstring'''
lowerCamelCase__ : Optional[Any] = [
# (model_name, model_kwargs)
('bert-base-cased', {}),
('gpt2', {'use_cache': False}), # We don't support exporting GPT2 past keys anymore
]
@require_tf
@slow
def a__ (self ):
'''simple docstring'''
for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
self._test_export(lowerCamelCase_, 'tf', 1_2, **lowerCamelCase_ )
@require_torch
@slow
def a__ (self ):
'''simple docstring'''
for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
self._test_export(lowerCamelCase_, 'pt', 1_2, **lowerCamelCase_ )
@require_torch
@slow
def a__ (self ):
'''simple docstring'''
from transformers import BertModel
lowerCamelCase__ : Union[str, Any] = ['[UNK]', '[SEP]', '[CLS]', '[PAD]', '[MASK]', 'some', 'other', 'words']
with NamedTemporaryFile(mode='w+t' ) as vocab_file:
vocab_file.write('\n'.join(lowerCamelCase_ ) )
vocab_file.flush()
lowerCamelCase__ : Tuple = BertTokenizerFast(vocab_file.name )
with TemporaryDirectory() as bert_save_dir:
lowerCamelCase__ : Optional[Any] = BertModel(BertConfig(vocab_size=len(lowerCamelCase_ ) ) )
model.save_pretrained(lowerCamelCase_ )
self._test_export(lowerCamelCase_, 'pt', 1_2, lowerCamelCase_ )
@require_tf
@slow
def a__ (self ):
'''simple docstring'''
for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
lowerCamelCase__ : Optional[Any] = self._test_export(lowerCamelCase_, 'tf', 1_2, **lowerCamelCase_ )
lowerCamelCase__ : Any = quantize(Path(lowerCamelCase_ ) )
# Ensure the actual quantized model is not bigger than the original one
if quantized_path.stat().st_size >= Path(lowerCamelCase_ ).stat().st_size:
self.fail('Quantized model is bigger than initial ONNX model' )
@require_torch
@slow
def a__ (self ):
'''simple docstring'''
for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
lowerCamelCase__ : Any = self._test_export(lowerCamelCase_, 'pt', 1_2, **lowerCamelCase_ )
lowerCamelCase__ : Optional[Any] = quantize(lowerCamelCase_ )
# Ensure the actual quantized model is not bigger than the original one
if quantized_path.stat().st_size >= Path(lowerCamelCase_ ).stat().st_size:
self.fail('Quantized model is bigger than initial ONNX model' )
def a__ (self, lowerCamelCase_, lowerCamelCase_, lowerCamelCase_, lowerCamelCase_=None, **lowerCamelCase_ ):
'''simple docstring'''
try:
# Compute path
with TemporaryDirectory() as tempdir:
lowerCamelCase__ : str = Path(lowerCamelCase_ ).joinpath('model.onnx' )
# Remove folder if exists
if path.parent.exists():
path.parent.rmdir()
# Export
convert(lowerCamelCase_, lowerCamelCase_, lowerCamelCase_, lowerCamelCase_, lowerCamelCase_, **lowerCamelCase_ )
return path
except Exception as e:
self.fail(lowerCamelCase_ )
@require_torch
@require_tokenizers
@slow
def a__ (self ):
'''simple docstring'''
from transformers import BertModel
lowerCamelCase__ : str = BertModel(BertConfig.from_pretrained('lysandre/tiny-bert-random' ) )
lowerCamelCase__ : Union[str, Any] = BertTokenizerFast.from_pretrained('lysandre/tiny-bert-random' )
self._test_infer_dynamic_axis(lowerCamelCase_, lowerCamelCase_, 'pt' )
@require_tf
@require_tokenizers
@slow
def a__ (self ):
'''simple docstring'''
from transformers import TFBertModel
lowerCamelCase__ : Dict = TFBertModel(BertConfig.from_pretrained('lysandre/tiny-bert-random' ) )
lowerCamelCase__ : Optional[int] = BertTokenizerFast.from_pretrained('lysandre/tiny-bert-random' )
self._test_infer_dynamic_axis(lowerCamelCase_, lowerCamelCase_, 'tf' )
def a__ (self, lowerCamelCase_, lowerCamelCase_, lowerCamelCase_ ):
'''simple docstring'''
lowerCamelCase__ : Dict = FeatureExtractionPipeline(lowerCamelCase_, lowerCamelCase_ )
lowerCamelCase__ : Optional[int] = ['input_ids', 'token_type_ids', 'attention_mask', 'output_0', 'output_1']
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : str = infer_shapes(lowerCamelCase_, lowerCamelCase_ )
# Assert all variables are present
self.assertEqual(len(lowerCamelCase_ ), len(lowerCamelCase_ ) )
self.assertTrue(all(var_name in shapes for var_name in variable_names ) )
self.assertSequenceEqual(variable_names[:3], lowerCamelCase_ )
self.assertSequenceEqual(variable_names[3:], lowerCamelCase_ )
# Assert inputs are {0: batch, 1: sequence}
for var_name in ["input_ids", "token_type_ids", "attention_mask"]:
self.assertDictEqual(shapes[var_name], {0: 'batch', 1: 'sequence'} )
# Assert outputs are {0: batch, 1: sequence} and {0: batch}
self.assertDictEqual(shapes['output_0'], {0: 'batch', 1: 'sequence'} )
self.assertDictEqual(shapes['output_1'], {0: 'batch'} )
def a__ (self ):
'''simple docstring'''
lowerCamelCase__ : List[Any] = ['input_ids', 'attention_mask', 'token_type_ids']
lowerCamelCase__ : Optional[int] = {'input_ids': [1, 2, 3, 4], 'attention_mask': [0, 0, 0, 0], 'token_type_ids': [1, 1, 1, 1]}
lowerCamelCase__ , lowerCamelCase__ : str = ensure_valid_input(FuncContiguousArgs(), lowerCamelCase_, lowerCamelCase_ )
# Should have exactly the same number of args (all are valid)
self.assertEqual(len(lowerCamelCase_ ), 3 )
# Should have exactly the same input names
self.assertEqual(set(lowerCamelCase_ ), set(lowerCamelCase_ ) )
# Parameter should be reordered according to their respective place in the function:
# (input_ids, token_type_ids, attention_mask)
self.assertEqual(lowerCamelCase_, (tokens['input_ids'], tokens['token_type_ids'], tokens['attention_mask']) )
# Generated args are interleaved with another args (for instance parameter "past" in GPT2)
lowerCamelCase__ , lowerCamelCase__ : Any = ensure_valid_input(FuncNonContiguousArgs(), lowerCamelCase_, lowerCamelCase_ )
# Should have exactly the one arg (all before the one not provided "some_other_args")
self.assertEqual(len(lowerCamelCase_ ), 1 )
self.assertEqual(len(lowerCamelCase_ ), 1 )
# Should have only "input_ids"
self.assertEqual(inputs_args[0], tokens['input_ids'] )
self.assertEqual(ordered_input_names[0], 'input_ids' )
def a__ (self ):
'''simple docstring'''
lowerCamelCase__ : Tuple = generate_identified_filename(Path('/home/something/my_fake_model.onnx' ), '-test' )
self.assertEqual('/home/something/my_fake_model-test.onnx', generated.as_posix() )
| 696 | 1 |
"""simple docstring"""
from .integrations import (
is_optuna_available,
is_ray_available,
is_sigopt_available,
is_wandb_available,
run_hp_search_optuna,
run_hp_search_ray,
run_hp_search_sigopt,
run_hp_search_wandb,
)
from .trainer_utils import (
HPSearchBackend,
default_hp_space_optuna,
default_hp_space_ray,
default_hp_space_sigopt,
default_hp_space_wandb,
)
from .utils import logging
_a : Union[str, Any] = logging.get_logger(__name__)
class __A :
_UpperCamelCase : Dict = 42
_UpperCamelCase : Dict = None
@staticmethod
def __A ( ):
raise NotImplementedError
def __A ( self , a__ , a__ , a__ , **a__ ):
raise NotImplementedError
def __A ( self , a__ ):
raise NotImplementedError
def __A ( self ):
if not self.is_available():
raise RuntimeError(
F"You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}." )
@classmethod
def __A ( cls ):
return F"`pip install {cls.pip_package or cls.name}`"
class __A ( SCREAMING_SNAKE_CASE_ ):
_UpperCamelCase : List[str] = "optuna"
@staticmethod
def __A ( ):
return is_optuna_available()
def __A ( self , a__ , a__ , a__ , **a__ ):
return run_hp_search_optuna(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , **_lowerCAmelCase )
def __A ( self , a__ ):
return default_hp_space_optuna(_lowerCAmelCase )
class __A ( SCREAMING_SNAKE_CASE_ ):
_UpperCamelCase : Union[str, Any] = "ray"
_UpperCamelCase : str = "\'ray[tune]\'"
@staticmethod
def __A ( ):
return is_ray_available()
def __A ( self , a__ , a__ , a__ , **a__ ):
return run_hp_search_ray(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , **_lowerCAmelCase )
def __A ( self , a__ ):
return default_hp_space_ray(_lowerCAmelCase )
class __A ( SCREAMING_SNAKE_CASE_ ):
_UpperCamelCase : int = "sigopt"
@staticmethod
def __A ( ):
return is_sigopt_available()
def __A ( self , a__ , a__ , a__ , **a__ ):
return run_hp_search_sigopt(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , **_lowerCAmelCase )
def __A ( self , a__ ):
return default_hp_space_sigopt(_lowerCAmelCase )
class __A ( SCREAMING_SNAKE_CASE_ ):
_UpperCamelCase : Optional[Any] = "wandb"
@staticmethod
def __A ( ):
return is_wandb_available()
def __A ( self , a__ , a__ , a__ , **a__ ):
return run_hp_search_wandb(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , **_lowerCAmelCase )
def __A ( self , a__ ):
return default_hp_space_wandb(_lowerCAmelCase )
_a : Union[str, Any] = {
HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend]
}
def SCREAMING_SNAKE_CASE ( ) -> str:
_lowerCAmelCase : Optional[int] = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()]
if len(lowerCAmelCase_ ) > 0:
_lowerCAmelCase : Tuple = available_backends[0].name
if len(lowerCAmelCase_ ) > 1:
logger.info(
f"{len(lowerCAmelCase_ )} hyperparameter search backends available. Using {name} as the default." )
return name
raise RuntimeError(
"""No hyperparameter search backend available.\n"""
+ """\n""".join(
f" - To install {backend.name} run {backend.pip_install()}"
for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
| 213 |
import functools
import operator
from ...configuration_utils import PretrainedConfig
from ...utils import logging
SCREAMING_SNAKE_CASE :List[str] = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE :Dict = {
'''facebook/wav2vec2-base-960h''': '''https://huggingface.co/facebook/wav2vec2-base-960h/resolve/main/config.json''',
# See all Wav2Vec2 models at https://huggingface.co/models?filter=wav2vec2
}
class __lowerCAmelCase ( a ):
"""simple docstring"""
_SCREAMING_SNAKE_CASE = 'wav2vec2'
def __init__( self : Any , _lowerCAmelCase : Optional[Any]=3_2 , _lowerCAmelCase : List[Any]=7_6_8 , _lowerCAmelCase : Dict=1_2 , _lowerCAmelCase : Tuple=1_2 , _lowerCAmelCase : Optional[int]=3_0_7_2 , _lowerCAmelCase : Any="gelu" , _lowerCAmelCase : List[str]=0.1 , _lowerCAmelCase : Dict=0.1 , _lowerCAmelCase : Union[str, Any]=0.1 , _lowerCAmelCase : Dict=0.0 , _lowerCAmelCase : Optional[int]=0.0 , _lowerCAmelCase : List[Any]=0.1 , _lowerCAmelCase : List[Any]=0.1 , _lowerCAmelCase : Dict=0.02 , _lowerCAmelCase : Any=1e-5 , _lowerCAmelCase : Any="group" , _lowerCAmelCase : Union[str, Any]="gelu" , _lowerCAmelCase : str=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , _lowerCAmelCase : Optional[Any]=(5, 2, 2, 2, 2, 2, 2) , _lowerCAmelCase : Optional[Any]=(1_0, 3, 3, 3, 3, 2, 2) , _lowerCAmelCase : int=False , _lowerCAmelCase : int=1_2_8 , _lowerCAmelCase : Union[str, Any]=1_6 , _lowerCAmelCase : Union[str, Any]=False , _lowerCAmelCase : List[Any]=True , _lowerCAmelCase : Dict=0.05 , _lowerCAmelCase : List[str]=1_0 , _lowerCAmelCase : Tuple=2 , _lowerCAmelCase : str=0.0 , _lowerCAmelCase : Union[str, Any]=1_0 , _lowerCAmelCase : int=0 , _lowerCAmelCase : Optional[int]=3_2_0 , _lowerCAmelCase : Optional[Any]=2 , _lowerCAmelCase : str=0.1 , _lowerCAmelCase : Optional[Any]=1_0_0 , _lowerCAmelCase : Tuple=2_5_6 , _lowerCAmelCase : Union[str, Any]=2_5_6 , _lowerCAmelCase : Union[str, Any]=0.1 , _lowerCAmelCase : Optional[Any]="sum" , _lowerCAmelCase : List[str]=False , _lowerCAmelCase : List[Any]=False , _lowerCAmelCase : List[str]=2_5_6 , _lowerCAmelCase : List[Any]=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 1_5_0_0) , _lowerCAmelCase : List[str]=(5, 3, 3, 1, 1) , _lowerCAmelCase : Union[str, Any]=(1, 2, 3, 1, 1) , _lowerCAmelCase : Optional[Any]=5_1_2 , _lowerCAmelCase : Any=0 , _lowerCAmelCase : Optional[int]=1 , _lowerCAmelCase : List[str]=2 , _lowerCAmelCase : Tuple=False , _lowerCAmelCase : Any=3 , _lowerCAmelCase : List[Any]=2 , _lowerCAmelCase : Optional[Any]=3 , _lowerCAmelCase : List[str]=None , _lowerCAmelCase : str=None , **_lowerCAmelCase : Tuple , ) -> Optional[int]:
"""simple docstring"""
super().__init__(**_lowerCAmelCase , pad_token_id=_lowerCAmelCase , bos_token_id=_lowerCAmelCase , eos_token_id=_lowerCAmelCase )
snake_case_ = hidden_size
snake_case_ = feat_extract_norm
snake_case_ = feat_extract_activation
snake_case_ = list(_lowerCAmelCase )
snake_case_ = list(_lowerCAmelCase )
snake_case_ = list(_lowerCAmelCase )
snake_case_ = conv_bias
snake_case_ = num_conv_pos_embeddings
snake_case_ = num_conv_pos_embedding_groups
snake_case_ = len(self.conv_dim )
snake_case_ = num_hidden_layers
snake_case_ = intermediate_size
snake_case_ = hidden_act
snake_case_ = num_attention_heads
snake_case_ = hidden_dropout
snake_case_ = attention_dropout
snake_case_ = activation_dropout
snake_case_ = feat_proj_dropout
snake_case_ = final_dropout
snake_case_ = layerdrop
snake_case_ = layer_norm_eps
snake_case_ = initializer_range
snake_case_ = vocab_size
snake_case_ = do_stable_layer_norm
snake_case_ = use_weighted_layer_sum
if (
(len(self.conv_stride ) != self.num_feat_extract_layers)
or (len(self.conv_kernel ) != self.num_feat_extract_layers)
or (len(self.conv_dim ) != self.num_feat_extract_layers)
):
raise ValueError(
"Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
" `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
F''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,'''
F''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' )
# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
snake_case_ = apply_spec_augment
snake_case_ = mask_time_prob
snake_case_ = mask_time_length
snake_case_ = mask_time_min_masks
snake_case_ = mask_feature_prob
snake_case_ = mask_feature_length
snake_case_ = mask_feature_min_masks
# parameters for pretraining with codevector quantized representations
snake_case_ = num_codevectors_per_group
snake_case_ = num_codevector_groups
snake_case_ = contrastive_logits_temperature
snake_case_ = feat_quantizer_dropout
snake_case_ = num_negatives
snake_case_ = codevector_dim
snake_case_ = proj_codevector_dim
snake_case_ = diversity_loss_weight
# ctc loss
snake_case_ = ctc_loss_reduction
snake_case_ = ctc_zero_infinity
# adapter
snake_case_ = add_adapter
snake_case_ = adapter_kernel_size
snake_case_ = adapter_stride
snake_case_ = num_adapter_layers
snake_case_ = output_hidden_size or hidden_size
snake_case_ = adapter_attn_dim
# SequenceClassification-specific parameter. Feel free to ignore for other classes.
snake_case_ = classifier_proj_size
# XVector-specific parameters. Feel free to ignore for other classes.
snake_case_ = list(_lowerCAmelCase )
snake_case_ = list(_lowerCAmelCase )
snake_case_ = list(_lowerCAmelCase )
snake_case_ = xvector_output_dim
@property
def lowerCAmelCase__ ( self : str ) -> int:
"""simple docstring"""
return functools.reduce(operator.mul , self.conv_stride , 1 )
| 283 | 0 |
def A_ ( __UpperCamelCase : float , __UpperCamelCase : float ):
if density <= 0:
raise ValueError('''Impossible fluid density''' )
if bulk_modulus <= 0:
raise ValueError('''Impossible bulk modulus''' )
return (bulk_modulus / density) ** 0.5
if __name__ == "__main__":
import doctest
doctest.testmod() | 715 |
"""simple docstring"""
import os
def A_ ( __UpperCamelCase : str = "input.txt" ):
with open(os.path.join(os.path.dirname(__UpperCamelCase ) , __UpperCamelCase ) ) as input_file:
lowercase = [
[int(__UpperCamelCase ) for element in line.split(''',''' )]
for line in input_file.readlines()
]
lowercase = len(__UpperCamelCase )
lowercase = len(matrix[0] )
lowercase = [[-1 for _ in range(__UpperCamelCase )] for _ in range(__UpperCamelCase )]
for i in range(__UpperCamelCase ):
lowercase = matrix[i][0]
for j in range(1 , __UpperCamelCase ):
for i in range(__UpperCamelCase ):
lowercase = minimal_path_sums[i][j - 1] + matrix[i][j]
for i in range(1 , __UpperCamelCase ):
lowercase = min(
minimal_path_sums[i][j] , minimal_path_sums[i - 1][j] + matrix[i][j] )
for i in range(rows - 2 , -1 , -1 ):
lowercase = min(
minimal_path_sums[i][j] , minimal_path_sums[i + 1][j] + matrix[i][j] )
return min(minimal_path_sums_row[-1] for minimal_path_sums_row in minimal_path_sums )
if __name__ == "__main__":
print(f'''{solution() = }''') | 396 | 0 |
import os
from typing import List, Optional, Union
from ...image_processing_utils import BatchFeature
from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
from ..auto import AutoTokenizer
class __lowerCAmelCase ( UpperCAmelCase_ ):
"""simple docstring"""
A__ : int = ["image_processor", "tokenizer"]
A__ : List[str] = "BlipImageProcessor"
A__ : Union[str, Any] = "AutoTokenizer"
def __init__( self : List[Any] , _snake_case : List[str] , _snake_case : List[Any] , _snake_case : List[Any] ):
"""simple docstring"""
super().__init__(_snake_case , _snake_case )
# add QFormer tokenizer
A__ = qformer_tokenizer
def __call__( self : int , _snake_case : ImageInput = None , _snake_case : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , _snake_case : bool = True , _snake_case : Union[bool, str, PaddingStrategy] = False , _snake_case : Union[bool, str, TruncationStrategy] = None , _snake_case : Optional[int] = None , _snake_case : int = 0 , _snake_case : Optional[int] = None , _snake_case : Optional[bool] = None , _snake_case : bool = False , _snake_case : bool = False , _snake_case : bool = False , _snake_case : bool = False , _snake_case : bool = False , _snake_case : bool = True , _snake_case : Optional[Union[str, TensorType]] = None , **_snake_case : Any , ):
"""simple docstring"""
if images is None and text is None:
raise ValueError('You have to specify at least images or text.' )
A__ = BatchFeature()
if text is not None:
A__ = self.tokenizer(
text=_snake_case , add_special_tokens=_snake_case , padding=_snake_case , truncation=_snake_case , max_length=_snake_case , stride=_snake_case , pad_to_multiple_of=_snake_case , return_attention_mask=_snake_case , return_overflowing_tokens=_snake_case , return_special_tokens_mask=_snake_case , return_offsets_mapping=_snake_case , return_token_type_ids=_snake_case , return_length=_snake_case , verbose=_snake_case , return_tensors=_snake_case , **_snake_case , )
encoding.update(_snake_case )
A__ = self.qformer_tokenizer(
text=_snake_case , add_special_tokens=_snake_case , padding=_snake_case , truncation=_snake_case , max_length=_snake_case , stride=_snake_case , pad_to_multiple_of=_snake_case , return_attention_mask=_snake_case , return_overflowing_tokens=_snake_case , return_special_tokens_mask=_snake_case , return_offsets_mapping=_snake_case , return_token_type_ids=_snake_case , return_length=_snake_case , verbose=_snake_case , return_tensors=_snake_case , **_snake_case , )
A__ = qformer_text_encoding.pop('input_ids' )
A__ = qformer_text_encoding.pop('attention_mask' )
if images is not None:
A__ = self.image_processor(_snake_case , return_tensors=_snake_case )
encoding.update(_snake_case )
return encoding
def _a ( self : Optional[int] , *_snake_case : List[str] , **_snake_case : List[str] ):
"""simple docstring"""
return self.tokenizer.batch_decode(*_snake_case , **_snake_case )
def _a ( self : Any , *_snake_case : Union[str, Any] , **_snake_case : Any ):
"""simple docstring"""
return self.tokenizer.decode(*_snake_case , **_snake_case )
@property
# Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names
def _a ( self : Optional[Any] ):
"""simple docstring"""
A__ = self.tokenizer.model_input_names
A__ = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
def _a ( self : int , _snake_case : List[Any] , **_snake_case : List[Any] ):
"""simple docstring"""
if os.path.isfile(_snake_case ):
raise ValueError(F'''Provided path ({save_directory}) should be a directory, not a file''' )
os.makedirs(_snake_case , exist_ok=_snake_case )
A__ = os.path.join(_snake_case , 'qformer_tokenizer' )
self.qformer_tokenizer.save_pretrained(_snake_case )
return super().save_pretrained(_snake_case , **_snake_case )
@classmethod
def _a ( cls : int , _snake_case : Optional[Any] , **_snake_case : Optional[int] ):
"""simple docstring"""
A__ = AutoTokenizer.from_pretrained(_snake_case , subfolder='qformer_tokenizer' )
A__ = cls._get_arguments_from_pretrained(_snake_case , **_snake_case )
args.append(_snake_case )
return cls(*_snake_case )
| 9 |
def lowerCamelCase ( a_ ) -> list:
lowerCAmelCase_ = len(a_ )
for _ in range(a_ ):
for i in range(_ % 2 , arr_size - 1 , 2 ):
if arr[i + 1] < arr[i]:
lowerCAmelCase_ , lowerCAmelCase_ = arr[i + 1], arr[i]
return arr
if __name__ == "__main__":
lowerCamelCase_ = list(range(1_0, 0, -1))
print(f'''Original: {arr}. Sorted: {odd_even_transposition(arr)}''')
| 318 | 0 |
"""simple docstring"""
from ...processing_utils import ProcessorMixin
class __snake_case ( __lowerCAmelCase ):
a__ = """SpeechT5FeatureExtractor"""
a__ = """SpeechT5Tokenizer"""
def __init__( self , lowercase , lowercase) -> str:
'''simple docstring'''
super().__init__(lowercase , lowercase)
def __call__( self , *lowercase , **lowercase) -> int:
'''simple docstring'''
a__: Any = kwargs.pop('audio' , lowercase)
a__: str = kwargs.pop('text' , lowercase)
a__: List[Any] = kwargs.pop('text_target' , lowercase)
a__: Any = kwargs.pop('audio_target' , lowercase)
a__: Optional[Any] = kwargs.pop('sampling_rate' , lowercase)
if audio is not None and text is not None:
raise ValueError(
'Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?')
if audio_target is not None and text_target is not None:
raise ValueError(
'Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?')
if audio is None and audio_target is None and text is None and text_target is None:
raise ValueError(
'You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process.')
if audio is not None:
a__: str = self.feature_extractor(lowercase , *lowercase , sampling_rate=lowercase , **lowercase)
elif text is not None:
a__: Optional[int] = self.tokenizer(lowercase , **lowercase)
else:
a__: List[str] = None
if audio_target is not None:
a__: List[Any] = self.feature_extractor(audio_target=lowercase , *lowercase , sampling_rate=lowercase , **lowercase)
a__: Tuple = targets['input_values']
elif text_target is not None:
a__: Union[str, Any] = self.tokenizer(lowercase , **lowercase)
a__: Tuple = targets['input_ids']
else:
a__: Optional[Any] = None
if inputs is None:
return targets
if targets is not None:
a__: str = labels
a__: List[Any] = targets.get('attention_mask')
if decoder_attention_mask is not None:
a__: List[Any] = decoder_attention_mask
return inputs
def lowerCamelCase_ ( self , *lowercase , **lowercase) -> List[str]:
'''simple docstring'''
a__: Dict = kwargs.pop('input_values' , lowercase)
a__: Any = kwargs.pop('input_ids' , lowercase)
a__: Any = kwargs.pop('labels' , lowercase)
if input_values is not None and input_ids is not None:
raise ValueError('Cannot process both `input_values` and `input_ids` inputs.')
if input_values is None and input_ids is None and labels is None:
raise ValueError(
'You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded.')
if input_values is not None:
a__: Dict = self.feature_extractor.pad(lowercase , *lowercase , **lowercase)
elif input_ids is not None:
a__: Tuple = self.tokenizer.pad(lowercase , **lowercase)
else:
a__: Union[str, Any] = None
if labels is not None:
if "input_ids" in labels or (isinstance(lowercase , lowercase) and "input_ids" in labels[0]):
a__: Optional[Any] = self.tokenizer.pad(lowercase , **lowercase)
a__: Optional[int] = targets['input_ids']
else:
a__: List[Any] = self.feature_extractor.feature_size
a__: Dict = self.feature_extractor.num_mel_bins
a__: List[Any] = self.feature_extractor.pad(lowercase , *lowercase , **lowercase)
a__: Union[str, Any] = feature_size_hack
a__: Any = targets['input_values']
else:
a__: Optional[Any] = None
if inputs is None:
return targets
if targets is not None:
a__: List[Any] = labels
a__: Optional[Any] = targets.get('attention_mask')
if decoder_attention_mask is not None:
a__: Union[str, Any] = decoder_attention_mask
return inputs
def lowerCamelCase_ ( self , *lowercase , **lowercase) -> int:
'''simple docstring'''
return self.tokenizer.batch_decode(*lowercase , **lowercase)
def lowerCamelCase_ ( self , *lowercase , **lowercase) -> Dict:
'''simple docstring'''
return self.tokenizer.decode(*lowercase , **lowercase)
| 217 | """simple docstring"""
from __future__ import annotations
from cmath import sqrt
def __a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->tuple[complex, complex]:
if a == 0:
raise ValueError('Coefficient \'a\' must not be zero.' )
a__: Optional[Any] = b * b - 4 * a * c
a__: str = (-b + sqrt(_SCREAMING_SNAKE_CASE )) / (2 * a)
a__: Tuple = (-b - sqrt(_SCREAMING_SNAKE_CASE )) / (2 * a)
return (
root_a.real if not root_a.imag else root_a,
root_a.real if not root_a.imag else root_a,
)
def __a ( ) ->Tuple:
a__ , a__: int = quadratic_roots(a=5 , b=6 , c=1 )
print(F'The solutions are: {solutiona} and {solutiona}' )
if __name__ == "__main__":
main()
| 217 | 1 |
'''simple docstring'''
def _a ( lowerCamelCase_ ):
if isinstance(_lowerCamelCase , _lowerCamelCase ):
raise TypeError('''\'float\' object cannot be interpreted as an integer''' )
if isinstance(_lowerCamelCase , _lowerCamelCase ):
raise TypeError('''\'str\' object cannot be interpreted as an integer''' )
if num == 0:
return "0b0"
snake_case : Optional[Any] =False
if num < 0:
snake_case : Tuple =True
snake_case : str =-num
snake_case : list[int] =[]
while num > 0:
binary.insert(0 , num % 2 )
num >>= 1
if negative:
return "-0b" + "".join(str(_lowerCamelCase ) for e in binary )
return "0b" + "".join(str(_lowerCamelCase ) for e in binary )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 349 |
"""simple docstring"""
import json
import os
import unittest
from transformers import MgpstrTokenizer
from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class A_ ( _a , unittest.TestCase ):
lowerCAmelCase__ = MgpstrTokenizer
lowerCAmelCase__ = False
lowerCAmelCase__ = {}
lowerCAmelCase__ = False
def _lowercase ( self: int ):
'''simple docstring'''
super().setUp()
# fmt: off
_lowerCamelCase : List[Any] = ["[GO]", "[s]", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
# fmt: on
_lowerCamelCase : Optional[Any] = dict(zip(__lowerCAmelCase ,range(len(__lowerCAmelCase ) ) ) )
_lowerCamelCase : List[str] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["vocab_file"] )
with open(self.vocab_file ,"w" ,encoding="utf-8" ) as fp:
fp.write(json.dumps(__lowerCAmelCase ) + "\n" )
def _lowercase ( self: List[str] ,**__lowerCAmelCase: Optional[Any] ):
'''simple docstring'''
return MgpstrTokenizer.from_pretrained(self.tmpdirname ,**__lowerCAmelCase )
def _lowercase ( self: List[Any] ,__lowerCAmelCase: Union[str, Any] ):
'''simple docstring'''
_lowerCamelCase : List[Any] = "tester"
_lowerCamelCase : Optional[Any] = "tester"
return input_text, output_text
@unittest.skip("MGP-STR always lower cases letters." )
def _lowercase ( self: Any ):
'''simple docstring'''
pass
def _lowercase ( self: Tuple ):
'''simple docstring'''
_lowerCamelCase : List[str] = self.get_tokenizers(do_lower_case=__lowerCAmelCase )
for tokenizer in tokenizers:
with self.subTest(F"""{tokenizer.__class__.__name__}""" ):
_lowerCamelCase : Tuple = "[SPECIAL_TOKEN]"
tokenizer.add_special_tokens({"cls_token": special_token} )
_lowerCamelCase : Optional[Any] = tokenizer.encode([special_token] ,add_special_tokens=__lowerCAmelCase )
self.assertEqual(len(__lowerCAmelCase ) ,1 )
_lowerCamelCase : int = tokenizer.decode(__lowerCAmelCase ,skip_special_tokens=__lowerCAmelCase )
self.assertTrue(special_token not in decoded )
def _lowercase ( self: Tuple ):
'''simple docstring'''
_lowerCamelCase : List[str] = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(F"""{tokenizer.__class__.__name__}""" ):
_lowerCamelCase, _lowerCamelCase : List[Any] = self.get_input_output_texts(__lowerCAmelCase )
_lowerCamelCase : Optional[Any] = tokenizer.tokenize(__lowerCAmelCase )
_lowerCamelCase : int = tokenizer.convert_tokens_to_ids(__lowerCAmelCase )
_lowerCamelCase : List[Any] = tokenizer.encode(__lowerCAmelCase ,add_special_tokens=__lowerCAmelCase )
self.assertListEqual(__lowerCAmelCase ,__lowerCAmelCase )
_lowerCamelCase : Dict = tokenizer.convert_ids_to_tokens(__lowerCAmelCase )
self.assertNotEqual(len(__lowerCAmelCase ) ,0 )
_lowerCamelCase : Optional[int] = tokenizer.decode(__lowerCAmelCase )
self.assertIsInstance(__lowerCAmelCase ,__lowerCAmelCase )
self.assertEqual(text_a.replace(" " ,"" ) ,__lowerCAmelCase )
@unittest.skip("MGP-STR tokenizer only handles one sequence." )
def _lowercase ( self: Union[str, Any] ):
'''simple docstring'''
pass
@unittest.skip("inputs cannot be pretokenized in MgpstrTokenizer" )
def _lowercase ( self: str ):
'''simple docstring'''
pass | 46 | 0 |
from math import pow
def UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ) -> Optional[int]:
'''simple docstring'''
if current_sum == needed_sum:
# If the sum of the powers is equal to needed_sum, then we have a solution.
solutions_count += 1
return current_sum, solutions_count
_A= int(pow(_lowerCamelCase , _lowerCamelCase ) )
if current_sum + i_to_n <= needed_sum:
# If the sum of the powers is less than needed_sum, then continue adding powers.
current_sum += i_to_n
_A= backtrack(
_lowerCamelCase , _lowerCamelCase , current_number + 1 , _lowerCamelCase , _lowerCamelCase )
current_sum -= i_to_n
if i_to_n < needed_sum:
# If the power of i is less than needed_sum, then try with the next power.
_A= backtrack(
_lowerCamelCase , _lowerCamelCase , current_number + 1 , _lowerCamelCase , _lowerCamelCase )
return current_sum, solutions_count
def UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> Optional[Any]:
'''simple docstring'''
if not (1 <= needed_sum <= 10_00 and 2 <= power <= 10):
raise ValueError(
'Invalid input\n'
'needed_sum must be between 1 and 1000, power between 2 and 10.' )
return backtrack(_lowerCamelCase , _lowerCamelCase , 1 , 0 , 0 )[1] # Return the solutions_count
if __name__ == "__main__":
import doctest
doctest.testmod()
| 719 | from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCAmelCase_ = logging.get_logger(__name__)
UpperCAmelCase_ = {
'''facebook/s2t-wav2vec2-large-en-de''': (
'''https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json'''
),
# See all Speech2Text models at https://huggingface.co/models?filter=speech2text2
}
class lowerCAmelCase ( _a ):
_SCREAMING_SNAKE_CASE : Optional[Any] ="""speech_to_text_2"""
_SCREAMING_SNAKE_CASE : str =["""past_key_values"""]
_SCREAMING_SNAKE_CASE : Tuple ={"""num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model"""}
def __init__( self , lowerCAmelCase__=10000 , lowerCAmelCase__=6 , lowerCAmelCase__=2048 , lowerCAmelCase__=4 , lowerCAmelCase__=0.0 , lowerCAmelCase__=True , lowerCAmelCase__="relu" , lowerCAmelCase__=256 , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.02 , lowerCAmelCase__=2 , lowerCAmelCase__=True , lowerCAmelCase__=1 , lowerCAmelCase__=0 , lowerCAmelCase__=2 , lowerCAmelCase__=1024 , **lowerCAmelCase__ , ):
_A= vocab_size
_A= d_model
_A= decoder_ffn_dim
_A= decoder_layers
_A= decoder_attention_heads
_A= dropout
_A= attention_dropout
_A= activation_dropout
_A= activation_function
_A= init_std
_A= decoder_layerdrop
_A= use_cache
_A= decoder_layers
_A= scale_embedding # scale factor will be sqrt(d_model) if True
_A= max_target_positions
super().__init__(
pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , decoder_start_token_id=lowerCAmelCase__ , **lowerCAmelCase__ , ) | 476 | 0 |
"""simple docstring"""
import datasets
import faiss
import numpy as np
import streamlit as st
import torch
from elasticsearch import Elasticsearch
from elia_utils import (
embed_questions_for_retrieval,
make_qa_sas_model,
qa_sas_generate,
query_es_index,
query_qa_dense_index,
)
import transformers
from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer
SCREAMING_SNAKE_CASE = """bart"""
SCREAMING_SNAKE_CASE = True
@st.cache(allow_output_mutation=UpperCAmelCase_ )
def lowerCamelCase__ ( )-> Union[str, Any]:
"""simple docstring"""
if LOAD_DENSE_INDEX:
UpperCamelCase = AutoTokenizer.from_pretrained("yjernite/retribert-base-uncased" )
UpperCamelCase = AutoModel.from_pretrained("yjernite/retribert-base-uncased" ).to("cuda:0" )
UpperCamelCase = qar_model.eval()
else:
UpperCamelCase , UpperCamelCase = (None, None)
if MODEL_TYPE == "bart":
UpperCamelCase = AutoTokenizer.from_pretrained("yjernite/bart_eli5" )
UpperCamelCase = AutoModelForSeqaSeqLM.from_pretrained("yjernite/bart_eli5" ).to("cuda:0" )
UpperCamelCase = torch.load("seq2seq_models/eli5_bart_model_blm_2.pth" )
sas_model.load_state_dict(save_dict["model"] )
UpperCamelCase = sas_model.eval()
else:
UpperCamelCase , UpperCamelCase = make_qa_sas_model(
model_name="t5-small" , from_file="seq2seq_models/eli5_t5_model_1024_4.pth" , device="cuda:0" )
return (qar_tokenizer, qar_model, sas_tokenizer, sas_model)
@st.cache(allow_output_mutation=UpperCAmelCase_ )
def lowerCamelCase__ ( )-> List[Any]:
"""simple docstring"""
if LOAD_DENSE_INDEX:
UpperCamelCase = faiss.StandardGpuResources()
UpperCamelCase = datasets.load_dataset(path="wiki_snippets" , name="wiki40b_en_100_0" )["train"]
UpperCamelCase = np.memmap(
"wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat" , dtype="float32" , mode="r" , shape=(wikiaab_passages.num_rows, 1_28) , )
UpperCamelCase = faiss.IndexFlatIP(1_28 )
UpperCamelCase = faiss.index_cpu_to_gpu(UpperCAmelCase_ , 1 , UpperCAmelCase_ )
wikiaab_gpu_index_flat.add(UpperCAmelCase_ ) # TODO fix for larger GPU
else:
UpperCamelCase , UpperCamelCase = (None, None)
UpperCamelCase = Elasticsearch([{"host": "localhost", "port": "9200"}] )
return (wikiaab_passages, wikiaab_gpu_index_flat, es_client)
@st.cache(allow_output_mutation=UpperCAmelCase_ )
def lowerCamelCase__ ( )-> int:
"""simple docstring"""
UpperCamelCase = datasets.load_dataset("eli5" , name="LFQA_reddit" )
UpperCamelCase = elia["train_eli5"]
UpperCamelCase = np.memmap(
"eli5_questions_reps.dat" , dtype="float32" , mode="r" , shape=(elia_train.num_rows, 1_28) )
UpperCamelCase = faiss.IndexFlatIP(1_28 )
eli5_train_q_index.add(UpperCAmelCase_ )
return (elia_train, eli5_train_q_index)
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = load_indexes()
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = load_models()
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = load_train_data()
def lowerCamelCase__ ( UpperCAmelCase_ , UpperCAmelCase_=10 )-> Optional[int]:
"""simple docstring"""
UpperCamelCase = embed_questions_for_retrieval([question] , UpperCAmelCase_ , UpperCAmelCase_ )
UpperCamelCase , UpperCamelCase = eli5_train_q_index.search(UpperCAmelCase_ , UpperCAmelCase_ )
UpperCamelCase = [elia_train[int(UpperCAmelCase_ )] for i in I[0]]
return nn_examples
def lowerCamelCase__ ( UpperCAmelCase_ , UpperCAmelCase_="wiki40b" , UpperCAmelCase_="dense" , UpperCAmelCase_=10 )-> str:
"""simple docstring"""
if source == "none":
UpperCamelCase , UpperCamelCase = (" <P> ".join(["" for _ in range(11 )] ).strip(), [])
else:
if method == "dense":
UpperCamelCase , UpperCamelCase = query_qa_dense_index(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
else:
UpperCamelCase , UpperCamelCase = query_es_index(
UpperCAmelCase_ , UpperCAmelCase_ , index_name="english_wiki40b_snippets_100w" , n_results=UpperCAmelCase_ , )
UpperCamelCase = [
(res["article_title"], res["section_title"].strip(), res["score"], res["passage_text"]) for res in hit_lst
]
UpperCamelCase = "question: {} context: {}".format(UpperCAmelCase_ , UpperCAmelCase_ )
return question_doc, support_list
@st.cache(
hash_funcs={
torch.Tensor: (lambda UpperCAmelCase_ : None),
transformers.models.bart.tokenization_bart.BartTokenizer: (lambda UpperCAmelCase_ : None),
} )
def lowerCamelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_=64 , UpperCAmelCase_=2_56 , UpperCAmelCase_=False , UpperCAmelCase_=2 , UpperCAmelCase_=0.95 , UpperCAmelCase_=0.8 )-> Tuple:
"""simple docstring"""
with torch.no_grad():
UpperCamelCase = qa_sas_generate(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , num_answers=1 , num_beams=UpperCAmelCase_ , min_len=UpperCAmelCase_ , max_len=UpperCAmelCase_ , do_sample=UpperCAmelCase_ , temp=UpperCAmelCase_ , top_p=UpperCAmelCase_ , top_k=UpperCAmelCase_ , max_input_length=10_24 , device="cuda:0" , )[0]
return (answer, support_list)
st.title("""Long Form Question Answering with ELI5""")
# Start sidebar
SCREAMING_SNAKE_CASE = """<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>"""
SCREAMING_SNAKE_CASE = """
<html>
<head>
<style>
.img-container {
padding-left: 90px;
padding-right: 90px;
padding-top: 50px;
padding-bottom: 50px;
background-color: #f0f3f9;
}
</style>
</head>
<body>
<span class=\"img-container\"> <!-- Inline parent element -->
%s
</span>
</body>
</html>
""" % (
header_html,
)
st.sidebar.markdown(
header_full,
unsafe_allow_html=True,
)
# Long Form QA with ELI5 and Wikipedia
SCREAMING_SNAKE_CASE = """
This demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).
First, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,
a pre-processed fixed snapshot of Wikipedia.
"""
st.sidebar.markdown(description, unsafe_allow_html=True)
SCREAMING_SNAKE_CASE = [
"""Answer the question""",
"""View the retrieved document only""",
"""View the most similar ELI5 question and answer""",
"""Show me everything, please!""",
]
SCREAMING_SNAKE_CASE = st.sidebar.checkbox("""Demo options""")
if demo_options:
SCREAMING_SNAKE_CASE = st.sidebar.selectbox(
"""""",
action_list,
index=3,
)
SCREAMING_SNAKE_CASE = action_list.index(action_st)
SCREAMING_SNAKE_CASE = st.sidebar.selectbox(
"""""",
["""Show full text of passages""", """Show passage section titles"""],
index=0,
)
SCREAMING_SNAKE_CASE = show_type == """Show full text of passages"""
else:
SCREAMING_SNAKE_CASE = 3
SCREAMING_SNAKE_CASE = True
SCREAMING_SNAKE_CASE = st.sidebar.checkbox("""Retrieval options""")
if retrieval_options:
SCREAMING_SNAKE_CASE = """
### Information retriever options
The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding
trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.
The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.
"""
st.sidebar.markdown(retriever_info)
SCREAMING_SNAKE_CASE = st.sidebar.selectbox("""Which Wikipedia format should the model use?""", ["""wiki40b""", """none"""])
SCREAMING_SNAKE_CASE = st.sidebar.selectbox("""Which Wikipedia indexer should the model use?""", ["""dense""", """sparse""", """mixed"""])
else:
SCREAMING_SNAKE_CASE = """wiki40b"""
SCREAMING_SNAKE_CASE = """dense"""
SCREAMING_SNAKE_CASE = """beam"""
SCREAMING_SNAKE_CASE = 2
SCREAMING_SNAKE_CASE = 64
SCREAMING_SNAKE_CASE = 256
SCREAMING_SNAKE_CASE = None
SCREAMING_SNAKE_CASE = None
SCREAMING_SNAKE_CASE = st.sidebar.checkbox("""Generation options""")
if generate_options:
SCREAMING_SNAKE_CASE = """
### Answer generation options
The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)
weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with
**beam** search, or **sample** from the decoder's output probabilities.
"""
st.sidebar.markdown(generate_info)
SCREAMING_SNAKE_CASE = st.sidebar.selectbox("""Would you like to use beam search or sample an answer?""", ["""beam""", """sampled"""])
SCREAMING_SNAKE_CASE = st.sidebar.slider(
"""Minimum generation length""", min_value=8, max_value=256, value=64, step=8, format=None, key=None
)
SCREAMING_SNAKE_CASE = st.sidebar.slider(
"""Maximum generation length""", min_value=64, max_value=512, value=256, step=16, format=None, key=None
)
if sampled == "beam":
SCREAMING_SNAKE_CASE = st.sidebar.slider("""Beam size""", min_value=1, max_value=8, value=2, step=None, format=None, key=None)
else:
SCREAMING_SNAKE_CASE = st.sidebar.slider(
"""Nucleus sampling p""", min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None
)
SCREAMING_SNAKE_CASE = st.sidebar.slider(
"""Temperature""", min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None
)
SCREAMING_SNAKE_CASE = None
# start main text
SCREAMING_SNAKE_CASE = [
"""<MY QUESTION>""",
"""How do people make chocolate?""",
"""Why do we get a fever when we are sick?""",
"""How can different animals perceive different colors?""",
"""What is natural language processing?""",
"""What's the best way to treat a sunburn?""",
"""What exactly are vitamins ?""",
"""How does nuclear energy provide electricity?""",
"""What's the difference between viruses and bacteria?""",
"""Why are flutes classified as woodwinds when most of them are made out of metal ?""",
"""Why do people like drinking coffee even though it tastes so bad?""",
"""What happens when wine ages? How does it make the wine taste better?""",
"""If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?""",
"""How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?""",
"""How does New Zealand have so many large bird predators?""",
]
SCREAMING_SNAKE_CASE = st.selectbox(
"""What would you like to ask? ---- select <MY QUESTION> to enter a new query""",
questions_list,
index=1,
)
if question_s == "<MY QUESTION>":
SCREAMING_SNAKE_CASE = st.text_input("""Enter your question here:""", """""")
else:
SCREAMING_SNAKE_CASE = question_s
if st.button("""Show me!"""):
if action in [0, 1, 3]:
if index_type == "mixed":
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = make_support(question, source=wiki_source, method="""dense""", n_results=10)
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = make_support(question, source=wiki_source, method="""sparse""", n_results=10)
SCREAMING_SNAKE_CASE = []
for res_d, res_s in zip(support_list_dense, support_list_sparse):
if tuple(res_d) not in support_list:
support_list += [tuple(res_d)]
if tuple(res_s) not in support_list:
support_list += [tuple(res_s)]
SCREAMING_SNAKE_CASE = support_list[:10]
SCREAMING_SNAKE_CASE = """<P> """ + """ <P> """.join([res[-1] for res in support_list])
else:
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = make_support(question, source=wiki_source, method=index_type, n_results=10)
if action in [0, 3]:
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = answer_question(
question_doc,
sas_model,
sas_tokenizer,
min_len=min_len,
max_len=int(max_len),
sampling=(sampled == """sampled"""),
n_beams=n_beams,
top_p=top_p,
temp=temp,
)
st.markdown("""### The model generated answer is:""")
st.write(answer)
if action in [0, 1, 3] and wiki_source != "none":
st.markdown("""--- \n ### The model is drawing information from the following Wikipedia passages:""")
for i, res in enumerate(support_list):
SCREAMING_SNAKE_CASE = """https://en.wikipedia.org/wiki/{}""".format(res[0].replace(""" """, """_"""))
SCREAMING_SNAKE_CASE = res[1].strip()
if sec_titles == "":
SCREAMING_SNAKE_CASE = """[{}]({})""".format(res[0], wiki_url)
else:
SCREAMING_SNAKE_CASE = sec_titles.split(""" & """)
SCREAMING_SNAKE_CASE = """ & """.join(
["""[{}]({}#{})""".format(sec.strip(), wiki_url, sec.strip().replace(""" """, """_""")) for sec in sec_list]
)
st.markdown(
"""{0:02d} - **Article**: {1:<18} <br> _Section_: {2}""".format(i + 1, res[0], sections),
unsafe_allow_html=True,
)
if show_passages:
st.write(
"""> <span style=\"font-family:arial; font-size:10pt;\">""" + res[-1] + """</span>""", unsafe_allow_html=True
)
if action in [2, 3]:
SCREAMING_SNAKE_CASE = find_nearest_training(question)
SCREAMING_SNAKE_CASE = nn_train_list[0]
st.markdown(
"""--- \n ### The most similar question in the ELI5 training set was: \n\n {}""".format(train_exple["""title"""])
)
SCREAMING_SNAKE_CASE = [
"""{}. {}""".format(i + 1, """ \n""".join([line.strip() for line in ans.split("""\n""") if line.strip() != """"""]))
for i, (ans, sc) in enumerate(zip(train_exple["""answers"""]["""text"""], train_exple["""answers"""]["""score"""]))
if i == 0 or sc > 2
]
st.markdown("""##### Its answers were: \n\n {}""".format("""\n""".join(answers_st)))
SCREAMING_SNAKE_CASE = """
---
**Disclaimer**
*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.
Evaluating biases of such a model and ensuring factual generations are still very much open research problems.
Therefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*
"""
st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
| 554 |
"""simple docstring"""
import unittest
from transformers import GPTNeoXJapaneseConfig, is_torch_available
from transformers.models.gpt_neox_japanese.tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer
from transformers.testing_utils import require_torch, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseModel
class __a :
def __init__( self : Optional[int] , UpperCAmelCase_ : Any , UpperCAmelCase_ : str=13 , UpperCAmelCase_ : Optional[int]=7 , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Dict=99 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : List[Any]=5 , UpperCAmelCase_ : str=4 , UpperCAmelCase_ : Union[str, Any]=4 , UpperCAmelCase_ : Optional[int]="gelu" , UpperCAmelCase_ : Tuple=0.0 , UpperCAmelCase_ : Any=0.1 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Union[str, Any]=512 , UpperCAmelCase_ : int=16 , UpperCAmelCase_ : Optional[Any]=2 , UpperCAmelCase_ : str=0.02 , UpperCAmelCase_ : Any=3 , UpperCAmelCase_ : Any=4 , UpperCAmelCase_ : Optional[Any]=None , )-> Tuple:
"""simple docstring"""
UpperCamelCase = parent
UpperCamelCase = batch_size
UpperCamelCase = seq_length
UpperCamelCase = is_training
UpperCamelCase = use_input_mask
UpperCamelCase = use_token_type_ids
UpperCamelCase = use_labels
UpperCamelCase = vocab_size
UpperCamelCase = hidden_size
UpperCamelCase = num_hidden_layers
UpperCamelCase = num_attention_heads
UpperCamelCase = intermediate_multiple_size
UpperCamelCase = hidden_act
UpperCamelCase = hidden_dropout
UpperCamelCase = attention_dropout
UpperCamelCase = weight_tying
UpperCamelCase = max_position_embeddings
UpperCamelCase = type_vocab_size
UpperCamelCase = type_sequence_label_size
UpperCamelCase = initializer_range
UpperCamelCase = num_labels
UpperCamelCase = num_choices
UpperCamelCase = scope
def _SCREAMING_SNAKE_CASE ( self : Optional[int] )-> Union[str, Any]:
"""simple docstring"""
UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
UpperCamelCase = None
if self.use_input_mask:
UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] )
UpperCamelCase = None
if self.use_labels:
UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
UpperCamelCase = self.get_config()
return config, input_ids, input_mask, token_labels
def _SCREAMING_SNAKE_CASE ( self : Dict )-> Dict:
"""simple docstring"""
return GPTNeoXJapaneseConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_multiple_size=self.intermediate_multiple_size , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , weight_tying=self.weight_tying , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , )
def _SCREAMING_SNAKE_CASE ( self : Any )-> List[Any]:
"""simple docstring"""
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = self.prepare_config_and_inputs()
UpperCamelCase = True
return config, input_ids, input_mask, token_labels
def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[Any] )-> List[str]:
"""simple docstring"""
UpperCamelCase = GPTNeoXJapaneseModel(config=UpperCAmelCase_ )
model.to(UpperCAmelCase_ )
model.eval()
UpperCamelCase = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ )
UpperCamelCase = model(UpperCAmelCase_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def _SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] )-> List[str]:
"""simple docstring"""
UpperCamelCase = True
UpperCamelCase = GPTNeoXJapaneseModel(UpperCAmelCase_ )
model.to(UpperCAmelCase_ )
model.eval()
UpperCamelCase = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def _SCREAMING_SNAKE_CASE ( self : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] )-> Any:
"""simple docstring"""
UpperCamelCase = GPTNeoXJapaneseForCausalLM(config=UpperCAmelCase_ )
model.to(UpperCAmelCase_ )
model.eval()
UpperCamelCase = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def _SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[Any] )-> Any:
"""simple docstring"""
UpperCamelCase = True
UpperCamelCase = GPTNeoXJapaneseForCausalLM(config=UpperCAmelCase_ )
model.to(UpperCAmelCase_ )
model.eval()
# first forward pass
UpperCamelCase = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , use_cache=UpperCAmelCase_ )
UpperCamelCase = outputs.past_key_values
# create hypothetical multiple next token and extent to next_input_ids
UpperCamelCase = ids_tensor((self.batch_size, 3) , config.vocab_size )
UpperCamelCase = ids_tensor((self.batch_size, 3) , vocab_size=2 )
# append to next input_ids and
UpperCamelCase = torch.cat([input_ids, next_tokens] , dim=-1 )
UpperCamelCase = torch.cat([input_mask, next_mask] , dim=-1 )
UpperCamelCase = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , output_hidden_states=UpperCAmelCase_ )
UpperCamelCase = output_from_no_past["hidden_states"][0]
UpperCamelCase = model(
UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ , output_hidden_states=UpperCAmelCase_ , )["hidden_states"][0]
# select random slice
UpperCamelCase = ids_tensor((1,) , output_from_past.shape[-1] ).item()
UpperCamelCase = output_from_no_past[:, -3:, random_slice_idx].detach()
UpperCamelCase = output_from_past[:, :, random_slice_idx].detach()
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] )
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=1e-3 ) )
def _SCREAMING_SNAKE_CASE ( self : Optional[Any] )-> Any:
"""simple docstring"""
UpperCamelCase = self.prepare_config_and_inputs()
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = config_and_inputs
UpperCamelCase = {"input_ids": input_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class __a ( _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ):
UpperCamelCase_ : Union[str, Any] = (GPTNeoXJapaneseModel, GPTNeoXJapaneseForCausalLM) if is_torch_available() else ()
UpperCamelCase_ : Optional[int] = (GPTNeoXJapaneseForCausalLM,) if is_torch_available() else ()
UpperCamelCase_ : List[str] = (
{'''feature-extraction''': GPTNeoXJapaneseModel, '''text-generation''': GPTNeoXJapaneseForCausalLM}
if is_torch_available()
else {}
)
UpperCamelCase_ : Optional[Any] = False
UpperCamelCase_ : Tuple = False
UpperCamelCase_ : Optional[int] = False
UpperCamelCase_ : List[Any] = False
def _SCREAMING_SNAKE_CASE ( self : List[str] )-> List[str]:
"""simple docstring"""
UpperCamelCase = GPTNeoXJapaneseModelTester(self )
UpperCamelCase = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 )
def _SCREAMING_SNAKE_CASE ( self : str )-> Any:
"""simple docstring"""
self.config_tester.run_common_tests()
def _SCREAMING_SNAKE_CASE ( self : Optional[int] )-> Dict:
"""simple docstring"""
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
def _SCREAMING_SNAKE_CASE ( self : List[Any] )-> Optional[Any]:
"""simple docstring"""
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_model_as_decoder(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
def _SCREAMING_SNAKE_CASE ( self : Dict )-> List[Any]:
"""simple docstring"""
# This regression test was failing with PyTorch < 1.3
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_decoder()
UpperCamelCase = None
self.model_tester.create_and_check_model_as_decoder(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
def _SCREAMING_SNAKE_CASE ( self : List[Any] )-> List[Any]:
"""simple docstring"""
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_decoder_model_past_large_inputs(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
def _SCREAMING_SNAKE_CASE ( self : List[Any] )-> Optional[int]:
"""simple docstring"""
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_causal_lm(*UpperCAmelCase_ )
@slow
def _SCREAMING_SNAKE_CASE ( self : Dict )-> str:
"""simple docstring"""
UpperCamelCase = "abeja/gpt-neox-japanese-2.7b"
UpperCamelCase = ["データサイエンティストとは、", "100年後に必要とされる会社は、", "フルリモートの環境で働くために必要なことは、", "国境の長いトンネルを抜けると", "美味しい日本食といえば、"]
UpperCamelCase = [
"データサイエンティストとは、データを分析し、ビジネスに役立つ知見を導き出す専門家のことです。",
"100年後に必要とされる会社は、「人」が中心の会社です。",
"フルリモートの環境で働くために必要なことは、「自分の時間をコントロールする」ことです。",
"国境の長いトンネルを抜けると、そこは雪国だった。",
"美味しい日本食といえば、やっぱりお寿司ですよね。",
]
UpperCamelCase = GPTNeoXJapaneseTokenizer.from_pretrained(UpperCAmelCase_ )
UpperCamelCase = GPTNeoXJapaneseForCausalLM.from_pretrained(UpperCAmelCase_ )
UpperCamelCase = []
for prompt in prompts:
UpperCamelCase = tokenizer(UpperCAmelCase_ , return_tensors="pt" ).input_ids
UpperCamelCase = model.generate(UpperCAmelCase_ , max_length=50 )
UpperCamelCase = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ )
predicted_outputs += generated_string
self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ )
| 554 | 1 |
from __future__ import annotations
from decimal import Decimal
from numpy import array
def UpperCamelCase ( lowercase_ ) -> Any:
'''simple docstring'''
lowercase__ : Any = Decimal
# Check if the provided matrix has 2 rows and 2 columns
# since this implementation only works for 2x2 matrices
if len(lowercase_ ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2:
# Calculate the determinant of the matrix
lowercase__ : str = float(
d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) )
if determinant == 0:
raise ValueError("""This matrix has no inverse.""" )
# Creates a copy of the matrix with swapped positions of the elements
lowercase__ : str = [[0.0, 0.0], [0.0, 0.0]]
lowercase__ , lowercase__ : List[str] = matrix[1][1], matrix[0][0]
lowercase__ , lowercase__ : List[str] = -matrix[1][0], -matrix[0][1]
# Calculate the inverse of the matrix
return [
[(float(d(lowercase_ ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix
]
elif (
len(lowercase_ ) == 3
and len(matrix[0] ) == 3
and len(matrix[1] ) == 3
and len(matrix[2] ) == 3
):
# Calculate the determinant of the matrix using Sarrus rule
lowercase__ : List[Any] = float(
(
(d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] ))
+ (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] ))
+ (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] ))
)
- (
(d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] ))
+ (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] ))
+ (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] ))
) )
if determinant == 0:
raise ValueError("""This matrix has no inverse.""" )
# Creating cofactor matrix
lowercase__ : int = [
[d(0.0 ), d(0.0 ), d(0.0 )],
[d(0.0 ), d(0.0 ), d(0.0 )],
[d(0.0 ), d(0.0 ), d(0.0 )],
]
lowercase__ : int = (d(matrix[1][1] ) * d(matrix[2][2] )) - (
d(matrix[1][2] ) * d(matrix[2][1] )
)
lowercase__ : List[Any] = -(
(d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] ))
)
lowercase__ : Dict = (d(matrix[1][0] ) * d(matrix[2][1] )) - (
d(matrix[1][1] ) * d(matrix[2][0] )
)
lowercase__ : int = -(
(d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] ))
)
lowercase__ : Any = (d(matrix[0][0] ) * d(matrix[2][2] )) - (
d(matrix[0][2] ) * d(matrix[2][0] )
)
lowercase__ : int = -(
(d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] ))
)
lowercase__ : Dict = (d(matrix[0][1] ) * d(matrix[1][2] )) - (
d(matrix[0][2] ) * d(matrix[1][1] )
)
lowercase__ : str = -(
(d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] ))
)
lowercase__ : str = (d(matrix[0][0] ) * d(matrix[1][1] )) - (
d(matrix[0][1] ) * d(matrix[1][0] )
)
# Transpose the cofactor matrix (Adjoint matrix)
lowercase__ : int = array(lowercase_ )
for i in range(3 ):
for j in range(3 ):
lowercase__ : Tuple = cofactor_matrix[j][i]
# Inverse of the matrix using the formula (1/determinant) * adjoint matrix
lowercase__ : Dict = array(lowercase_ )
for i in range(3 ):
for j in range(3 ):
inverse_matrix[i][j] /= d(lowercase_ )
# Calculate the inverse of the matrix
return [[float(d(lowercase_ ) ) or 0.0 for n in row] for row in inverse_matrix]
raise ValueError("""Please provide a matrix of size 2x2 or 3x3.""" )
| 702 |
lowerCamelCase__ : str = [
[0, 1_6, 1_3, 0, 0, 0],
[0, 0, 1_0, 1_2, 0, 0],
[0, 4, 0, 0, 1_4, 0],
[0, 0, 9, 0, 0, 2_0],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0],
]
def UpperCamelCase ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> str:
'''simple docstring'''
lowercase__ : Any = [False] * len(lowercase_ )
lowercase__ : List[Any] = [s]
lowercase__ : int = True
while queue:
lowercase__ : Dict = queue.pop(0 )
for ind in range(len(graph[u] ) ):
if visited[ind] is False and graph[u][ind] > 0:
queue.append(lowercase_ )
lowercase__ : Optional[Any] = True
lowercase__ : int = u
return visited[t]
def UpperCamelCase ( lowercase_ , lowercase_ , lowercase_ ) -> int:
'''simple docstring'''
lowercase__ : Optional[int] = [-1] * (len(lowercase_ ))
lowercase__ : Optional[Any] = 0
lowercase__ : List[Any] = []
lowercase__ : Optional[Any] = [i[:] for i in graph] # Record original cut, copy.
while bfs(lowercase_ , lowercase_ , lowercase_ , lowercase_ ):
lowercase__ : Optional[int] = float("""Inf""" )
lowercase__ : Tuple = sink
while s != source:
# Find the minimum value in select path
lowercase__ : List[str] = min(lowercase_ , graph[parent[s]][s] )
lowercase__ : List[str] = parent[s]
max_flow += path_flow
lowercase__ : str = sink
while v != source:
lowercase__ : int = parent[v]
graph[u][v] -= path_flow
graph[v][u] += path_flow
lowercase__ : Union[str, Any] = parent[v]
for i in range(len(lowercase_ ) ):
for j in range(len(graph[0] ) ):
if graph[i][j] == 0 and temp[i][j] > 0:
res.append((i, j) )
return res
if __name__ == "__main__":
print(mincut(test_graph, source=0, sink=5))
| 495 | 0 |
'''simple docstring'''
import logging
import os
from .state import PartialState
class _a ( logging.LoggerAdapter ):
'''simple docstring'''
@staticmethod
def UpperCamelCase_ ( A ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : int = PartialState()
return not main_process_only or (main_process_only and state.is_main_process)
def UpperCamelCase_ ( self, A, A, *A, **A ):
'''simple docstring'''
if PartialState._shared_state == {}:
raise RuntimeError(
'You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.' )
SCREAMING_SNAKE_CASE : int = kwargs.pop('main_process_only', A )
SCREAMING_SNAKE_CASE : List[Any] = kwargs.pop('in_order', A )
if self.isEnabledFor(A ):
if self._should_log(A ):
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = self.process(A, A )
self.logger.log(A, A, *A, **A )
elif in_order:
SCREAMING_SNAKE_CASE : List[str] = PartialState()
for i in range(state.num_processes ):
if i == state.process_index:
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = self.process(A, A )
self.logger.log(A, A, *A, **A )
state.wait_for_everyone()
def lowercase__( __UpperCamelCase: str ,__UpperCamelCase: str = None ):
"""simple docstring"""
if log_level is None:
SCREAMING_SNAKE_CASE : Union[str, Any] = os.environ.get('ACCELERATE_LOG_LEVEL' ,__UpperCamelCase )
SCREAMING_SNAKE_CASE : Dict = logging.getLogger(__UpperCamelCase )
if log_level is not None:
logger.setLevel(log_level.upper() )
logger.root.setLevel(log_level.upper() )
return MultiProcessAdapter(__UpperCamelCase ,{} )
| 28 |
'''simple docstring'''
import inspect
import warnings
from typing import Any, Dict, Optional, Union
from packaging import version
def lowercase__( *__UpperCamelCase: Union[str, Any] ,__UpperCamelCase: Optional[Union[Dict, Any]] = None ,__UpperCamelCase: Dict=True ,__UpperCamelCase: List[Any]=2 ):
"""simple docstring"""
from .. import __version__
SCREAMING_SNAKE_CASE : int = take_from
SCREAMING_SNAKE_CASE : Optional[int] = ()
if not isinstance(args[0] ,__UpperCamelCase ):
SCREAMING_SNAKE_CASE : List[str] = (args,)
for attribute, version_name, message in args:
if version.parse(version.parse(__UpperCamelCase ).base_version ) >= version.parse(__UpperCamelCase ):
raise ValueError(
f"The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers'"
f" version {__version__} is >= {version_name}" )
SCREAMING_SNAKE_CASE : Tuple = None
if isinstance(__UpperCamelCase ,__UpperCamelCase ) and attribute in deprecated_kwargs:
values += (deprecated_kwargs.pop(__UpperCamelCase ),)
SCREAMING_SNAKE_CASE : Dict = f"The `{attribute}` argument is deprecated and will be removed in version {version_name}."
elif hasattr(__UpperCamelCase ,__UpperCamelCase ):
values += (getattr(__UpperCamelCase ,__UpperCamelCase ),)
SCREAMING_SNAKE_CASE : Optional[int] = f"The `{attribute}` attribute is deprecated and will be removed in version {version_name}."
elif deprecated_kwargs is None:
SCREAMING_SNAKE_CASE : Dict = f"`{attribute}` is deprecated and will be removed in version {version_name}."
if warning is not None:
SCREAMING_SNAKE_CASE : Dict = warning + ' ' if standard_warn else ''
warnings.warn(warning + message ,__UpperCamelCase ,stacklevel=__UpperCamelCase )
if isinstance(__UpperCamelCase ,__UpperCamelCase ) and len(__UpperCamelCase ) > 0:
SCREAMING_SNAKE_CASE : Union[str, Any] = inspect.getouterframes(inspect.currentframe() )[1]
SCREAMING_SNAKE_CASE : Any = call_frame.filename
SCREAMING_SNAKE_CASE : Tuple = call_frame.lineno
SCREAMING_SNAKE_CASE : Union[str, Any] = call_frame.function
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = next(iter(deprecated_kwargs.items() ) )
raise TypeError(f"{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`" )
if len(__UpperCamelCase ) == 0:
return
elif len(__UpperCamelCase ) == 1:
return values[0]
return values
| 28 | 1 |
"""simple docstring"""
from collections import Counter
from timeit import timeit
def _UpperCamelCase ( _A = "" , ) -> Tuple:
return sum(c % 2 for c in Counter(input_str.replace(""" """ , """""" ).lower() ).values() ) < 2
def _UpperCamelCase ( _A = "" ) -> List[Any]:
if len(snake_case_ ) == 0:
return True
_UpperCAmelCase = input_str.replace(""" """ , """""" ).lower()
# character_freq_dict: Stores the frequency of every character in the input string
_UpperCAmelCase = {}
for character in lower_case_input_str:
_UpperCAmelCase = character_freq_dict.get(snake_case_ , 0 ) + 1
_UpperCAmelCase = 0
for character_count in character_freq_dict.values():
if character_count % 2:
odd_char += 1
if odd_char > 1:
return False
return True
def _UpperCamelCase ( _A = "" ) -> Dict:
print("""\nFor string = """ , snake_case_ , """:""" )
print(
"""> can_string_be_rearranged_as_palindrome_counter()""" , """\tans =""" , can_string_be_rearranged_as_palindrome_counter(snake_case_ ) , """\ttime =""" , timeit(
"""z.can_string_be_rearranged_as_palindrome_counter(z.check_str)""" , setup="""import __main__ as z""" , ) , """seconds""" , )
print(
"""> can_string_be_rearranged_as_palindrome()""" , """\tans =""" , can_string_be_rearranged_as_palindrome(snake_case_ ) , """\ttime =""" , timeit(
"""z.can_string_be_rearranged_as_palindrome(z.check_str)""" , setup="""import __main__ as z""" , ) , """seconds""" , )
if __name__ == "__main__":
a : Union[str, Any] = input(
'''Enter string to determine if it can be rearranged as a palindrome or not: '''
).strip()
benchmark(check_str)
a : Any = can_string_be_rearranged_as_palindrome_counter(check_str)
print(F"{check_str} can {'' if status else 'not '}be rearranged as a palindrome") | 702 |
"""simple docstring"""
import re
import warnings
from contextlib import contextmanager
from ...processing_utils import ProcessorMixin
class a_ ( _UpperCAmelCase ):
a : Any = ['image_processor', 'tokenizer']
a : Optional[int] = 'AutoImageProcessor'
a : Any = 'AutoTokenizer'
def __init__( self : List[str] , __UpperCamelCase : List[Any]=None , __UpperCamelCase : List[str]=None , **__UpperCamelCase : List[Any] ) ->Dict:
'''simple docstring'''
_UpperCAmelCase = None
if "feature_extractor" in kwargs:
warnings.warn(
"""The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
""" instead.""" , __UpperCamelCase , )
_UpperCAmelCase = kwargs.pop("""feature_extractor""" )
_UpperCAmelCase = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError("""You need to specify an `image_processor`.""" )
if tokenizer is None:
raise ValueError("""You need to specify a `tokenizer`.""" )
super().__init__(__UpperCamelCase , __UpperCamelCase )
_UpperCAmelCase = self.image_processor
_UpperCAmelCase = False
def __call__( self : Union[str, Any] , *__UpperCamelCase : str , **__UpperCamelCase : Optional[Any] ) ->List[str]:
'''simple docstring'''
if self._in_target_context_manager:
return self.current_processor(*__UpperCamelCase , **__UpperCamelCase )
_UpperCAmelCase = kwargs.pop("""images""" , __UpperCamelCase )
_UpperCAmelCase = kwargs.pop("""text""" , __UpperCamelCase )
if len(__UpperCamelCase ) > 0:
_UpperCAmelCase = args[0]
_UpperCAmelCase = args[1:]
if images is None and text is None:
raise ValueError("""You need to specify either an `images` or `text` input to process.""" )
if images is not None:
_UpperCAmelCase = self.image_processor(__UpperCamelCase , *__UpperCamelCase , **__UpperCamelCase )
if text is not None:
_UpperCAmelCase = self.tokenizer(__UpperCamelCase , **__UpperCamelCase )
if text is None:
return inputs
elif images is None:
return encodings
else:
_UpperCAmelCase = encodings["""input_ids"""]
return inputs
def _snake_case ( self : Union[str, Any] , *__UpperCamelCase : int , **__UpperCamelCase : Tuple ) ->Tuple:
'''simple docstring'''
return self.tokenizer.batch_decode(*__UpperCamelCase , **__UpperCamelCase )
def _snake_case ( self : Tuple , *__UpperCamelCase : int , **__UpperCamelCase : Union[str, Any] ) ->int:
'''simple docstring'''
return self.tokenizer.decode(*__UpperCamelCase , **__UpperCamelCase )
@contextmanager
def _snake_case ( self : Tuple ) ->Union[str, Any]:
'''simple docstring'''
warnings.warn(
"""`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """
"""labels by using the argument `text` of the regular `__call__` method (either in the same call as """
"""your images inputs, or in a separate call.""" )
_UpperCAmelCase = True
_UpperCAmelCase = self.tokenizer
yield
_UpperCAmelCase = self.image_processor
_UpperCAmelCase = False
def _snake_case ( self : str , __UpperCamelCase : Dict , __UpperCamelCase : Optional[Any]=False , __UpperCamelCase : Union[str, Any]=None ) ->List[str]:
'''simple docstring'''
if added_vocab is None:
_UpperCAmelCase = self.tokenizer.get_added_vocab()
_UpperCAmelCase = {}
while tokens:
_UpperCAmelCase = re.search(r"""<s_(.*?)>""" , __UpperCamelCase , re.IGNORECASE )
if start_token is None:
break
_UpperCAmelCase = start_token.group(1 )
_UpperCAmelCase = re.search(rf"""</s_{key}>""" , __UpperCamelCase , re.IGNORECASE )
_UpperCAmelCase = start_token.group()
if end_token is None:
_UpperCAmelCase = tokens.replace(__UpperCamelCase , """""" )
else:
_UpperCAmelCase = end_token.group()
_UpperCAmelCase = re.escape(__UpperCamelCase )
_UpperCAmelCase = re.escape(__UpperCamelCase )
_UpperCAmelCase = re.search(f"""{start_token_escaped}(.*?){end_token_escaped}""" , __UpperCamelCase , re.IGNORECASE )
if content is not None:
_UpperCAmelCase = content.group(1 ).strip()
if r"<s_" in content and r"</s_" in content: # non-leaf node
_UpperCAmelCase = self.tokenajson(__UpperCamelCase , is_inner_value=__UpperCamelCase , added_vocab=__UpperCamelCase )
if value:
if len(__UpperCamelCase ) == 1:
_UpperCAmelCase = value[0]
_UpperCAmelCase = value
else: # leaf nodes
_UpperCAmelCase = []
for leaf in content.split(r"""<sep/>""" ):
_UpperCAmelCase = leaf.strip()
if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>":
_UpperCAmelCase = leaf[1:-2] # for categorical special tokens
output[key].append(__UpperCamelCase )
if len(output[key] ) == 1:
_UpperCAmelCase = output[key][0]
_UpperCAmelCase = tokens[tokens.find(__UpperCamelCase ) + len(__UpperCamelCase ) :].strip()
if tokens[:6] == r"<sep/>": # non-leaf nodes
return [output] + self.tokenajson(tokens[6:] , is_inner_value=__UpperCamelCase , added_vocab=__UpperCamelCase )
if len(__UpperCamelCase ):
return [output] if is_inner_value else output
else:
return [] if is_inner_value else {"text_sequence": tokens}
@property
def _snake_case ( self : Tuple ) ->Optional[int]:
'''simple docstring'''
warnings.warn(
"""`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , __UpperCamelCase , )
return self.image_processor_class
@property
def _snake_case ( self : List[str] ) ->Dict:
'''simple docstring'''
warnings.warn(
"""`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , __UpperCamelCase , )
return self.image_processor | 19 | 0 |
'''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.
from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer
from .base import PipelineTool
SCREAMING_SNAKE_CASE__ = {
"Acehnese Arabic": "ace_Arab",
"Acehnese Latin": "ace_Latn",
"Mesopotamian Arabic": "acm_Arab",
"Ta'izzi-Adeni Arabic": "acq_Arab",
"Tunisian Arabic": "aeb_Arab",
"Afrikaans": "afr_Latn",
"South Levantine Arabic": "ajp_Arab",
"Akan": "aka_Latn",
"Amharic": "amh_Ethi",
"North Levantine Arabic": "apc_Arab",
"Modern Standard Arabic": "arb_Arab",
"Modern Standard Arabic Romanized": "arb_Latn",
"Najdi Arabic": "ars_Arab",
"Moroccan Arabic": "ary_Arab",
"Egyptian Arabic": "arz_Arab",
"Assamese": "asm_Beng",
"Asturian": "ast_Latn",
"Awadhi": "awa_Deva",
"Central Aymara": "ayr_Latn",
"South Azerbaijani": "azb_Arab",
"North Azerbaijani": "azj_Latn",
"Bashkir": "bak_Cyrl",
"Bambara": "bam_Latn",
"Balinese": "ban_Latn",
"Belarusian": "bel_Cyrl",
"Bemba": "bem_Latn",
"Bengali": "ben_Beng",
"Bhojpuri": "bho_Deva",
"Banjar Arabic": "bjn_Arab",
"Banjar Latin": "bjn_Latn",
"Standard Tibetan": "bod_Tibt",
"Bosnian": "bos_Latn",
"Buginese": "bug_Latn",
"Bulgarian": "bul_Cyrl",
"Catalan": "cat_Latn",
"Cebuano": "ceb_Latn",
"Czech": "ces_Latn",
"Chokwe": "cjk_Latn",
"Central Kurdish": "ckb_Arab",
"Crimean Tatar": "crh_Latn",
"Welsh": "cym_Latn",
"Danish": "dan_Latn",
"German": "deu_Latn",
"Southwestern Dinka": "dik_Latn",
"Dyula": "dyu_Latn",
"Dzongkha": "dzo_Tibt",
"Greek": "ell_Grek",
"English": "eng_Latn",
"Esperanto": "epo_Latn",
"Estonian": "est_Latn",
"Basque": "eus_Latn",
"Ewe": "ewe_Latn",
"Faroese": "fao_Latn",
"Fijian": "fij_Latn",
"Finnish": "fin_Latn",
"Fon": "fon_Latn",
"French": "fra_Latn",
"Friulian": "fur_Latn",
"Nigerian Fulfulde": "fuv_Latn",
"Scottish Gaelic": "gla_Latn",
"Irish": "gle_Latn",
"Galician": "glg_Latn",
"Guarani": "grn_Latn",
"Gujarati": "guj_Gujr",
"Haitian Creole": "hat_Latn",
"Hausa": "hau_Latn",
"Hebrew": "heb_Hebr",
"Hindi": "hin_Deva",
"Chhattisgarhi": "hne_Deva",
"Croatian": "hrv_Latn",
"Hungarian": "hun_Latn",
"Armenian": "hye_Armn",
"Igbo": "ibo_Latn",
"Ilocano": "ilo_Latn",
"Indonesian": "ind_Latn",
"Icelandic": "isl_Latn",
"Italian": "ita_Latn",
"Javanese": "jav_Latn",
"Japanese": "jpn_Jpan",
"Kabyle": "kab_Latn",
"Jingpho": "kac_Latn",
"Kamba": "kam_Latn",
"Kannada": "kan_Knda",
"Kashmiri Arabic": "kas_Arab",
"Kashmiri Devanagari": "kas_Deva",
"Georgian": "kat_Geor",
"Central Kanuri Arabic": "knc_Arab",
"Central Kanuri Latin": "knc_Latn",
"Kazakh": "kaz_Cyrl",
"Kabiyè": "kbp_Latn",
"Kabuverdianu": "kea_Latn",
"Khmer": "khm_Khmr",
"Kikuyu": "kik_Latn",
"Kinyarwanda": "kin_Latn",
"Kyrgyz": "kir_Cyrl",
"Kimbundu": "kmb_Latn",
"Northern Kurdish": "kmr_Latn",
"Kikongo": "kon_Latn",
"Korean": "kor_Hang",
"Lao": "lao_Laoo",
"Ligurian": "lij_Latn",
"Limburgish": "lim_Latn",
"Lingala": "lin_Latn",
"Lithuanian": "lit_Latn",
"Lombard": "lmo_Latn",
"Latgalian": "ltg_Latn",
"Luxembourgish": "ltz_Latn",
"Luba-Kasai": "lua_Latn",
"Ganda": "lug_Latn",
"Luo": "luo_Latn",
"Mizo": "lus_Latn",
"Standard Latvian": "lvs_Latn",
"Magahi": "mag_Deva",
"Maithili": "mai_Deva",
"Malayalam": "mal_Mlym",
"Marathi": "mar_Deva",
"Minangkabau Arabic ": "min_Arab",
"Minangkabau Latin": "min_Latn",
"Macedonian": "mkd_Cyrl",
"Plateau Malagasy": "plt_Latn",
"Maltese": "mlt_Latn",
"Meitei Bengali": "mni_Beng",
"Halh Mongolian": "khk_Cyrl",
"Mossi": "mos_Latn",
"Maori": "mri_Latn",
"Burmese": "mya_Mymr",
"Dutch": "nld_Latn",
"Norwegian Nynorsk": "nno_Latn",
"Norwegian Bokmål": "nob_Latn",
"Nepali": "npi_Deva",
"Northern Sotho": "nso_Latn",
"Nuer": "nus_Latn",
"Nyanja": "nya_Latn",
"Occitan": "oci_Latn",
"West Central Oromo": "gaz_Latn",
"Odia": "ory_Orya",
"Pangasinan": "pag_Latn",
"Eastern Panjabi": "pan_Guru",
"Papiamento": "pap_Latn",
"Western Persian": "pes_Arab",
"Polish": "pol_Latn",
"Portuguese": "por_Latn",
"Dari": "prs_Arab",
"Southern Pashto": "pbt_Arab",
"Ayacucho Quechua": "quy_Latn",
"Romanian": "ron_Latn",
"Rundi": "run_Latn",
"Russian": "rus_Cyrl",
"Sango": "sag_Latn",
"Sanskrit": "san_Deva",
"Santali": "sat_Olck",
"Sicilian": "scn_Latn",
"Shan": "shn_Mymr",
"Sinhala": "sin_Sinh",
"Slovak": "slk_Latn",
"Slovenian": "slv_Latn",
"Samoan": "smo_Latn",
"Shona": "sna_Latn",
"Sindhi": "snd_Arab",
"Somali": "som_Latn",
"Southern Sotho": "sot_Latn",
"Spanish": "spa_Latn",
"Tosk Albanian": "als_Latn",
"Sardinian": "srd_Latn",
"Serbian": "srp_Cyrl",
"Swati": "ssw_Latn",
"Sundanese": "sun_Latn",
"Swedish": "swe_Latn",
"Swahili": "swh_Latn",
"Silesian": "szl_Latn",
"Tamil": "tam_Taml",
"Tatar": "tat_Cyrl",
"Telugu": "tel_Telu",
"Tajik": "tgk_Cyrl",
"Tagalog": "tgl_Latn",
"Thai": "tha_Thai",
"Tigrinya": "tir_Ethi",
"Tamasheq Latin": "taq_Latn",
"Tamasheq Tifinagh": "taq_Tfng",
"Tok Pisin": "tpi_Latn",
"Tswana": "tsn_Latn",
"Tsonga": "tso_Latn",
"Turkmen": "tuk_Latn",
"Tumbuka": "tum_Latn",
"Turkish": "tur_Latn",
"Twi": "twi_Latn",
"Central Atlas Tamazight": "tzm_Tfng",
"Uyghur": "uig_Arab",
"Ukrainian": "ukr_Cyrl",
"Umbundu": "umb_Latn",
"Urdu": "urd_Arab",
"Northern Uzbek": "uzn_Latn",
"Venetian": "vec_Latn",
"Vietnamese": "vie_Latn",
"Waray": "war_Latn",
"Wolof": "wol_Latn",
"Xhosa": "xho_Latn",
"Eastern Yiddish": "ydd_Hebr",
"Yoruba": "yor_Latn",
"Yue Chinese": "yue_Hant",
"Chinese Simplified": "zho_Hans",
"Chinese Traditional": "zho_Hant",
"Standard Malay": "zsm_Latn",
"Zulu": "zul_Latn",
}
class snake_case (UpperCamelCase ):
lowerCAmelCase__ :Optional[Any] = "facebook/nllb-200-distilled-600M"
lowerCAmelCase__ :str = (
"This is a tool that translates text from a language to another. It takes three inputs: `text`, which should "
"be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, "
"which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in "
"plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`."
)
lowerCAmelCase__ :List[str] = "translator"
lowerCAmelCase__ :str = AutoTokenizer
lowerCAmelCase__ :str = AutoModelForSeqaSeqLM
lowerCAmelCase__ :Union[str, Any] = LANGUAGE_CODES
lowerCAmelCase__ :Optional[Any] = ["text", "text", "text"]
lowerCAmelCase__ :Optional[int] = ["text"]
def _a ( self ,UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ) -> str:
if src_lang not in self.lang_to_code:
raise ValueError(F'''{src_lang} is not a supported language.''' )
if tgt_lang not in self.lang_to_code:
raise ValueError(F'''{tgt_lang} is not a supported language.''' )
lowercase__ = self.lang_to_code[src_lang]
lowercase__ = self.lang_to_code[tgt_lang]
return self.pre_processor._build_translation_inputs(
UpperCAmelCase_ ,return_tensors="pt" ,src_lang=UpperCAmelCase_ ,tgt_lang=UpperCAmelCase_ )
def _a ( self ,UpperCAmelCase_ ) -> str:
return self.model.generate(**UpperCAmelCase_ )
def _a ( self ,UpperCAmelCase_ ) -> int:
return self.post_processor.decode(outputs[0].tolist() ,skip_special_tokens=UpperCAmelCase_ )
| 267 |
'''simple docstring'''
def lowerCamelCase ( _snake_case : str ):
'''simple docstring'''
return " ".join(
"".join(word[::-1] ) if len(_snake_case ) > 4 else word for word in sentence.split() )
if __name__ == "__main__":
import doctest
doctest.testmod()
print(reverse_long_words("Hey wollef sroirraw"))
| 267 | 1 |
'''simple docstring'''
import torch
from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel
class _SCREAMING_SNAKE_CASE (lowercase__ ):
A__ = 'M-CLIP'
def __init__( self : List[Any] , __UpperCamelCase : int=1024 , __UpperCamelCase : Union[str, Any]=768 , **__UpperCamelCase : int ) -> Any:
"""simple docstring"""
snake_case__ : int = transformerDimSize
snake_case__ : Tuple = imageDimSize
super().__init__(**__UpperCamelCase )
class _SCREAMING_SNAKE_CASE (lowercase__ ):
A__ = MCLIPConfig
def __init__( self : Optional[int] , __UpperCamelCase : Union[str, Any] , *__UpperCamelCase : Dict , **__UpperCamelCase : Any ) -> str:
"""simple docstring"""
super().__init__(__UpperCamelCase , *__UpperCamelCase , **__UpperCamelCase )
snake_case__ : str = XLMRobertaModel(__UpperCamelCase )
snake_case__ : Optional[Any] = torch.nn.Linear(
in_features=config.transformerDimensions , out_features=config.numDims )
def lowerCAmelCase ( self : Union[str, Any] , __UpperCamelCase : List[str] , __UpperCamelCase : Union[str, Any] ) -> Tuple:
"""simple docstring"""
snake_case__ : int = self.transformer(input_ids=__UpperCamelCase , attention_mask=__UpperCamelCase )[0]
snake_case__ : List[str] = (embs * attention_mask.unsqueeze(2 )).sum(dim=1 ) / attention_mask.sum(dim=1 )[:, None]
return self.LinearTransformation(__UpperCamelCase ), embs
| 574 |
'''simple docstring'''
import functools
import logging
import os
import sys
import threading
from logging import (
CRITICAL, # NOQA
DEBUG, # NOQA
ERROR, # NOQA
FATAL, # NOQA
INFO, # NOQA
NOTSET, # NOQA
WARN, # NOQA
WARNING, # NOQA
)
from typing import Optional
import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib
_lowercase : Optional[int] =threading.Lock()
_lowercase : Optional[logging.Handler] =None
_lowercase : Any ={
"debug": logging.DEBUG,
"info": logging.INFO,
"warning": logging.WARNING,
"error": logging.ERROR,
"critical": logging.CRITICAL,
}
_lowercase : Union[str, Any] =logging.WARNING
_lowercase : List[str] =True
def __UpperCAmelCase ( ) -> int:
snake_case__ : Union[str, Any] = os.getenv('''TRANSFORMERS_VERBOSITY''' , UpperCamelCase__ )
if env_level_str:
if env_level_str in log_levels:
return log_levels[env_level_str]
else:
logging.getLogger().warning(
F'''Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, '''
F'''has to be one of: { ", ".join(log_levels.keys() ) }''' )
return _default_log_level
def __UpperCAmelCase ( ) -> str:
return __name__.split('''.''' )[0]
def __UpperCAmelCase ( ) -> logging.Logger:
return logging.getLogger(_get_library_name() )
def __UpperCAmelCase ( ) -> None:
global _default_handler
with _lock:
if _default_handler:
# This library has already configured the library root logger.
return
snake_case__ : List[Any] = logging.StreamHandler() # Set sys.stderr as stream.
snake_case__ : int = sys.stderr.flush
# Apply our default configuration to the library root logger.
snake_case__ : List[str] = _get_library_root_logger()
library_root_logger.addHandler(_default_handler )
library_root_logger.setLevel(_get_default_logging_level() )
snake_case__ : int = False
def __UpperCAmelCase ( ) -> None:
global _default_handler
with _lock:
if not _default_handler:
return
snake_case__ : Optional[Any] = _get_library_root_logger()
library_root_logger.removeHandler(_default_handler )
library_root_logger.setLevel(logging.NOTSET )
snake_case__ : List[Any] = None
def __UpperCAmelCase ( ) -> Tuple:
return log_levels
def __UpperCAmelCase ( UpperCamelCase__ :Optional[str] = None ) -> logging.Logger:
if name is None:
snake_case__ : Dict = _get_library_name()
_configure_library_root_logger()
return logging.getLogger(UpperCamelCase__ )
def __UpperCAmelCase ( ) -> int:
_configure_library_root_logger()
return _get_library_root_logger().getEffectiveLevel()
def __UpperCAmelCase ( UpperCamelCase__ :int ) -> None:
_configure_library_root_logger()
_get_library_root_logger().setLevel(UpperCamelCase__ )
def __UpperCAmelCase ( ) -> Dict:
return set_verbosity(UpperCamelCase__ )
def __UpperCAmelCase ( ) -> str:
return set_verbosity(UpperCamelCase__ )
def __UpperCAmelCase ( ) -> List[str]:
return set_verbosity(UpperCamelCase__ )
def __UpperCAmelCase ( ) -> str:
return set_verbosity(UpperCamelCase__ )
def __UpperCAmelCase ( ) -> None:
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().removeHandler(_default_handler )
def __UpperCAmelCase ( ) -> None:
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().addHandler(_default_handler )
def __UpperCAmelCase ( UpperCamelCase__ :logging.Handler ) -> None:
_configure_library_root_logger()
assert handler is not None
_get_library_root_logger().addHandler(UpperCamelCase__ )
def __UpperCAmelCase ( UpperCamelCase__ :logging.Handler ) -> None:
_configure_library_root_logger()
assert handler is not None and handler not in _get_library_root_logger().handlers
_get_library_root_logger().removeHandler(UpperCamelCase__ )
def __UpperCAmelCase ( ) -> None:
_configure_library_root_logger()
snake_case__ : str = False
def __UpperCAmelCase ( ) -> None:
_configure_library_root_logger()
snake_case__ : Optional[Any] = True
def __UpperCAmelCase ( ) -> None:
snake_case__ : str = _get_library_root_logger().handlers
for handler in handlers:
snake_case__ : Union[str, Any] = logging.Formatter('''[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s''' )
handler.setFormatter(UpperCamelCase__ )
def __UpperCAmelCase ( ) -> None:
snake_case__ : str = _get_library_root_logger().handlers
for handler in handlers:
handler.setFormatter(UpperCamelCase__ )
def __UpperCAmelCase ( self :List[str] , *UpperCamelCase__ :List[str] , **UpperCamelCase__ :Union[str, Any] ) -> Optional[Any]:
snake_case__ : List[Any] = os.getenv('''TRANSFORMERS_NO_ADVISORY_WARNINGS''' , UpperCamelCase__ )
if no_advisory_warnings:
return
self.warning(*UpperCamelCase__ , **UpperCamelCase__ )
_lowercase : Any =warning_advice
@functools.lru_cache(UpperCamelCase__ )
def __UpperCAmelCase ( self :int , *UpperCamelCase__ :Tuple , **UpperCamelCase__ :List[str] ) -> List[Any]:
self.warning(*UpperCamelCase__ , **UpperCamelCase__ )
_lowercase : List[Any] =warning_once
class _SCREAMING_SNAKE_CASE :
def __init__( self : Any , *__UpperCamelCase : str , **__UpperCamelCase : List[Any] ) -> Union[str, Any]: # pylint: disable=unused-argument
"""simple docstring"""
snake_case__ : Any = args[0] if args else None
def __iter__( self : List[Any] ) -> Any:
"""simple docstring"""
return iter(self._iterator )
def __getattr__( self : Union[str, Any] , __UpperCamelCase : Dict ) -> int:
"""simple docstring"""
def empty_fn(*__UpperCamelCase : List[Any] , **__UpperCamelCase : int ): # pylint: disable=unused-argument
return
return empty_fn
def __enter__( self : List[str] ) -> Union[str, Any]:
"""simple docstring"""
return self
def __exit__( self : Union[str, Any] , __UpperCamelCase : List[Any] , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : Dict ) -> int:
"""simple docstring"""
return
class _SCREAMING_SNAKE_CASE :
def __call__( self : Tuple , *__UpperCamelCase : str , **__UpperCamelCase : Dict ) -> Dict:
"""simple docstring"""
if _tqdm_active:
return tqdm_lib.tqdm(*__UpperCamelCase , **__UpperCamelCase )
else:
return EmptyTqdm(*__UpperCamelCase , **__UpperCamelCase )
def lowerCAmelCase ( self : List[str] , *__UpperCamelCase : Union[str, Any] , **__UpperCamelCase : Union[str, Any] ) -> Optional[Any]:
"""simple docstring"""
snake_case__ : Dict = None
if _tqdm_active:
return tqdm_lib.tqdm.set_lock(*__UpperCamelCase , **__UpperCamelCase )
def lowerCAmelCase ( self : Dict ) -> Tuple:
"""simple docstring"""
if _tqdm_active:
return tqdm_lib.tqdm.get_lock()
_lowercase : Dict =_tqdm_cls()
def __UpperCAmelCase ( ) -> bool:
global _tqdm_active
return bool(_tqdm_active )
def __UpperCAmelCase ( ) -> List[Any]:
global _tqdm_active
snake_case__ : Any = True
hf_hub_utils.enable_progress_bars()
def __UpperCAmelCase ( ) -> Any:
global _tqdm_active
snake_case__ : Any = False
hf_hub_utils.disable_progress_bars()
| 574 | 1 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__UpperCamelCase = logging.get_logger(__name__)
__UpperCamelCase = {
"edbeeching/decision-transformer-gym-hopper-medium": (
"https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json"
),
# See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer
}
class _A ( __lowercase ):
lowercase__: Any = '''decision_transformer'''
lowercase__: Union[str, Any] = ['''past_key_values''']
lowercase__: List[str] = {
'''max_position_embeddings''': '''n_positions''',
'''num_attention_heads''': '''n_head''',
'''num_hidden_layers''': '''n_layer''',
}
def __init__( self : Tuple , __magic_name__ : Optional[Any]=17 , __magic_name__ : Any=4 , __magic_name__ : Union[str, Any]=1_28 , __magic_name__ : Optional[Any]=40_96 , __magic_name__ : List[Any]=True , __magic_name__ : List[Any]=1 , __magic_name__ : Optional[Any]=10_24 , __magic_name__ : Union[str, Any]=3 , __magic_name__ : Tuple=1 , __magic_name__ : Dict=None , __magic_name__ : Tuple="relu" , __magic_name__ : List[str]=0.1 , __magic_name__ : Optional[int]=0.1 , __magic_name__ : Any=0.1 , __magic_name__ : str=1E-5 , __magic_name__ : Dict=0.02 , __magic_name__ : List[str]=True , __magic_name__ : List[str]=True , __magic_name__ : Optional[int]=5_02_56 , __magic_name__ : Optional[Any]=5_02_56 , __magic_name__ : int=False , __magic_name__ : Union[str, Any]=False , **__magic_name__ : int , ) -> int:
"""simple docstring"""
__snake_case : str = state_dim
__snake_case : Optional[Any] = act_dim
__snake_case : Dict = hidden_size
__snake_case : int = max_ep_len
__snake_case : Any = action_tanh
__snake_case : Union[str, Any] = vocab_size
__snake_case : Optional[Any] = n_positions
__snake_case : Optional[int] = n_layer
__snake_case : List[Any] = n_head
__snake_case : Tuple = n_inner
__snake_case : int = activation_function
__snake_case : List[Any] = resid_pdrop
__snake_case : Union[str, Any] = embd_pdrop
__snake_case : int = attn_pdrop
__snake_case : Optional[Any] = layer_norm_epsilon
__snake_case : Optional[Any] = initializer_range
__snake_case : str = scale_attn_weights
__snake_case : str = use_cache
__snake_case : List[Any] = scale_attn_by_inverse_layer_idx
__snake_case : Dict = reorder_and_upcast_attn
__snake_case : Any = bos_token_id
__snake_case : Dict = eos_token_id
super().__init__(bos_token_id=__magic_name__ , eos_token_id=__magic_name__ , **__magic_name__ )
| 26 |
import math
def UpperCamelCase ( _A, _A ):
"""simple docstring"""
__magic_name__ : Optional[int] = len(_A )
__magic_name__ : Tuple = int(math.floor(math.sqrt(_A ) ) )
__magic_name__ : Optional[int] = 0
while arr[min(_A, _A ) - 1] < x:
__magic_name__ : Tuple = step
step += int(math.floor(math.sqrt(_A ) ) )
if prev >= n:
return -1
while arr[prev] < x:
__magic_name__ : Union[str, Any] = prev + 1
if prev == min(_A, _A ):
return -1
if arr[prev] == x:
return prev
return -1
if __name__ == "__main__":
__magic_name__: List[Any] = input("Enter numbers separated by a comma:\n").strip()
__magic_name__: List[str] = [int(item) for item in user_input.split(",")]
__magic_name__: Optional[int] = int(input("Enter the number to be searched:\n"))
__magic_name__: str = jump_search(arr, x)
if res == -1:
print("Number not found!")
else:
print(F"""Number {x} is at index {res}""")
| 324 | 0 |
import argparse
import torch
from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert
from transformers.utils import logging
logging.set_verbosity_info()
def __UpperCAmelCase ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_) -> str:
# Initialise PyTorch model
UpperCamelCase__ : Optional[int] = BertConfig.from_json_file(lowerCamelCase_)
print(f'Building PyTorch model from configuration: {config}')
UpperCamelCase__ : str = BertForPreTraining(lowerCamelCase_)
# Load weights from tf checkpoint
load_tf_weights_in_bert(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_)
# Save pytorch-model
print(f'Save PyTorch model to {pytorch_dump_path}')
torch.save(model.state_dict() , lowerCamelCase_)
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)
| 710 |
'''simple docstring'''
from __future__ import annotations
class __lowercase :
def __init__( self : Union[str, Any] , UpperCAmelCase_ : list[list[int]]):
UpperCamelCase__ : int = TypeError(
'Matrices must be formed from a list of zero or more lists containing at '
'least one and the same number of values, each of which must be of type '
'int or float.')
if len(UpperCAmelCase_) != 0:
UpperCamelCase__ : str = len(rows[0])
if cols == 0:
raise error
for row in rows:
if len(UpperCAmelCase_) != cols:
raise error
for value in row:
if not isinstance(UpperCAmelCase_ , (int, float)):
raise error
UpperCamelCase__ : Optional[int] = rows
else:
UpperCamelCase__ : Optional[Any] = []
def __UpperCamelCase ( self : Union[str, Any]):
return [[row[i] for row in self.rows] for i in range(len(self.rows[0]))]
@property
def __UpperCamelCase ( self : Dict):
return len(self.rows)
@property
def __UpperCamelCase ( self : Tuple):
return len(self.rows[0])
@property
def __UpperCamelCase ( self : List[Any]):
return (self.num_rows, self.num_columns)
@property
def __UpperCamelCase ( self : Any):
return self.order[0] == self.order[1]
def __UpperCamelCase ( self : Any):
UpperCamelCase__ : Optional[int] = [
[0 if column_num != row_num else 1 for column_num in range(self.num_rows)]
for row_num in range(self.num_rows)
]
return Matrix(UpperCAmelCase_)
def __UpperCamelCase ( self : Dict):
if not self.is_square:
return 0
if self.order == (0, 0):
return 1
if self.order == (1, 1):
return int(self.rows[0][0])
if self.order == (2, 2):
return int(
(self.rows[0][0] * self.rows[1][1])
- (self.rows[0][1] * self.rows[1][0]))
else:
return sum(
self.rows[0][column] * self.cofactors().rows[0][column]
for column in range(self.num_columns))
def __UpperCamelCase ( self : str):
return bool(self.determinant())
def __UpperCamelCase ( self : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : int):
UpperCamelCase__ : Optional[Any] = [
[
self.rows[other_row][other_column]
for other_column in range(self.num_columns)
if other_column != column
]
for other_row in range(self.num_rows)
if other_row != row
]
return Matrix(UpperCAmelCase_).determinant()
def __UpperCamelCase ( self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : int):
if (row + column) % 2 == 0:
return self.get_minor(UpperCAmelCase_ , UpperCAmelCase_)
return -1 * self.get_minor(UpperCAmelCase_ , UpperCAmelCase_)
def __UpperCamelCase ( self : List[Any]):
return Matrix(
[
[self.get_minor(UpperCAmelCase_ , UpperCAmelCase_) for column in range(self.num_columns)]
for row in range(self.num_rows)
])
def __UpperCamelCase ( self : Optional[int]):
return Matrix(
[
[
self.minors().rows[row][column]
if (row + column) % 2 == 0
else self.minors().rows[row][column] * -1
for column in range(self.minors().num_columns)
]
for row in range(self.minors().num_rows)
])
def __UpperCamelCase ( self : Dict):
UpperCamelCase__ : Dict = [
[self.cofactors().rows[column][row] for column in range(self.num_columns)]
for row in range(self.num_rows)
]
return Matrix(UpperCAmelCase_)
def __UpperCamelCase ( self : int):
UpperCamelCase__ : List[Any] = self.determinant()
if not determinant:
raise TypeError('Only matrices with a non-zero determinant have an inverse')
return self.adjugate() * (1 / determinant)
def __repr__( self : Any):
return str(self.rows)
def __str__( self : List[Any]):
if self.num_rows == 0:
return "[]"
if self.num_rows == 1:
return "[[" + ". ".join(str(self.rows[0])) + "]]"
return (
"["
+ "\n ".join(
[
'[' + '. '.join([str(UpperCAmelCase_) for value in row]) + '.]'
for row in self.rows
])
+ "]"
)
def __UpperCamelCase ( self : Dict , UpperCAmelCase_ : list[int] , UpperCAmelCase_ : int | None = None):
UpperCamelCase__ : List[str] = TypeError('Row must be a list containing all ints and/or floats')
if not isinstance(UpperCAmelCase_ , UpperCAmelCase_):
raise type_error
for value in row:
if not isinstance(UpperCAmelCase_ , (int, float)):
raise type_error
if len(UpperCAmelCase_) != self.num_columns:
raise ValueError(
'Row must be equal in length to the other rows in the matrix')
if position is None:
self.rows.append(UpperCAmelCase_)
else:
UpperCamelCase__ : Tuple = self.rows[0:position] + [row] + self.rows[position:]
def __UpperCamelCase ( self : Tuple , UpperCAmelCase_ : list[int] , UpperCAmelCase_ : int | None = None):
UpperCamelCase__ : int = TypeError(
'Column must be a list containing all ints and/or floats')
if not isinstance(UpperCAmelCase_ , UpperCAmelCase_):
raise type_error
for value in column:
if not isinstance(UpperCAmelCase_ , (int, float)):
raise type_error
if len(UpperCAmelCase_) != self.num_rows:
raise ValueError(
'Column must be equal in length to the other columns in the matrix')
if position is None:
UpperCamelCase__ : Optional[int] = [self.rows[i] + [column[i]] for i in range(self.num_rows)]
else:
UpperCamelCase__ : str = [
self.rows[i][0:position] + [column[i]] + self.rows[i][position:]
for i in range(self.num_rows)
]
def __eq__( self : List[Any] , UpperCAmelCase_ : object):
if not isinstance(UpperCAmelCase_ , UpperCAmelCase_):
return NotImplemented
return self.rows == other.rows
def __ne__( self : Any , UpperCAmelCase_ : object):
return not self == other
def __neg__( self : Union[str, Any]):
return self * -1
def __add__( self : Optional[int] , UpperCAmelCase_ : Matrix):
if self.order != other.order:
raise ValueError('Addition requires matrices of the same order')
return Matrix(
[
[self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns)]
for i in range(self.num_rows)
])
def __sub__( self : Tuple , UpperCAmelCase_ : Matrix):
if self.order != other.order:
raise ValueError('Subtraction requires matrices of the same order')
return Matrix(
[
[self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns)]
for i in range(self.num_rows)
])
def __mul__( self : Any , UpperCAmelCase_ : Matrix | int | float):
if isinstance(UpperCAmelCase_ , (int, float)):
return Matrix(
[[int(element * other) for element in row] for row in self.rows])
elif isinstance(UpperCAmelCase_ , UpperCAmelCase_):
if self.num_columns != other.num_rows:
raise ValueError(
'The number of columns in the first matrix must '
'be equal to the number of rows in the second')
return Matrix(
[
[Matrix.dot_product(UpperCAmelCase_ , UpperCAmelCase_) for column in other.columns()]
for row in self.rows
])
else:
raise TypeError(
'A Matrix can only be multiplied by an int, float, or another matrix')
def __pow__( self : Dict , UpperCAmelCase_ : int):
if not isinstance(UpperCAmelCase_ , UpperCAmelCase_):
raise TypeError('A Matrix can only be raised to the power of an int')
if not self.is_square:
raise ValueError('Only square matrices can be raised to a power')
if other == 0:
return self.identity()
if other < 0:
if self.is_invertable():
return self.inverse() ** (-other)
raise ValueError(
'Only invertable matrices can be raised to a negative power')
UpperCamelCase__ : str = self
for _ in range(other - 1):
result *= self
return result
@classmethod
def __UpperCamelCase ( cls : Optional[int] , UpperCAmelCase_ : list[int] , UpperCAmelCase_ : list[int]):
return sum(row[i] * column[i] for i in range(len(UpperCAmelCase_)))
if __name__ == "__main__":
import doctest
doctest.testmod()
| 6 | 0 |
'''simple docstring'''
from typing import List, Optional, Union
from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class _snake_case ( a__ ):
lowerCAmelCase :Any = ['''image_processor''', '''tokenizer''']
lowerCAmelCase :Union[str, Any] = '''BlipImageProcessor'''
lowerCAmelCase :Any = ('''BertTokenizer''', '''BertTokenizerFast''')
def __init__( self , _lowerCamelCase , _lowerCamelCase):
UpperCAmelCase__ : Union[str, Any] = False
super().__init__(_lowerCamelCase , _lowerCamelCase)
UpperCAmelCase__ : Union[str, Any] = self.image_processor
def __call__( self , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = True , _lowerCamelCase = False , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = 0 , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = False , _lowerCamelCase = False , _lowerCamelCase = False , _lowerCamelCase = False , _lowerCamelCase = False , _lowerCamelCase = True , _lowerCamelCase = None , **_lowerCamelCase , ):
if images is None and text is None:
raise ValueError("""You have to specify either images or text.""")
# Get only text
if images is None:
UpperCAmelCase__ : Dict = self.tokenizer
UpperCAmelCase__ : Any = self.tokenizer(
text=_lowerCamelCase , add_special_tokens=_lowerCamelCase , padding=_lowerCamelCase , truncation=_lowerCamelCase , max_length=_lowerCamelCase , stride=_lowerCamelCase , pad_to_multiple_of=_lowerCamelCase , return_attention_mask=_lowerCamelCase , return_overflowing_tokens=_lowerCamelCase , return_special_tokens_mask=_lowerCamelCase , return_offsets_mapping=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , return_length=_lowerCamelCase , verbose=_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase , )
return text_encoding
# add pixel_values
UpperCAmelCase__ : int = self.image_processor(_lowerCamelCase , return_tensors=_lowerCamelCase)
if text is not None:
UpperCAmelCase__ : List[Any] = self.tokenizer(
text=_lowerCamelCase , add_special_tokens=_lowerCamelCase , padding=_lowerCamelCase , truncation=_lowerCamelCase , max_length=_lowerCamelCase , stride=_lowerCamelCase , pad_to_multiple_of=_lowerCamelCase , return_attention_mask=_lowerCamelCase , return_overflowing_tokens=_lowerCamelCase , return_special_tokens_mask=_lowerCamelCase , return_offsets_mapping=_lowerCamelCase , return_token_type_ids=_lowerCamelCase , return_length=_lowerCamelCase , verbose=_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase , )
else:
UpperCAmelCase__ : Tuple = None
if text_encoding is not None:
encoding_image_processor.update(_lowerCamelCase)
return encoding_image_processor
def snake_case__ ( self , *_lowerCamelCase , **_lowerCamelCase):
return self.tokenizer.batch_decode(*_lowerCamelCase , **_lowerCamelCase)
def snake_case__ ( self , *_lowerCamelCase , **_lowerCamelCase):
return self.tokenizer.decode(*_lowerCamelCase , **_lowerCamelCase)
@property
def snake_case__ ( self):
UpperCAmelCase__ : Optional[Any] = self.tokenizer.model_input_names
UpperCAmelCase__ : str = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) | 407 |
'''simple docstring'''
from typing import List, Optional, Tuple, Union
import torch
from ...models import UNetaDModel
from ...schedulers import ScoreSdeVeScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class _snake_case ( a__ ):
lowerCAmelCase :UNetaDModel
lowerCAmelCase :ScoreSdeVeScheduler
def __init__( self , _lowerCamelCase , _lowerCamelCase):
super().__init__()
self.register_modules(unet=_lowerCamelCase , scheduler=_lowerCamelCase)
@torch.no_grad()
def __call__( self , _lowerCamelCase = 1 , _lowerCamelCase = 2000 , _lowerCamelCase = None , _lowerCamelCase = "pil" , _lowerCamelCase = True , **_lowerCamelCase , ):
UpperCAmelCase__ : Union[str, Any] = self.unet.config.sample_size
UpperCAmelCase__ : Any = (batch_size, 3, img_size, img_size)
UpperCAmelCase__ : Optional[int] = self.unet
UpperCAmelCase__ : Any = randn_tensor(_lowerCamelCase , generator=_lowerCamelCase) * self.scheduler.init_noise_sigma
UpperCAmelCase__ : Optional[int] = sample.to(self.device)
self.scheduler.set_timesteps(_lowerCamelCase)
self.scheduler.set_sigmas(_lowerCamelCase)
for i, t in enumerate(self.progress_bar(self.scheduler.timesteps)):
UpperCAmelCase__ : List[str] = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device)
# correction step
for _ in range(self.scheduler.config.correct_steps):
UpperCAmelCase__ : List[str] = self.unet(_lowerCamelCase , _lowerCamelCase).sample
UpperCAmelCase__ : List[Any] = self.scheduler.step_correct(_lowerCamelCase , _lowerCamelCase , generator=_lowerCamelCase).prev_sample
# prediction step
UpperCAmelCase__ : Any = model(_lowerCamelCase , _lowerCamelCase).sample
UpperCAmelCase__ : Union[str, Any] = self.scheduler.step_pred(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , generator=_lowerCamelCase)
UpperCAmelCase__ , UpperCAmelCase__ : Optional[int] = output.prev_sample, output.prev_sample_mean
UpperCAmelCase__ : Optional[Any] = sample_mean.clamp(0 , 1)
UpperCAmelCase__ : List[str] = sample.cpu().permute(0 , 2 , 3 , 1).numpy()
if output_type == "pil":
UpperCAmelCase__ : str = self.numpy_to_pil(_lowerCamelCase)
if not return_dict:
return (sample,)
return ImagePipelineOutput(images=_lowerCamelCase) | 407 | 1 |
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
a__ = logging.get_logger(__name__)
a__ = {'''vocab_file''': '''spiece.model'''}
a__ = {
'''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
a__ = {
'''t5-small''': 512,
'''t5-base''': 512,
'''t5-large''': 512,
'''t5-3b''': 512,
'''t5-11b''': 512,
}
a__ = '''▁'''
class UpperCAmelCase_ ( __lowercase ):
"""simple docstring"""
UpperCAmelCase__ : Dict = VOCAB_FILES_NAMES
UpperCAmelCase__ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP
UpperCAmelCase__ : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
UpperCAmelCase__ : Dict = ["input_ids", "attention_mask"]
def __init__( self , _a , _a="</s>" , _a="<unk>" , _a="<pad>" , _a=1_0_0 , _a=None , _a = None , _a=True , **_a , ) -> None:
# Add extra_ids to the special token list
if extra_ids > 0 and additional_special_tokens is None:
_a : Optional[Any] = [F"""<extra_id_{i}>""" for i in range(_a )]
elif extra_ids > 0 and additional_special_tokens is not None:
# Check that we have the right number of extra_id special tokens
_a : str = len(set(filter(lambda _a : bool('''extra_id''' in str(_a ) ) , _a ) ) )
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''' )
_a : Union[str, Any] = legacy
_a : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
eos_token=_a , unk_token=_a , pad_token=_a , extra_ids=_a , additional_special_tokens=_a , sp_model_kwargs=self.sp_model_kwargs , legacy=_a , **_a , )
_a : Tuple = vocab_file
_a : List[str] = extra_ids
_a : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(_a )
@staticmethod
def __lowercase ( _a , _a , _a ) -> Union[str, Any]:
if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes:
_a : Dict = 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.''' , _a , )
return max_model_length
@property
def __lowercase ( self ) -> List[Any]:
return self.sp_model.get_piece_size() + self._extra_ids
def __lowercase ( self ) -> List[str]:
_a : List[Any] = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __lowercase ( self , _a , _a = None , _a = False ) -> List[int]:
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a )
# normal case: some special tokens
if token_ids_a is None:
return ([0] * len(_a )) + [1]
return ([0] * len(_a )) + [1] + ([0] * len(_a )) + [1]
def __lowercase ( self ) -> List[str]:
return list(
set(filter(lambda _a : bool(re.search(R'''<extra_id_\d+>''' , _a ) ) is not None , self.additional_special_tokens ) ) )
def __lowercase ( self ) -> Any:
return [self._convert_token_to_id(_a ) for token in self.get_sentinel_tokens()]
def __lowercase ( self , _a ) -> List[int]:
if len(_a ) > 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 __lowercase ( self , _a , _a = None ) -> List[int]:
_a : Optional[Any] = [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 __lowercase ( self , _a , _a = None ) -> List[int]:
_a : int = self._add_eos_if_not_present(_a )
if token_ids_a is None:
return token_ids_a
else:
_a : Dict = self._add_eos_if_not_present(_a )
return token_ids_a + token_ids_a
def __getstate__( self ) -> Tuple:
_a : str = self.__dict__.copy()
_a : Union[str, Any] = None
return state
def __setstate__( self , _a ) -> Optional[int]:
_a : List[Any] = d
# for backward compatibility
if not hasattr(self , '''sp_model_kwargs''' ):
_a : str = {}
_a : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def __lowercase ( self , _a , **_a ) -> List[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:
_a : Dict = SPIECE_UNDERLINE + text.replace(_a , ''' ''' )
return super().tokenize(_a , **_a )
def __lowercase ( self , _a , **_a ) -> List[Any]:
if not self.legacy:
_a : List[str] = text.startswith(_a )
if is_first:
_a : Optional[Any] = text[1:]
_a : List[str] = self.sp_model.encode(_a , out_type=_a )
if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_a ):
_a : Dict = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:]
return tokens
def __lowercase ( self , _a ) -> int:
if token.startswith('''<extra_id_''' ):
_a : Optional[int] = re.match(R'''<extra_id_(\d+)>''' , _a )
_a : Dict = int(match.group(1 ) )
return self.vocab_size - num - 1
return self.sp_model.piece_to_id(_a )
def __lowercase ( self , _a ) -> Tuple:
if index < self.sp_model.get_piece_size():
_a : Union[str, Any] = self.sp_model.IdToPiece(_a )
else:
_a : Optional[Any] = F"""<extra_id_{self.vocab_size - 1 - index}>"""
return token
def __lowercase ( self , _a ) -> Dict:
_a : Optional[Any] = []
_a : List[Any] = ''''''
_a : Tuple = 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(_a ) + token
_a : Any = True
_a : int = []
else:
current_sub_tokens.append(_a )
_a : Dict = False
out_string += self.sp_model.decode(_a )
return out_string.strip()
def __lowercase ( self , _a , _a = None ) -> Tuple[str]:
if not os.path.isdir(_a ):
logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" )
return
_a : Optional[int] = os.path.join(
_a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , _a )
elif not os.path.isfile(self.vocab_file ):
with open(_a , '''wb''' ) as fi:
_a : int = self.sp_model.serialized_model_proto()
fi.write(_a )
return (out_vocab_file,)
| 578 |
from __future__ import annotations
import os
import tempfile
import unittest
from transformers import ConvBertConfig, is_tf_available
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TFConvBertForMaskedLM,
TFConvBertForMultipleChoice,
TFConvBertForQuestionAnswering,
TFConvBertForSequenceClassification,
TFConvBertForTokenClassification,
TFConvBertModel,
)
class UpperCAmelCase_ :
"""simple docstring"""
def __init__( self , _a , _a=1_3 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=9_9 , _a=3_2 , _a=2 , _a=4 , _a=3_7 , _a="gelu" , _a=0.1 , _a=0.1 , _a=5_1_2 , _a=1_6 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , ) -> Optional[int]:
_a : List[str] = parent
_a : str = 1_3
_a : Union[str, Any] = 7
_a : str = True
_a : Union[str, Any] = True
_a : Tuple = True
_a : Optional[Any] = True
_a : Tuple = 9_9
_a : int = 3_8_4
_a : Union[str, Any] = 2
_a : Dict = 4
_a : List[Any] = 3_7
_a : Optional[int] = '''gelu'''
_a : Any = 0.1
_a : Tuple = 0.1
_a : Optional[Any] = 5_1_2
_a : str = 1_6
_a : List[str] = 2
_a : Union[str, Any] = 0.02
_a : Tuple = 3
_a : Optional[Any] = 4
_a : List[Any] = 1_2_8
_a : str = 2
_a : Optional[int] = 9
_a : Union[str, Any] = 1
_a : Tuple = None
def __lowercase ( self ) -> Union[str, Any]:
_a : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
_a : str = None
if self.use_input_mask:
_a : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] )
_a : Optional[int] = None
if self.use_token_type_ids:
_a : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
_a : str = None
_a : Tuple = None
_a : str = None
if self.use_labels:
_a : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size )
_a : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
_a : List[Any] = ids_tensor([self.batch_size] , self.num_choices )
_a : int = ConvBertConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=_a , )
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def __lowercase ( self , _a , _a , _a , _a , _a , _a , _a ) -> List[str]:
_a : Dict = TFConvBertModel(config=_a )
_a : List[Any] = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
_a : List[str] = [input_ids, input_mask]
_a : int = model(_a )
_a : Optional[Any] = model(_a )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def __lowercase ( self , _a , _a , _a , _a , _a , _a , _a ) -> List[str]:
_a : Any = TFConvBertForMaskedLM(config=_a )
_a : Optional[Any] = {
'''input_ids''': input_ids,
'''attention_mask''': input_mask,
'''token_type_ids''': token_type_ids,
}
_a : Any = model(_a )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def __lowercase ( self , _a , _a , _a , _a , _a , _a , _a ) -> Any:
_a : List[str] = self.num_labels
_a : Any = TFConvBertForSequenceClassification(config=_a )
_a : Dict = {
'''input_ids''': input_ids,
'''attention_mask''': input_mask,
'''token_type_ids''': token_type_ids,
}
_a : List[str] = model(_a )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def __lowercase ( self , _a , _a , _a , _a , _a , _a , _a ) -> int:
_a : int = self.num_choices
_a : str = TFConvBertForMultipleChoice(config=_a )
_a : Optional[Any] = tf.tile(tf.expand_dims(_a , 1 ) , (1, self.num_choices, 1) )
_a : Tuple = tf.tile(tf.expand_dims(_a , 1 ) , (1, self.num_choices, 1) )
_a : int = tf.tile(tf.expand_dims(_a , 1 ) , (1, self.num_choices, 1) )
_a : int = {
'''input_ids''': multiple_choice_inputs_ids,
'''attention_mask''': multiple_choice_input_mask,
'''token_type_ids''': multiple_choice_token_type_ids,
}
_a : Optional[int] = model(_a )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def __lowercase ( self , _a , _a , _a , _a , _a , _a , _a ) -> Optional[Any]:
_a : List[Any] = self.num_labels
_a : Optional[Any] = TFConvBertForTokenClassification(config=_a )
_a : int = {
'''input_ids''': input_ids,
'''attention_mask''': input_mask,
'''token_type_ids''': token_type_ids,
}
_a : str = model(_a )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def __lowercase ( self , _a , _a , _a , _a , _a , _a , _a ) -> Tuple:
_a : Optional[int] = TFConvBertForQuestionAnswering(config=_a )
_a : Optional[Any] = {
'''input_ids''': input_ids,
'''attention_mask''': input_mask,
'''token_type_ids''': token_type_ids,
}
_a : Tuple = model(_a )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def __lowercase ( self ) -> Optional[int]:
_a : Union[str, Any] = self.prepare_config_and_inputs()
(
(
_a
) , (
_a
) , (
_a
) , (
_a
) , (
_a
) , (
_a
) , (
_a
) ,
) : Optional[Any] = config_and_inputs
_a : str = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
return config, inputs_dict
@require_tf
class UpperCAmelCase_ ( __lowercase , __lowercase , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ : Tuple = (
(
TFConvBertModel,
TFConvBertForMaskedLM,
TFConvBertForQuestionAnswering,
TFConvBertForSequenceClassification,
TFConvBertForTokenClassification,
TFConvBertForMultipleChoice,
)
if is_tf_available()
else ()
)
UpperCAmelCase__ : List[Any] = (
{
"feature-extraction": TFConvBertModel,
"fill-mask": TFConvBertForMaskedLM,
"question-answering": TFConvBertForQuestionAnswering,
"text-classification": TFConvBertForSequenceClassification,
"token-classification": TFConvBertForTokenClassification,
"zero-shot": TFConvBertForSequenceClassification,
}
if is_tf_available()
else {}
)
UpperCAmelCase__ : List[str] = False
UpperCAmelCase__ : int = False
UpperCAmelCase__ : Dict = False
def __lowercase ( self ) -> List[str]:
_a : Optional[Any] = TFConvBertModelTester(self )
_a : List[str] = ConfigTester(self , config_class=_a , hidden_size=3_7 )
def __lowercase ( self ) -> str:
self.config_tester.run_common_tests()
def __lowercase ( self ) -> List[Any]:
_a : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_a )
def __lowercase ( self ) -> Tuple:
_a : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*_a )
def __lowercase ( self ) -> Tuple:
_a : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*_a )
def __lowercase ( self ) -> List[str]:
_a : int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*_a )
def __lowercase ( self ) -> Any:
_a : List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*_a )
def __lowercase ( self ) -> Dict:
_a : Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*_a )
@slow
def __lowercase ( self ) -> Union[str, Any]:
_a , _a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common()
_a : Optional[int] = True
_a : Optional[int] = True
if hasattr(_a , '''use_cache''' ):
_a : int = True
_a : Union[str, Any] = getattr(self.model_tester , '''encoder_seq_length''' , self.model_tester.seq_length )
_a : List[str] = getattr(self.model_tester , '''key_length''' , _a )
for model_class in self.all_model_classes:
_a : List[Any] = self._prepare_for_class(_a , _a )
_a : Dict = model_class(_a )
_a : Union[str, Any] = len(model(_a ) )
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(_a , saved_model=_a )
_a : Any = os.path.join(_a , '''saved_model''' , '''1''' )
_a : List[Any] = tf.keras.models.load_model(_a )
_a : Optional[int] = model(_a )
if self.is_encoder_decoder:
_a : List[Any] = outputs['''encoder_hidden_states''']
_a : Optional[Any] = outputs['''encoder_attentions''']
else:
_a : List[str] = outputs['''hidden_states''']
_a : Union[str, Any] = outputs['''attentions''']
self.assertEqual(len(_a ) , _a )
_a : Optional[int] = getattr(
self.model_tester , '''expected_num_hidden_layers''' , self.model_tester.num_hidden_layers + 1 )
self.assertEqual(len(_a ) , _a )
self.assertListEqual(
list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , )
self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers )
self.assertListEqual(
list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , )
@slow
def __lowercase ( self ) -> Union[str, Any]:
_a : Any = TFConvBertModel.from_pretrained('''YituTech/conv-bert-base''' )
self.assertIsNotNone(_a )
def __lowercase ( self ) -> Union[str, Any]:
_a , _a : List[str] = self.model_tester.prepare_config_and_inputs_for_common()
_a : List[str] = True
_a : Optional[Any] = getattr(self.model_tester , '''decoder_seq_length''' , self.model_tester.seq_length )
_a : Any = getattr(self.model_tester , '''encoder_seq_length''' , self.model_tester.seq_length )
_a : Optional[Any] = getattr(self.model_tester , '''key_length''' , _a )
_a : Optional[int] = getattr(self.model_tester , '''key_length''' , _a )
def check_decoder_attentions_output(_a ):
_a : int = len(_a )
self.assertEqual(out_len % 2 , 0 )
_a : Dict = outputs.decoder_attentions
self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers )
self.assertListEqual(
list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , )
def check_encoder_attentions_output(_a ):
_a : Optional[Any] = [
t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions)
]
self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers )
self.assertListEqual(
list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , )
for model_class in self.all_model_classes:
_a : Any = True
_a : Optional[Any] = False
_a : List[str] = model_class(_a )
_a : List[str] = model(self._prepare_for_class(_a , _a ) )
_a : List[Any] = len(_a )
self.assertEqual(config.output_hidden_states , _a )
check_encoder_attentions_output(_a )
if self.is_encoder_decoder:
_a : Union[str, Any] = model_class(_a )
_a : List[Any] = model(self._prepare_for_class(_a , _a ) )
self.assertEqual(config.output_hidden_states , _a )
check_decoder_attentions_output(_a )
# Check that output attentions can also be changed via the config
del inputs_dict["output_attentions"]
_a : Dict = True
_a : int = model_class(_a )
_a : Optional[int] = model(self._prepare_for_class(_a , _a ) )
self.assertEqual(config.output_hidden_states , _a )
check_encoder_attentions_output(_a )
# Check attention is always last and order is fine
_a : List[str] = True
_a : str = True
_a : Any = model_class(_a )
_a : Optional[Any] = model(self._prepare_for_class(_a , _a ) )
self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(_a ) )
self.assertEqual(model.config.output_hidden_states , _a )
check_encoder_attentions_output(_a )
@require_tf
class UpperCAmelCase_ ( unittest.TestCase ):
"""simple docstring"""
@slow
def __lowercase ( self ) -> str:
_a : Any = TFConvBertModel.from_pretrained('''YituTech/conv-bert-base''' )
_a : str = tf.constant([[0, 1, 2, 3, 4, 5]] )
_a : Optional[int] = model(_a )[0]
_a : Any = [1, 6, 7_6_8]
self.assertEqual(output.shape , _a )
_a : str = tf.constant(
[
[
[-0.0347_5493, -0.468_6034, -0.3063_8832],
[0.2263_7248, -0.2698_8646, -0.742_3424],
[0.1032_4868, -0.4501_3508, -0.5828_0784],
]
] )
tf.debugging.assert_near(output[:, :3, :3] , _a , atol=1e-4 )
| 578 | 1 |
import warnings
from transformers import AutoTokenizer
from transformers.utils import is_torch_available
from transformers.utils.generic import ExplicitEnum
from ...processing_utils import ProcessorMixin
if is_torch_available():
import torch
class __lowerCamelCase ( UpperCamelCase__ ):
"""simple docstring"""
snake_case__ = "char"
snake_case__ = "bpe"
snake_case__ = "wp"
UpperCamelCase = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE)
class __lowerCamelCase ( UpperCamelCase__ ):
"""simple docstring"""
snake_case__ = ["image_processor", "char_tokenizer"]
snake_case__ = "ViTImageProcessor"
snake_case__ = "MgpstrTokenizer"
def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : int=None , **SCREAMING_SNAKE_CASE__ : str ) -> str:
lowerCAmelCase__ = None
if "feature_extractor" in kwargs:
warnings.warn(
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
" instead." , SCREAMING_SNAKE_CASE__ , )
lowerCAmelCase__ = kwargs.pop("feature_extractor" )
lowerCAmelCase__ = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError("You need to specify an `image_processor`." )
if tokenizer is None:
raise ValueError("You need to specify a `tokenizer`." )
lowerCAmelCase__ = tokenizer
lowerCAmelCase__ = AutoTokenizer.from_pretrained("gpt2" )
lowerCAmelCase__ = AutoTokenizer.from_pretrained("bert-base-uncased" )
super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
def __call__( self : List[str] , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , **SCREAMING_SNAKE_CASE__ : Dict ) -> Dict:
if images is None and text is None:
raise ValueError("You need to specify either an `images` or `text` input to process." )
if images is not None:
lowerCAmelCase__ = self.image_processor(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
if text is not None:
lowerCAmelCase__ = self.char_tokenizer(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
if text is None:
return inputs
elif images is None:
return encodings
else:
lowerCAmelCase__ = encodings["input_ids"]
return inputs
def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Any:
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = sequences
lowerCAmelCase__ = char_preds.size(0 )
lowerCAmelCase__ , lowerCAmelCase__ = self._decode_helper(SCREAMING_SNAKE_CASE__ , "char" )
lowerCAmelCase__ , lowerCAmelCase__ = self._decode_helper(SCREAMING_SNAKE_CASE__ , "bpe" )
lowerCAmelCase__ , lowerCAmelCase__ = self._decode_helper(SCREAMING_SNAKE_CASE__ , "wp" )
lowerCAmelCase__ = []
lowerCAmelCase__ = []
for i in range(SCREAMING_SNAKE_CASE__ ):
lowerCAmelCase__ = [char_scores[i], bpe_scores[i], wp_scores[i]]
lowerCAmelCase__ = [char_strs[i], bpe_strs[i], wp_strs[i]]
lowerCAmelCase__ = scores.index(max(SCREAMING_SNAKE_CASE__ ) )
final_strs.append(strs[max_score_index] )
final_scores.append(scores[max_score_index] )
lowerCAmelCase__ = {}
lowerCAmelCase__ = final_strs
lowerCAmelCase__ = final_scores
lowerCAmelCase__ = char_strs
lowerCAmelCase__ = bpe_strs
lowerCAmelCase__ = wp_strs
return out
def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> str:
if format == DecodeType.CHARACTER:
lowerCAmelCase__ = self.char_decode
lowerCAmelCase__ = 1
lowerCAmelCase__ = "[s]"
elif format == DecodeType.BPE:
lowerCAmelCase__ = self.bpe_decode
lowerCAmelCase__ = 2
lowerCAmelCase__ = "#"
elif format == DecodeType.WORDPIECE:
lowerCAmelCase__ = self.wp_decode
lowerCAmelCase__ = 102
lowerCAmelCase__ = "[SEP]"
else:
raise ValueError(f'Format {format} is not supported.' )
lowerCAmelCase__ , lowerCAmelCase__ = [], []
lowerCAmelCase__ = pred_logits.size(0 )
lowerCAmelCase__ = pred_logits.size(1 )
lowerCAmelCase__ , lowerCAmelCase__ = pred_logits.topk(1 , dim=-1 , largest=SCREAMING_SNAKE_CASE__ , sorted=SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ = preds_index.view(-1 , SCREAMING_SNAKE_CASE__ )[:, 1:]
lowerCAmelCase__ = decoder(SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ , lowerCAmelCase__ = torch.nn.functional.softmax(SCREAMING_SNAKE_CASE__ , dim=2 ).max(dim=2 )
lowerCAmelCase__ = preds_max_prob[:, 1:]
for index in range(SCREAMING_SNAKE_CASE__ ):
lowerCAmelCase__ = preds_str[index].find(SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ = preds_str[index][:pred_eos]
lowerCAmelCase__ = preds_index[index].cpu().tolist()
lowerCAmelCase__ = pred_index.index(SCREAMING_SNAKE_CASE__ ) if eos_token in pred_index else -1
lowerCAmelCase__ = preds_max_prob[index][: pred_eos_index + 1]
lowerCAmelCase__ = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0
dec_strs.append(SCREAMING_SNAKE_CASE__ )
conf_scores.append(SCREAMING_SNAKE_CASE__ )
return dec_strs, conf_scores
def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Dict:
lowerCAmelCase__ = [seq.replace(" " , "" ) for seq in self.char_tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ )]
return decode_strs
def a ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> Optional[int]:
return self.bpe_tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ )
def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : str ) -> List[Any]:
lowerCAmelCase__ = [seq.replace(" " , "" ) for seq in self.wp_tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ )]
return decode_strs
| 61 |
"""simple docstring"""
# limitations under the License.
# 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 .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401
from .utils import deprecate
deprecate(
"""pipelines_utils""",
"""0.22.0""",
"""Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.""",
standard_warn=False,
stacklevel=3,
)
| 88 | 0 |
from typing import TYPE_CHECKING
# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
lowercase_ = {
'configuration_informer': [
'INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP',
'InformerConfig',
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase_ = [
'INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
'InformerForPrediction',
'InformerModel',
'InformerPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_informer import (
INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
InformerForPrediction,
InformerModel,
InformerPreTrainedModel,
)
else:
import sys
lowercase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 380 |
from math import pow, sqrt
def a ( *A__ : float ) -> bool:
"""simple docstring"""
_lowercase =len(A__ ) > 0 and all(value > 0.0 for value in values )
return result
def a ( A__ : float , A__ : float ) -> float | ValueError:
"""simple docstring"""
return (
round(sqrt(molar_mass_a / molar_mass_a ) , 6 )
if validate(A__ , A__ )
else ValueError('Input Error: Molar mass values must greater than 0.' )
)
def a ( A__ : float , A__ : float , A__ : float ) -> float | ValueError:
"""simple docstring"""
return (
round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 )
if validate(A__ , A__ , A__ )
else ValueError(
'Input Error: Molar mass and effusion rate values must greater than 0.' )
)
def a ( A__ : float , A__ : float , A__ : float ) -> float | ValueError:
"""simple docstring"""
return (
round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 )
if validate(A__ , A__ , A__ )
else ValueError(
'Input Error: Molar mass and effusion rate values must greater than 0.' )
)
def a ( A__ : float , A__ : float , A__ : float ) -> float | ValueError:
"""simple docstring"""
return (
round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 )
if validate(A__ , A__ , A__ )
else ValueError(
'Input Error: Molar mass and effusion rate values must greater than 0.' )
)
def a ( A__ : float , A__ : float , A__ : float ) -> float | ValueError:
"""simple docstring"""
return (
round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 )
if validate(A__ , A__ , A__ )
else ValueError(
'Input Error: Molar mass and effusion rate values must greater than 0.' )
)
| 380 | 1 |
'''simple docstring'''
import argparse
import torch
from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration
from transformers.utils import logging
logging.set_verbosity_info()
__SCREAMING_SNAKE_CASE : List[Any] = logging.get_logger(__name__)
__SCREAMING_SNAKE_CASE : Tuple = [
['''attention''', '''attn'''],
['''encoder_attention''', '''encoder_attn'''],
['''q_lin''', '''q_proj'''],
['''k_lin''', '''k_proj'''],
['''v_lin''', '''v_proj'''],
['''out_lin''', '''out_proj'''],
['''norm_embeddings''', '''layernorm_embedding'''],
['''position_embeddings''', '''embed_positions'''],
['''embeddings''', '''embed_tokens'''],
['''ffn.lin''', '''fc'''],
]
def a_ ( UpperCamelCase_ ):
if k == "embeddings.weight":
return "shared.weight"
for parlai_name, hf_name in PATTERNS:
A_ = k.replace(UpperCamelCase_ , UpperCamelCase_ )
if k.startswith("encoder" ):
A_ = k.replace(".attn" , ".self_attn" )
A_ = k.replace("norm1" , "self_attn_layer_norm" )
A_ = k.replace("norm2" , "final_layer_norm" )
elif k.startswith("decoder" ):
A_ = k.replace("norm1" , "self_attn_layer_norm" )
A_ = k.replace("norm2" , "encoder_attn_layer_norm" )
A_ = k.replace("norm3" , "final_layer_norm" )
return k
def a_ ( UpperCamelCase_ ):
A_ = [
"model.encoder.layernorm_embedding.weight",
"model.encoder.layernorm_embedding.bias",
"model.decoder.layernorm_embedding.weight",
"model.decoder.layernorm_embedding.bias",
]
for k in keys:
A_ = sd.pop(UpperCamelCase_ )
A_ = k.replace("layernorm_embedding" , "layer_norm" )
assert new_k not in sd
A_ = v
__SCREAMING_SNAKE_CASE : Union[str, Any] = ['''START''']
@torch.no_grad()
def a_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ):
A_ = torch.load(UpperCamelCase_ , map_location="cpu" )
A_ = model["model"]
A_ = BlenderbotConfig.from_json_file(UpperCamelCase_ )
A_ = BlenderbotForConditionalGeneration(UpperCamelCase_ )
A_ = m.model.state_dict().keys()
A_ = []
A_ = {}
for k, v in sd.items():
if k in IGNORE_KEYS:
continue
A_ = rename_state_dict_key(UpperCamelCase_ )
if new_k not in valid_keys:
failures.append([k, new_k] )
else:
A_ = v
if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm
rename_layernorm_keys(UpperCamelCase_ )
m.model.load_state_dict(UpperCamelCase_ , strict=UpperCamelCase_ )
m.half()
m.save_pretrained(UpperCamelCase_ )
if __name__ == "__main__":
__SCREAMING_SNAKE_CASE : Union[str, Any] = argparse.ArgumentParser()
# Required parameters
parser.add_argument('''--src_path''', type=str, help='''like blenderbot-model.bin''')
parser.add_argument('''--save_dir''', default='''hf_blenderbot''', type=str, help='''Where to save converted model.''')
parser.add_argument(
'''--hf_config_json''', default='''blenderbot-3b-config.json''', type=str, help='''Path to config to use'''
)
__SCREAMING_SNAKE_CASE : List[Any] = parser.parse_args()
convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
| 452 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_sentencepiece_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
if is_sentencepiece_available():
from ..ta.tokenization_ta import TaTokenizer
else:
from ...utils.dummy_sentencepiece_objects import TaTokenizer
__SCREAMING_SNAKE_CASE : str = TaTokenizer
if is_tokenizers_available():
from ..ta.tokenization_ta_fast import TaTokenizerFast
else:
from ...utils.dummy_tokenizers_objects import TaTokenizerFast
__SCREAMING_SNAKE_CASE : Any = TaTokenizerFast
__SCREAMING_SNAKE_CASE : Tuple = {'''configuration_mt5''': ['''MT5Config''', '''MT5OnnxConfig''']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__SCREAMING_SNAKE_CASE : List[Any] = [
'''MT5EncoderModel''',
'''MT5ForConditionalGeneration''',
'''MT5ForQuestionAnswering''',
'''MT5Model''',
'''MT5PreTrainedModel''',
'''MT5Stack''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__SCREAMING_SNAKE_CASE : str = ['''TFMT5EncoderModel''', '''TFMT5ForConditionalGeneration''', '''TFMT5Model''']
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__SCREAMING_SNAKE_CASE : List[str] = ['''FlaxMT5EncoderModel''', '''FlaxMT5ForConditionalGeneration''', '''FlaxMT5Model''']
if TYPE_CHECKING:
from .configuration_mta import MTaConfig, MTaOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mta import (
MTaEncoderModel,
MTaForConditionalGeneration,
MTaForQuestionAnswering,
MTaModel,
MTaPreTrainedModel,
MTaStack,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_mta import TFMTaEncoderModel, TFMTaForConditionalGeneration, TFMTaModel
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_mta import FlaxMTaEncoderModel, FlaxMTaForConditionalGeneration, FlaxMTaModel
else:
import sys
__SCREAMING_SNAKE_CASE : Union[str, Any] = _LazyModule(
__name__,
globals()['''__file__'''],
_import_structure,
extra_objects={'''MT5Tokenizer''': MTaTokenizer, '''MT5TokenizerFast''': MTaTokenizerFast},
module_spec=__spec__,
)
| 452 | 1 |
"""simple docstring"""
from __future__ import annotations
from typing import Any
class _UpperCAmelCase :
def __init__( self :str , __UpperCamelCase :int , __UpperCamelCase :int , __UpperCamelCase :float = 0 ):
A, A = row, column
A = [[default_value for c in range(__UpperCamelCase )] for r in range(__UpperCamelCase )]
def __str__( self :Union[str, Any] ):
A = f"Matrix consist of {self.row} rows and {self.column} columns\n"
# Make string identifier
A = 0
for row_vector in self.array:
for obj in row_vector:
A = max(__UpperCamelCase , len(str(__UpperCamelCase ) ) )
A = f"%{max_element_length}s"
# Make string and return
def single_line(__UpperCamelCase :list[float] ) -> str:
nonlocal string_format_identifier
A = "["
line += ", ".join(string_format_identifier % (obj,) for obj in row_vector )
line += "]"
return line
s += "\n".join(single_line(__UpperCamelCase ) for row_vector in self.array )
return s
def __repr__( self :Any ):
return str(self )
def lowerCamelCase ( self :List[Any] , __UpperCamelCase :tuple[int, int] ):
if not (isinstance(__UpperCamelCase , (list, tuple) ) and len(__UpperCamelCase ) == 2):
return False
elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column):
return False
else:
return True
def __getitem__( self :List[Any] , __UpperCamelCase :tuple[int, int] ):
assert self.validate_indicies(__UpperCamelCase )
return self.array[loc[0]][loc[1]]
def __setitem__( self :int , __UpperCamelCase :tuple[int, int] , __UpperCamelCase :float ):
assert self.validate_indicies(__UpperCamelCase )
A = value
def __add__( self :int , __UpperCamelCase :Matrix ):
assert isinstance(__UpperCamelCase , __UpperCamelCase )
assert self.row == another.row and self.column == another.column
# Add
A = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
A = self[r, c] + another[r, c]
return result
def __neg__( self :Tuple ):
A = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
A = -self[r, c]
return result
def __sub__( self :Dict , __UpperCamelCase :Matrix ):
return self + (-another)
def __mul__( self :Union[str, Any] , __UpperCamelCase :int | float | Matrix ):
if isinstance(__UpperCamelCase , (int, float) ): # Scalar multiplication
A = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
A = self[r, c] * another
return result
elif isinstance(__UpperCamelCase , __UpperCamelCase ): # Matrix multiplication
assert self.column == another.row
A = Matrix(self.row , another.column )
for r in range(self.row ):
for c in range(another.column ):
for i in range(self.column ):
result[r, c] += self[r, i] * another[i, c]
return result
else:
A = f"Unsupported type given for another ({type(__UpperCamelCase )})"
raise TypeError(__UpperCamelCase )
def lowerCamelCase ( self :Tuple ):
A = Matrix(self.column , self.row )
for r in range(self.row ):
for c in range(self.column ):
A = self[r, c]
return result
def lowerCamelCase ( self :List[Any] , __UpperCamelCase :Matrix , __UpperCamelCase :Matrix ):
assert isinstance(__UpperCamelCase , __UpperCamelCase ) and isinstance(__UpperCamelCase , __UpperCamelCase )
assert self.row == self.column == u.row == v.row # u, v should be column vector
assert u.column == v.column == 1 # u, v should be column vector
# Calculate
A = v.transpose()
A = (v_t * self * u)[0, 0] + 1
if numerator_factor == 0:
return None # It's not invertable
return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor))
# Testing
if __name__ == "__main__":
def A__ ( ):
# a^(-1)
A = Matrix(3 , 3 , 0 )
for i in range(3 ):
A = 1
print(F"a^(-1) is {ainv}" )
# u, v
A = Matrix(3 , 1 , 0 )
A, A, A = 1, 2, -3
A = Matrix(3 , 1 , 0 )
A, A, A = 4, -2, 5
print(F"u is {u}" )
print(F"v is {v}" )
print(F"uv^T is {u * v.transpose()}" )
# Sherman Morrison
print(F"(a + uv^T)^(-1) is {ainv.sherman_morrison(UpperCamelCase , UpperCamelCase )}" )
def A__ ( ):
import doctest
doctest.testmod()
testa()
| 524 |
"""simple docstring"""
import json
import os
from dataclasses import dataclass
from functools import partial
from typing import Callable
import flax.linen as nn
import jax
import jax.numpy as jnp
import joblib
import optax
import wandb
from flax import jax_utils, struct, traverse_util
from flax.serialization import from_bytes, to_bytes
from flax.training import train_state
from flax.training.common_utils import shard
from tqdm.auto import tqdm
from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering
from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule
class _UpperCAmelCase ( lowercase_ ):
UpperCamelCase = 42
UpperCamelCase = jnp.floataa
UpperCamelCase = True
def lowerCamelCase ( self :Optional[int] ):
super().setup()
A = nn.Dense(5 , dtype=self.dtype )
def __call__( self :Tuple , *__UpperCamelCase :str , **__UpperCamelCase :List[Any] ):
A = super().__call__(*__UpperCamelCase , **__UpperCamelCase )
A = self.cls(outputs[2] )
return outputs[:2] + (cls_out,)
class _UpperCAmelCase ( lowercase_ ):
UpperCamelCase = FlaxBigBirdForNaturalQuestionsModule
def A__ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ):
def cross_entropy(UpperCamelCase , UpperCamelCase , UpperCamelCase=None ):
A = logits.shape[-1]
A = (labels[..., None] == jnp.arange(UpperCamelCase )[None]).astype("f4" )
A = jax.nn.log_softmax(UpperCamelCase , axis=-1 )
A = -jnp.sum(labels * logits , axis=-1 )
if reduction is not None:
A = reduction(UpperCamelCase )
return loss
A = partial(UpperCamelCase , reduction=jnp.mean )
A = cross_entropy(UpperCamelCase , UpperCamelCase )
A = cross_entropy(UpperCamelCase , UpperCamelCase )
A = cross_entropy(UpperCamelCase , UpperCamelCase )
return (start_loss + end_loss + pooled_loss) / 3
@dataclass
class _UpperCAmelCase :
UpperCamelCase = "google/bigbird-roberta-base"
UpperCamelCase = 3_0_0_0
UpperCamelCase = 1_0_5_0_0
UpperCamelCase = 1_2_8
UpperCamelCase = 3
UpperCamelCase = 1
UpperCamelCase = 5
# tx_args
UpperCamelCase = 3e-5
UpperCamelCase = 0.0
UpperCamelCase = 2_0_0_0_0
UpperCamelCase = 0.0095
UpperCamelCase = "bigbird-roberta-natural-questions"
UpperCamelCase = "training-expt"
UpperCamelCase = "data/nq-training.jsonl"
UpperCamelCase = "data/nq-validation.jsonl"
def lowerCamelCase ( self :Optional[Any] ):
os.makedirs(self.base_dir , exist_ok=__UpperCamelCase )
A = os.path.join(self.base_dir , self.save_dir )
A = self.batch_size_per_device * jax.device_count()
@dataclass
class _UpperCAmelCase :
UpperCamelCase = 42
UpperCamelCase = 4_0_9_6 # no dynamic padding on TPUs
def __call__( self :List[Any] , __UpperCamelCase :Union[str, Any] ):
A = self.collate_fn(__UpperCamelCase )
A = jax.tree_util.tree_map(__UpperCamelCase , __UpperCamelCase )
return batch
def lowerCamelCase ( self :Tuple , __UpperCamelCase :Tuple ):
A, A = self.fetch_inputs(features["input_ids"] )
A = {
"input_ids": jnp.array(__UpperCamelCase , dtype=jnp.intaa ),
"attention_mask": jnp.array(__UpperCamelCase , dtype=jnp.intaa ),
"start_labels": jnp.array(features["start_token"] , dtype=jnp.intaa ),
"end_labels": jnp.array(features["end_token"] , dtype=jnp.intaa ),
"pooled_labels": jnp.array(features["category"] , dtype=jnp.intaa ),
}
return batch
def lowerCamelCase ( self :int , __UpperCamelCase :list ):
A = [self._fetch_inputs(__UpperCamelCase ) for ids in input_ids]
return zip(*__UpperCamelCase )
def lowerCamelCase ( self :Union[str, Any] , __UpperCamelCase :list ):
A = [1 for _ in range(len(__UpperCamelCase ) )]
while len(__UpperCamelCase ) < self.max_length:
input_ids.append(self.pad_id )
attention_mask.append(0 )
return input_ids, attention_mask
def A__ ( UpperCamelCase , UpperCamelCase , UpperCamelCase=None ):
if seed is not None:
A = dataset.shuffle(seed=UpperCamelCase )
for i in range(len(UpperCamelCase ) // batch_size ):
A = dataset[i * batch_size : (i + 1) * batch_size]
yield dict(UpperCamelCase )
@partial(jax.pmap , axis_name="batch" )
def A__ ( UpperCamelCase , UpperCamelCase , **UpperCamelCase ):
def loss_fn(UpperCamelCase ):
A = model_inputs.pop("start_labels" )
A = model_inputs.pop("end_labels" )
A = model_inputs.pop("pooled_labels" )
A = state.apply_fn(**UpperCamelCase , params=UpperCamelCase , dropout_rng=UpperCamelCase , train=UpperCamelCase )
A, A, A = outputs
return state.loss_fn(
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , )
A, A = jax.random.split(UpperCamelCase )
A = jax.value_and_grad(UpperCamelCase )
A, A = grad_fn(state.params )
A = jax.lax.pmean({"loss": loss} , axis_name="batch" )
A = jax.lax.pmean(UpperCamelCase , "batch" )
A = state.apply_gradients(grads=UpperCamelCase )
return state, metrics, new_drp_rng
@partial(jax.pmap , axis_name="batch" )
def A__ ( UpperCamelCase , **UpperCamelCase ):
A = model_inputs.pop("start_labels" )
A = model_inputs.pop("end_labels" )
A = model_inputs.pop("pooled_labels" )
A = state.apply_fn(**UpperCamelCase , params=state.params , train=UpperCamelCase )
A, A, A = outputs
A = state.loss_fn(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase )
A = jax.lax.pmean({"loss": loss} , axis_name="batch" )
return metrics
class _UpperCAmelCase ( train_state.TrainState ):
UpperCamelCase = struct.field(pytree_node=lowercase_ )
@dataclass
class _UpperCAmelCase :
UpperCamelCase = 42
UpperCamelCase = 42
UpperCamelCase = 42
UpperCamelCase = 42
UpperCamelCase = 42
UpperCamelCase = 42
UpperCamelCase = None
def lowerCamelCase ( self :List[Any] , __UpperCamelCase :Optional[int] , __UpperCamelCase :List[str] , __UpperCamelCase :Any , __UpperCamelCase :int=None ):
A = model.params
A = TrainState.create(
apply_fn=model.__call__ , params=__UpperCamelCase , tx=__UpperCamelCase , loss_fn=__UpperCamelCase , )
if ckpt_dir is not None:
A, A, A, A, A = restore_checkpoint(__UpperCamelCase , __UpperCamelCase )
A = {
"lr": args.lr,
"init_lr": args.init_lr,
"warmup_steps": args.warmup_steps,
"num_train_steps": num_train_steps,
"weight_decay": args.weight_decay,
}
A, A = build_tx(**__UpperCamelCase )
A = train_state.TrainState(
step=__UpperCamelCase , apply_fn=model.__call__ , params=__UpperCamelCase , tx=__UpperCamelCase , opt_state=__UpperCamelCase , )
A = args
A = data_collator
A = lr
A = params
A = jax_utils.replicate(__UpperCamelCase )
return state
def lowerCamelCase ( self :List[str] , __UpperCamelCase :List[Any] , __UpperCamelCase :List[Any] , __UpperCamelCase :Optional[int] ):
A = self.args
A = len(__UpperCamelCase ) // args.batch_size
A = jax.random.PRNGKey(0 )
A = jax.random.split(__UpperCamelCase , jax.device_count() )
for epoch in range(args.max_epochs ):
A = jnp.array(0 , dtype=jnp.floataa )
A = get_batched_dataset(__UpperCamelCase , args.batch_size , seed=__UpperCamelCase )
A = 0
for batch in tqdm(__UpperCamelCase , total=__UpperCamelCase , desc=f"Running EPOCH-{epoch}" ):
A = self.data_collator(__UpperCamelCase )
A, A, A = self.train_step_fn(__UpperCamelCase , __UpperCamelCase , **__UpperCamelCase )
running_loss += jax_utils.unreplicate(metrics["loss"] )
i += 1
if i % args.logging_steps == 0:
A = jax_utils.unreplicate(state.step )
A = running_loss.item() / i
A = self.scheduler_fn(state_step - 1 )
A = self.evaluate(__UpperCamelCase , __UpperCamelCase )
A = {
"step": state_step.item(),
"eval_loss": eval_loss.item(),
"tr_loss": tr_loss,
"lr": lr.item(),
}
tqdm.write(str(__UpperCamelCase ) )
self.logger.log(__UpperCamelCase , commit=__UpperCamelCase )
if i % args.save_steps == 0:
self.save_checkpoint(args.save_dir + f"-e{epoch}-s{i}" , state=__UpperCamelCase )
def lowerCamelCase ( self :int , __UpperCamelCase :Optional[Any] , __UpperCamelCase :List[Any] ):
A = get_batched_dataset(__UpperCamelCase , self.args.batch_size )
A = len(__UpperCamelCase ) // self.args.batch_size
A = jnp.array(0 , dtype=jnp.floataa )
A = 0
for batch in tqdm(__UpperCamelCase , total=__UpperCamelCase , desc="Evaluating ... " ):
A = self.data_collator(__UpperCamelCase )
A = self.val_step_fn(__UpperCamelCase , **__UpperCamelCase )
running_loss += jax_utils.unreplicate(metrics["loss"] )
i += 1
return running_loss / i
def lowerCamelCase ( self :List[str] , __UpperCamelCase :List[str] , __UpperCamelCase :Optional[int] ):
A = jax_utils.unreplicate(__UpperCamelCase )
print(f"SAVING CHECKPOINT IN {save_dir}" , end=" ... " )
self.model_save_fn(__UpperCamelCase , params=state.params )
with open(os.path.join(__UpperCamelCase , "opt_state.msgpack" ) , "wb" ) as f:
f.write(to_bytes(state.opt_state ) )
joblib.dump(self.args , os.path.join(__UpperCamelCase , "args.joblib" ) )
joblib.dump(self.data_collator , os.path.join(__UpperCamelCase , "data_collator.joblib" ) )
with open(os.path.join(__UpperCamelCase , "training_state.json" ) , "w" ) as f:
json.dump({"step": state.step.item()} , __UpperCamelCase )
print("DONE" )
def A__ ( UpperCamelCase , UpperCamelCase ):
print(F"RESTORING CHECKPOINT FROM {save_dir}" , end=" ... " )
with open(os.path.join(UpperCamelCase , "flax_model.msgpack" ) , "rb" ) as f:
A = from_bytes(state.params , f.read() )
with open(os.path.join(UpperCamelCase , "opt_state.msgpack" ) , "rb" ) as f:
A = from_bytes(state.opt_state , f.read() )
A = joblib.load(os.path.join(UpperCamelCase , "args.joblib" ) )
A = joblib.load(os.path.join(UpperCamelCase , "data_collator.joblib" ) )
with open(os.path.join(UpperCamelCase , "training_state.json" ) , "r" ) as f:
A = json.load(UpperCamelCase )
A = training_state["step"]
print("DONE" )
return params, opt_state, step, args, data_collator
def A__ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ):
A = num_train_steps - warmup_steps
A = optax.linear_schedule(init_value=UpperCamelCase , end_value=UpperCamelCase , transition_steps=UpperCamelCase )
A = optax.linear_schedule(init_value=UpperCamelCase , end_value=1E-7 , transition_steps=UpperCamelCase )
A = optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] )
return lr
def A__ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ):
def weight_decay_mask(UpperCamelCase ):
A = traverse_util.flatten_dict(UpperCamelCase )
A = {k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()}
return traverse_util.unflatten_dict(UpperCamelCase )
A = scheduler_fn(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase )
A = optax.adamw(learning_rate=UpperCamelCase , weight_decay=UpperCamelCase , mask=UpperCamelCase )
return tx, lr
| 524 | 1 |
def a__ ( A__ = 2_0_0 ):
SCREAMING_SNAKE_CASE_ : int = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 2_0_0]
SCREAMING_SNAKE_CASE_ : Optional[int] = [0] * (pence + 1)
SCREAMING_SNAKE_CASE_ : List[str] = 1 # base case: 1 way to make 0 pence
for coin in coins:
for i in range(A__, pence + 1, 1 ):
number_of_ways[i] += number_of_ways[i - coin]
return number_of_ways[pence]
if __name__ == "__main__":
assert solution(2_00) == 7_36_82
| 101 |
from typing import List, Optional, Union
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class __lowercase (__SCREAMING_SNAKE_CASE ):
"""simple docstring"""
_UpperCAmelCase = ["""image_processor""", """tokenizer"""]
_UpperCAmelCase = """Pix2StructImageProcessor"""
_UpperCAmelCase = ("""T5Tokenizer""", """T5TokenizerFast""")
def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Dict = False
super().__init__(lowerCAmelCase__ , lowerCAmelCase__ )
def __call__( self , lowerCAmelCase__=None , lowerCAmelCase__ = None , lowerCAmelCase__ = True , lowerCAmelCase__ = False , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = 2_0_4_8 , lowerCAmelCase__ = 0 , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = False , lowerCAmelCase__ = False , lowerCAmelCase__ = False , lowerCAmelCase__ = False , lowerCAmelCase__ = False , lowerCAmelCase__ = True , lowerCAmelCase__ = None , **lowerCAmelCase__ , ):
"""simple docstring"""
if images is None and text is None:
raise ValueError('You have to specify either images or text.' )
# Get only text
if images is None and not self.image_processor.is_vqa:
SCREAMING_SNAKE_CASE_ : Optional[Any] = self.tokenizer
SCREAMING_SNAKE_CASE_ : str = self.tokenizer(
text=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ , stride=lowerCAmelCase__ , pad_to_multiple_of=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , return_overflowing_tokens=lowerCAmelCase__ , return_special_tokens_mask=lowerCAmelCase__ , return_offsets_mapping=lowerCAmelCase__ , return_token_type_ids=lowerCAmelCase__ , return_length=lowerCAmelCase__ , verbose=lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , **lowerCAmelCase__ , )
return text_encoding
if not self.image_processor.is_vqa:
# add pixel_values
SCREAMING_SNAKE_CASE_ : List[Any] = self.image_processor(
lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , max_patches=lowerCAmelCase__ , **lowerCAmelCase__ )
else:
# add pixel_values and bbox
SCREAMING_SNAKE_CASE_ : Any = self.image_processor(
lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , max_patches=lowerCAmelCase__ , header_text=lowerCAmelCase__ , **lowerCAmelCase__ )
if text is not None and not self.image_processor.is_vqa:
SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.tokenizer(
text=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ , stride=lowerCAmelCase__ , pad_to_multiple_of=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , return_overflowing_tokens=lowerCAmelCase__ , return_special_tokens_mask=lowerCAmelCase__ , return_offsets_mapping=lowerCAmelCase__ , return_token_type_ids=lowerCAmelCase__ , return_length=lowerCAmelCase__ , verbose=lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , **lowerCAmelCase__ , )
if "attention_mask" in text_encoding:
SCREAMING_SNAKE_CASE_ : Any = text_encoding.pop('attention_mask' )
if "input_ids" in text_encoding:
SCREAMING_SNAKE_CASE_ : List[str] = text_encoding.pop('input_ids' )
else:
SCREAMING_SNAKE_CASE_ : Union[str, Any] = None
if text_encoding is not None:
encoding_image_processor.update(lowerCAmelCase__ )
return encoding_image_processor
def UpperCamelCase__ ( self , *lowerCAmelCase__ , **lowerCAmelCase__ ):
"""simple docstring"""
return self.tokenizer.batch_decode(*lowerCAmelCase__ , **lowerCAmelCase__ )
def UpperCamelCase__ ( self , *lowerCAmelCase__ , **lowerCAmelCase__ ):
"""simple docstring"""
return self.tokenizer.decode(*lowerCAmelCase__ , **lowerCAmelCase__ )
@property
def UpperCamelCase__ ( self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : List[str] = self.tokenizer.model_input_names
SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
| 101 | 1 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
SCREAMING_SNAKE_CASE_ = {
"""configuration_mvp""": ["""MVP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MvpConfig""", """MvpOnnxConfig"""],
"""tokenization_mvp""": ["""MvpTokenizer"""],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_ = ["""MvpTokenizerFast"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_ = [
"""MVP_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""MvpForCausalLM""",
"""MvpForConditionalGeneration""",
"""MvpForQuestionAnswering""",
"""MvpForSequenceClassification""",
"""MvpModel""",
"""MvpPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig
from .tokenization_mvp import MvpTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_mvp_fast import MvpTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mvp import (
MVP_PRETRAINED_MODEL_ARCHIVE_LIST,
MvpForCausalLM,
MvpForConditionalGeneration,
MvpForQuestionAnswering,
MvpForSequenceClassification,
MvpModel,
MvpPreTrainedModel,
)
else:
import sys
SCREAMING_SNAKE_CASE_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 706 |
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 rescale, resize, to_channel_dimension_format
from ...image_utils import (
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
if is_vision_available():
import PIL
SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__)
def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Dict , lowerCAmelCase: Union[str, Any] ) -> Union[str, Any]:
_UpperCAmelCase : Dict = b.T
_UpperCAmelCase : Dict = np.sum(np.square(lowerCAmelCase ) , axis=1 )
_UpperCAmelCase : Optional[Any] = np.sum(np.square(lowerCAmelCase ) , axis=0 )
_UpperCAmelCase : str = np.matmul(lowerCAmelCase , lowerCAmelCase )
_UpperCAmelCase : Any = aa[:, None] - 2 * ab + ba[None, :]
return d
def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Union[str, Any] , lowerCAmelCase: Dict ) -> int:
_UpperCAmelCase : Any = x.reshape(-1 , 3 )
_UpperCAmelCase : List[str] = squared_euclidean_distance(lowerCAmelCase , lowerCAmelCase )
return np.argmin(lowerCAmelCase , axis=1 )
class a ( UpperCAmelCase ):
_lowercase = ["pixel_values"]
def __init__( self , A_ = None , A_ = True , A_ = None , A_ = PILImageResampling.BILINEAR , A_ = True , A_ = True , **A_ , ):
'''simple docstring'''
super().__init__(**A_ )
_UpperCAmelCase : Optional[Any] = size if size is not None else {"height": 256, "width": 256}
_UpperCAmelCase : Optional[int] = get_size_dict(A_ )
_UpperCAmelCase : Union[str, Any] = np.array(A_ ) if clusters is not None else None
_UpperCAmelCase : int = do_resize
_UpperCAmelCase : Union[str, Any] = size
_UpperCAmelCase : Optional[Any] = resample
_UpperCAmelCase : str = do_normalize
_UpperCAmelCase : List[str] = do_color_quantize
def _UpperCAmelCase ( self , A_ , A_ , A_ = PILImageResampling.BILINEAR , A_ = None , **A_ , ):
'''simple docstring'''
_UpperCAmelCase : int = get_size_dict(A_ )
if "height" not in size or "width" not in size:
raise ValueError(f'Size dictionary must contain both height and width keys. Got {size.keys()}' )
return resize(
A_ , size=(size["height"], size["width"]) , resample=A_ , data_format=A_ , **A_ )
def _UpperCAmelCase ( self , A_ , A_ = None , ):
'''simple docstring'''
_UpperCAmelCase : Dict = rescale(image=A_ , scale=1 / 1_27.5 , data_format=A_ )
_UpperCAmelCase : List[Any] = image - 1
return image
def _UpperCAmelCase ( self , A_ , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = ChannelDimension.FIRST , **A_ , ):
'''simple docstring'''
_UpperCAmelCase : Optional[int] = do_resize if do_resize is not None else self.do_resize
_UpperCAmelCase : Any = size if size is not None else self.size
_UpperCAmelCase : Dict = get_size_dict(A_ )
_UpperCAmelCase : List[Any] = resample if resample is not None else self.resample
_UpperCAmelCase : Any = do_normalize if do_normalize is not None else self.do_normalize
_UpperCAmelCase : Optional[Any] = do_color_quantize if do_color_quantize is not None else self.do_color_quantize
_UpperCAmelCase : Any = clusters if clusters is not None else self.clusters
_UpperCAmelCase : Optional[int] = np.array(A_ )
_UpperCAmelCase : List[str] = make_list_of_images(A_ )
if not valid_images(A_ ):
raise ValueError(
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
"torch.Tensor, tf.Tensor or jax.ndarray." )
if do_resize and size is None or resample is None:
raise ValueError("Size and resample must be specified if do_resize is True." )
if do_color_quantize and clusters is None:
raise ValueError("Clusters must be specified if do_color_quantize is True." )
# All transformations expect numpy arrays.
_UpperCAmelCase : List[str] = [to_numpy_array(A_ ) for image in images]
if do_resize:
_UpperCAmelCase : int = [self.resize(image=A_ , size=A_ , resample=A_ ) for image in images]
if do_normalize:
_UpperCAmelCase : List[str] = [self.normalize(image=A_ ) for image in images]
if do_color_quantize:
_UpperCAmelCase : Tuple = [to_channel_dimension_format(A_ , ChannelDimension.LAST ) for image in images]
# color quantize from (batch_size, height, width, 3) to (batch_size, height, width)
_UpperCAmelCase : List[str] = np.array(A_ )
_UpperCAmelCase : List[Any] = color_quantize(A_ , A_ ).reshape(images.shape[:-1] )
# flatten to (batch_size, height*width)
_UpperCAmelCase : Any = images.shape[0]
_UpperCAmelCase : List[Any] = images.reshape(A_ , -1 )
# We need to convert back to a list of images to keep consistent behaviour across processors.
_UpperCAmelCase : Union[str, Any] = list(A_ )
else:
_UpperCAmelCase : Optional[Any] = [to_channel_dimension_format(A_ , A_ ) for image in images]
_UpperCAmelCase : List[Any] = {"input_ids": images}
return BatchFeature(data=A_ , tensor_type=A_ )
| 467 | 0 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_torch_available,
)
__lowerCAmelCase : Union[str, Any] = {'''configuration_vit_mae''': ['''VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ViTMAEConfig''']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCAmelCase : str = [
'''VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''ViTMAEForPreTraining''',
'''ViTMAELayer''',
'''ViTMAEModel''',
'''ViTMAEPreTrainedModel''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCAmelCase : str = [
'''TFViTMAEForPreTraining''',
'''TFViTMAEModel''',
'''TFViTMAEPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_vit_mae import (
VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST,
ViTMAEForPreTraining,
ViTMAELayer,
ViTMAEModel,
ViTMAEPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel
else:
import sys
__lowerCAmelCase : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 58 | """simple docstring"""
import unittest
import torch
from torch import nn
from accelerate.test_utils import require_cuda
from accelerate.utils.memory import find_executable_batch_size, release_memory
def _lowerCamelCase( ):
raise RuntimeError("CUDA out of memory." )
class snake_case__ ( nn.Module ):
def __init__( self ):
super().__init__()
__a = nn.Linear(3 , 4 )
__a = nn.BatchNormad(4 )
__a = nn.Linear(4 , 5 )
def a__ ( self , lowerCamelCase ):
return self.lineara(self.batchnorm(self.lineara(lowerCamelCase ) ) )
class snake_case__ ( unittest.TestCase ):
def a__ ( self ):
__a = []
@find_executable_batch_size(starting_batch_size=128 )
def mock_training_loop_function(lowerCamelCase ):
nonlocal batch_sizes
batch_sizes.append(lowerCamelCase )
if batch_size != 8:
raise_fake_out_of_memory()
mock_training_loop_function()
self.assertListEqual(lowerCamelCase , [128, 64, 32, 16, 8] )
def a__ ( self ):
__a = []
@find_executable_batch_size(starting_batch_size=128 )
def mock_training_loop_function(lowerCamelCase , lowerCamelCase ):
nonlocal batch_sizes
batch_sizes.append(lowerCamelCase )
if batch_size != 8:
raise_fake_out_of_memory()
return batch_size, arga
__a , __a = mock_training_loop_function("hello" )
self.assertListEqual(lowerCamelCase , [128, 64, 32, 16, 8] )
self.assertListEqual([bs, arga] , [8, "hello"] )
def a__ ( self ):
@find_executable_batch_size(starting_batch_size=0 )
def mock_training_loop_function(lowerCamelCase ):
pass
with self.assertRaises(lowerCamelCase ) as cm:
mock_training_loop_function()
self.assertIn("No executable batch size found, reached zero." , cm.exception.args[0] )
def a__ ( self ):
@find_executable_batch_size(starting_batch_size=16 )
def mock_training_loop_function(lowerCamelCase ):
if batch_size > 0:
raise_fake_out_of_memory()
pass
with self.assertRaises(lowerCamelCase ) as cm:
mock_training_loop_function()
self.assertIn("No executable batch size found, reached zero." , cm.exception.args[0] )
def a__ ( self ):
@find_executable_batch_size(starting_batch_size=128 )
def mock_training_loop_function(lowerCamelCase , lowerCamelCase , lowerCamelCase ):
if batch_size != 8:
raise raise_fake_out_of_memory()
with self.assertRaises(lowerCamelCase ) as cm:
mock_training_loop_function(128 , "hello" , "world" )
self.assertIn("Batch size was passed into `f`" , cm.exception.args[0] )
self.assertIn("`f(arg1='hello', arg2='world')" , cm.exception.args[0] )
def a__ ( self ):
@find_executable_batch_size(starting_batch_size=16 )
def mock_training_loop_function(lowerCamelCase ):
raise ValueError("Oops, we had an error!" )
with self.assertRaises(lowerCamelCase ) as cm:
mock_training_loop_function()
self.assertIn("Oops, we had an error!" , cm.exception.args[0] )
@require_cuda
def a__ ( self ):
__a = torch.cuda.memory_allocated()
__a = ModelForTest()
model.cuda()
self.assertGreater(torch.cuda.memory_allocated() , lowerCamelCase )
__a = release_memory(lowerCamelCase )
self.assertEqual(torch.cuda.memory_allocated() , lowerCamelCase )
| 528 | 0 |
import tempfile
import unittest
from transformers import SPIECE_UNDERLINE, BatchEncoding, PLBartTokenizer, is_torch_available
from transformers.testing_utils import (
get_tests_dir,
nested_simplify,
require_sentencepiece,
require_tokenizers,
require_torch,
)
from ...test_tokenization_common import TokenizerTesterMixin
__lowerCamelCase :Any = get_tests_dir('fixtures/test_sentencepiece.model')
if is_torch_available():
from transformers.models.plbart.modeling_plbart import shift_tokens_right
__lowerCamelCase :str = 50_003
__lowerCamelCase :int = 50_002
@require_sentencepiece
@require_tokenizers
class A__ ( __lowercase , unittest.TestCase):
"""simple docstring"""
snake_case__ : List[str] =PLBartTokenizer
snake_case__ : Any =None
snake_case__ : Dict =False
def a__ ( self: int )-> Tuple:
super().setUp()
# We have a SentencePiece fixture for testing
lowerCamelCase : List[Any] = PLBartTokenizer(__a , language_codes="""base""" , keep_accents=__a )
tokenizer.save_pretrained(self.tmpdirname )
def a__ ( self: int )-> str:
lowerCamelCase : Optional[Any] = PLBartTokenizer(__a , language_codes="""base""" , keep_accents=__a )
lowerCamelCase : List[str] = tokenizer.tokenize("""This is a test""" )
self.assertListEqual(__a , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(__a ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , )
lowerCamelCase : Optional[Any] = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" )
self.assertListEqual(
__a , [
SPIECE_UNDERLINE + """I""",
SPIECE_UNDERLINE + """was""",
SPIECE_UNDERLINE + """b""",
"""or""",
"""n""",
SPIECE_UNDERLINE + """in""",
SPIECE_UNDERLINE + """""",
"""9""",
"""2""",
"""0""",
"""0""",
"""0""",
""",""",
SPIECE_UNDERLINE + """and""",
SPIECE_UNDERLINE + """this""",
SPIECE_UNDERLINE + """is""",
SPIECE_UNDERLINE + """f""",
"""al""",
"""s""",
"""é""",
""".""",
] , )
lowerCamelCase : str = tokenizer.convert_tokens_to_ids(__a )
self.assertListEqual(
__a , [
value + tokenizer.fairseq_offset
for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]
] , )
lowerCamelCase : Dict = tokenizer.convert_ids_to_tokens(__a )
self.assertListEqual(
__a , [
SPIECE_UNDERLINE + """I""",
SPIECE_UNDERLINE + """was""",
SPIECE_UNDERLINE + """b""",
"""or""",
"""n""",
SPIECE_UNDERLINE + """in""",
SPIECE_UNDERLINE + """""",
"""<unk>""",
"""2""",
"""0""",
"""0""",
"""0""",
""",""",
SPIECE_UNDERLINE + """and""",
SPIECE_UNDERLINE + """this""",
SPIECE_UNDERLINE + """is""",
SPIECE_UNDERLINE + """f""",
"""al""",
"""s""",
"""<unk>""",
""".""",
] , )
lowerCamelCase : List[Any] = tokenizer.vocab_size
lowerCamelCase : str = [tokenizer.convert_ids_to_tokens(__a ) for x in range(end - 4 , __a )]
self.assertListEqual(__a , ["""__java__""", """__python__""", """__en_XX__""", """<mask>"""] )
lowerCamelCase : Optional[Any] = """java.lang.Exception, python.lang.Exception, javascript, php, ruby, go"""
lowerCamelCase : Optional[int] = tokenizer(__a ).input_ids
self.assertEqual(
tokenizer.decode(__a , skip_special_tokens=__a , clean_up_tokenization_spaces=__a ) , __a , )
def a__ ( self: Optional[int] )-> Optional[int]:
lowerCamelCase : Optional[Any] = PLBartTokenizer(__a , language_codes="""multi""" , keep_accents=__a )
lowerCamelCase : Optional[int] = tokenizer.tokenize("""This is a test""" )
self.assertListEqual(__a , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(__a ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , )
lowerCamelCase : int = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" )
self.assertListEqual(
__a , [
SPIECE_UNDERLINE + """I""",
SPIECE_UNDERLINE + """was""",
SPIECE_UNDERLINE + """b""",
"""or""",
"""n""",
SPIECE_UNDERLINE + """in""",
SPIECE_UNDERLINE + """""",
"""9""",
"""2""",
"""0""",
"""0""",
"""0""",
""",""",
SPIECE_UNDERLINE + """and""",
SPIECE_UNDERLINE + """this""",
SPIECE_UNDERLINE + """is""",
SPIECE_UNDERLINE + """f""",
"""al""",
"""s""",
"""é""",
""".""",
] , )
lowerCamelCase : Optional[Any] = tokenizer.convert_tokens_to_ids(__a )
self.assertListEqual(
__a , [
value + tokenizer.fairseq_offset
for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]
] , )
lowerCamelCase : str = tokenizer.convert_ids_to_tokens(__a )
self.assertListEqual(
__a , [
SPIECE_UNDERLINE + """I""",
SPIECE_UNDERLINE + """was""",
SPIECE_UNDERLINE + """b""",
"""or""",
"""n""",
SPIECE_UNDERLINE + """in""",
SPIECE_UNDERLINE + """""",
"""<unk>""",
"""2""",
"""0""",
"""0""",
"""0""",
""",""",
SPIECE_UNDERLINE + """and""",
SPIECE_UNDERLINE + """this""",
SPIECE_UNDERLINE + """is""",
SPIECE_UNDERLINE + """f""",
"""al""",
"""s""",
"""<unk>""",
""".""",
] , )
lowerCamelCase : Tuple = tokenizer.vocab_size
lowerCamelCase : int = [tokenizer.convert_ids_to_tokens(__a ) for x in range(end - 7 , __a )]
self.assertListEqual(
__a , ["""__java__""", """__python__""", """__en_XX__""", """__javascript__""", """__php__""", """__ruby__""", """__go__"""] )
lowerCamelCase : Tuple = """java.lang.Exception, python.lang.Exception, javascript, php, ruby, go"""
lowerCamelCase : List[Any] = tokenizer(__a ).input_ids
self.assertEqual(
tokenizer.decode(__a , skip_special_tokens=__a , clean_up_tokenization_spaces=__a ) , __a , )
@require_torch
@require_sentencepiece
@require_tokenizers
class A__ ( unittest.TestCase):
"""simple docstring"""
snake_case__ : Optional[int] ='''uclanlp/plbart-python-en_XX'''
snake_case__ : str =[
'''def maximum(a,b,c):NEW_LINE_INDENTreturn max([a,b,c])''',
'''def sum(a,b,c):NEW_LINE_INDENTreturn sum([a,b,c])''',
]
snake_case__ : Dict =[
'''Returns the maximum value of a b c.''',
'''Sums the values of a b c.''',
]
snake_case__ : Tuple =[
1_34,
54_52,
3_34_60,
3_34_41,
3_34_63,
3_34_65,
3_34_63,
3_34_49,
9_88,
20,
3_34_56,
19,
3_34_56,
7_71,
39,
42_58,
8_89,
33_18,
3_34_41,
3_34_63,
3_34_65,
3_34_63,
3_34_49,
24_71,
2,
PYTHON_CODE,
]
@classmethod
def a__ ( cls: Any )-> Optional[Any]:
lowerCamelCase : PLBartTokenizer = PLBartTokenizer.from_pretrained(
cls.checkpoint_name , language_codes="""base""" , src_lang="""python""" , tgt_lang="""en_XX""" )
lowerCamelCase : int = 1
return cls
def a__ ( self: Tuple )-> str:
self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""__java__"""] , 50_001 )
self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""__python__"""] , 50_002 )
self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""__en_XX__"""] , 50_003 )
def a__ ( self: List[str] )-> Tuple:
lowerCamelCase : Any = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0]
self.assertListEqual(self.expected_src_tokens , __a )
def a__ ( self: Optional[int] )-> Tuple:
self.assertIn(__a , self.tokenizer.all_special_ids )
lowerCamelCase : List[str] = [EN_CODE, 9_037, 33_442, 57, 752, 153, 14, 56, 18, 9, 2]
lowerCamelCase : int = self.tokenizer.decode(__a , skip_special_tokens=__a )
lowerCamelCase : List[str] = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__a )
self.assertEqual(__a , __a )
self.assertNotIn(self.tokenizer.eos_token , __a )
def a__ ( self: Union[str, Any] )-> Tuple:
lowerCamelCase : List[Any] = ["""def sum(a,b,c):NEW_LINE_INDENTreturn sum([a,b,c])""" * 20]
self.assertIsInstance(src_text[0] , __a )
lowerCamelCase : Dict = 10
lowerCamelCase : str = self.tokenizer(__a , max_length=__a , truncation=__a ).input_ids[0]
self.assertEqual(ids[-2] , 2 )
self.assertEqual(ids[-1] , __a )
self.assertEqual(len(__a ) , __a )
def a__ ( self: Optional[Any] )-> int:
self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """__java__"""] ) , [50_004, 50_001] )
def a__ ( self: int )-> Dict:
lowerCamelCase : Optional[Any] = tempfile.mkdtemp()
lowerCamelCase : Optional[Any] = self.tokenizer.fairseq_tokens_to_ids
self.tokenizer.save_pretrained(__a )
lowerCamelCase : str = PLBartTokenizer.from_pretrained(__a )
self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __a )
@require_torch
def a__ ( self: Optional[Any] )-> Optional[Any]:
lowerCamelCase : Optional[int] = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__a , return_tensors="""pt""" )
lowerCamelCase : int = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id )
# fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4
self.assertEqual(batch.input_ids[1][-2:].tolist() , [2, PYTHON_CODE] )
self.assertEqual(batch.decoder_input_ids[1][0] , __a )
self.assertEqual(batch.decoder_input_ids[1][-1] , 2 )
self.assertEqual(batch.labels[1][-2:].tolist() , [2, EN_CODE] )
@require_torch
def a__ ( self: Optional[int] )-> List[str]:
lowerCamelCase : Tuple = self.tokenizer(
self.src_text , text_target=self.tgt_text , padding=__a , truncation=__a , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , )
lowerCamelCase : Tuple = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id )
self.assertIsInstance(__a , __a )
self.assertEqual((2, 26) , batch.input_ids.shape )
self.assertEqual((2, 26) , batch.attention_mask.shape )
lowerCamelCase : List[Any] = batch.input_ids.tolist()[0]
self.assertListEqual(self.expected_src_tokens , __a )
self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS
# Test that special tokens are reset
self.assertEqual(self.tokenizer.prefix_tokens , [] )
self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, PYTHON_CODE] )
def a__ ( self: Optional[int] )-> List[str]:
lowerCamelCase : Dict = self.tokenizer(self.src_text , padding=__a , truncation=__a , max_length=3 , return_tensors="""pt""" )
lowerCamelCase : List[str] = self.tokenizer(
text_target=self.tgt_text , padding=__a , truncation=__a , max_length=10 , return_tensors="""pt""" )
lowerCamelCase : Optional[int] = targets["""input_ids"""]
lowerCamelCase : int = shift_tokens_right(__a , self.tokenizer.pad_token_id )
self.assertEqual(batch.input_ids.shape[1] , 3 )
self.assertEqual(batch.decoder_input_ids.shape[1] , 10 )
@require_torch
def a__ ( self: List[Any] )-> Any:
lowerCamelCase : List[str] = self.tokenizer._build_translation_inputs(
"""A test""" , return_tensors="""pt""" , src_lang="""en_XX""" , tgt_lang="""java""" )
self.assertEqual(
nested_simplify(__a ) , {
# A, test, EOS, en_XX
"""input_ids""": [[150, 242, 2, 50_003]],
"""attention_mask""": [[1, 1, 1, 1]],
# java
"""forced_bos_token_id""": 50_001,
} , )
| 707 |
"""simple docstring"""
__lowerCamelCase :List[Any] = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []}
__lowerCamelCase :Union[str, Any] = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]}
def snake_case ( UpperCamelCase__ : dict[int, list[int]] , UpperCamelCase__ : int , UpperCamelCase__ : list[bool] ) -> list[int]:
lowerCamelCase : Tuple = True
lowerCamelCase : Any = []
for neighbour in graph[vert]:
if not visited[neighbour]:
order += topology_sort(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )
order.append(UpperCamelCase__ )
return order
def snake_case ( UpperCamelCase__ : dict[int, list[int]] , UpperCamelCase__ : int , UpperCamelCase__ : list[bool] ) -> list[int]:
lowerCamelCase : List[Any] = True
lowerCamelCase : int = [vert]
for neighbour in reversed_graph[vert]:
if not visited[neighbour]:
component += find_components(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )
return component
def snake_case ( UpperCamelCase__ : dict[int, list[int]] ) -> list[list[int]]:
lowerCamelCase : int = len(UpperCamelCase__ ) * [False]
lowerCamelCase : dict[int, list[int]] = {vert: [] for vert in range(len(UpperCamelCase__ ) )}
for vert, neighbours in graph.items():
for neighbour in neighbours:
reversed_graph[neighbour].append(UpperCamelCase__ )
lowerCamelCase : int = []
for i, was_visited in enumerate(UpperCamelCase__ ):
if not was_visited:
order += topology_sort(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )
lowerCamelCase : Tuple = []
lowerCamelCase : str = len(UpperCamelCase__ ) * [False]
for i in range(len(UpperCamelCase__ ) ):
lowerCamelCase : Any = order[len(UpperCamelCase__ ) - i - 1]
if not visited[vert]:
lowerCamelCase : List[str] = find_components(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )
components_list.append(UpperCamelCase__ )
return components_list
| 42 | 0 |
import functools
def _lowercase ( a__ : str , a__ : str ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase = len(snake_case__ )
_UpperCamelCase = len(snake_case__ )
@functools.cache
def min_distance(a__ : int , a__ : int ) -> int:
# if first word index is overflow - delete all from the second word
if indexa >= len_worda:
return len_worda - indexa
# if second word index is overflow - delete all from the first word
if indexa >= len_worda:
return len_worda - indexa
_UpperCamelCase = int(worda[indexa] != worda[indexa] ) # current letters not identical
return min(
1 + min_distance(indexa + 1 , snake_case__ ) , 1 + min_distance(snake_case__ , indexa + 1 ) , diff + min_distance(indexa + 1 , indexa + 1 ) , )
return min_distance(0 , 0 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 147 |
"""simple docstring"""
from scipy.stats import spearmanr
import datasets
A_ = '''
The Spearman rank-order correlation coefficient is a measure of the
relationship between two datasets. Like other correlation coefficients,
this one varies between -1 and +1 with 0 implying no correlation.
Positive correlations imply that as data in dataset x increases, so
does data in dataset y. Negative correlations imply that as x increases,
y decreases. Correlations of -1 or +1 imply an exact monotonic relationship.
Unlike the Pearson correlation, the Spearman correlation does not
assume that both datasets are normally distributed.
The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Spearman correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.
'''
A_ = '''
Args:
predictions (`List[float]`): Predicted labels, as returned by a model.
references (`List[float]`): Ground truth labels.
return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns
only the spearmanr score. Defaults to `False`.
Returns:
spearmanr (`float`): Spearman correlation coefficient.
p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.
Examples:
Example 1:
>>> spearmanr_metric = datasets.load_metric("spearmanr")
>>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])
>>> print(results)
{\'spearmanr\': -0.7}
Example 2:
>>> spearmanr_metric = datasets.load_metric("spearmanr")
>>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],
... predictions=[10, 9, 2.5, 6, 4],
... return_pvalue=True)
>>> print(results[\'spearmanr\'])
-0.7
>>> print(round(results[\'spearmanr_pvalue\'], 2))
0.19
'''
A_ = r'''\
@book{kokoska2000crc,
title={CRC standard probability and statistics tables and formulae},
author={Kokoska, Stephen and Zwillinger, Daniel},
year={2000},
publisher={Crc Press}
}
@article{2020SciPy-NMeth,
author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
Haberland, Matt and Reddy, Tyler and Cournapeau, David and
Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
Kern, Robert and Larson, Eric and Carey, C J and
Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and
{VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
Harris, Charles R. and Archibald, Anne M. and
Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and
{van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
Computing in Python}},
journal = {Nature Methods},
year = {2020},
volume = {17},
pages = {261--272},
adsurl = {https://rdcu.be/b08Wh},
doi = {10.1038/s41592-019-0686-2},
}
'''
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class lowercase( datasets.Metric ):
'''simple docstring'''
def UpperCamelCase_ ( self: Dict ):
'''simple docstring'''
return datasets.MetricInfo(
description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features(
{
"""predictions""": datasets.Value("""float""" ),
"""references""": datasets.Value("""float""" ),
} ), reference_urls=["""https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html"""], )
def UpperCamelCase_ ( self: Any, a_: Union[str, Any], a_: Union[str, Any], a_: str=False ):
'''simple docstring'''
_snake_case : Optional[Any] = spearmanr(a_, a_ )
if return_pvalue:
return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
else:
return {"spearmanr": results[0]}
| 609 | 0 |
"""simple docstring"""
from collections import deque
def __lowerCAmelCase ( lowercase : Any ) -> List[Any]:
"""simple docstring"""
snake_case : Tuple = len(lowercase )
snake_case : Optional[int] = deque()
snake_case : Union[str, Any] = [False for _ in range(lowercase )]
snake_case : Optional[Any] = [-1 for _ in range(lowercase )]
snake_case : Optional[Any] = index_of[:]
def strong_connect(lowercase : str , lowercase : Any , lowercase : Dict ):
snake_case : Tuple = index # the number when this node is seen
snake_case : Optional[int] = index # lowest rank node reachable from here
index += 1
stack.append(lowercase )
snake_case : Optional[int] = True
for w in g[v]:
if index_of[w] == -1:
snake_case : Any = strong_connect(lowercase , lowercase , lowercase )
snake_case : Optional[int] = (
lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v]
)
elif on_stack[w]:
snake_case : Optional[int] = (
lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v]
)
if lowlink_of[v] == index_of[v]:
snake_case : int = []
snake_case : Dict = stack.pop()
snake_case : List[Any] = False
component.append(lowercase )
while w != v:
snake_case : Tuple = stack.pop()
snake_case : str = False
component.append(lowercase )
components.append(lowercase )
return index
snake_case : Any = []
for v in range(lowercase ):
if index_of[v] == -1:
strong_connect(lowercase , 0 , lowercase )
return components
def __lowerCAmelCase ( lowercase : Optional[Any] , lowercase : Optional[Any] ) -> Optional[Any]:
"""simple docstring"""
snake_case : Optional[int] = [[] for _ in range(lowercase )]
for u, v in edges:
g[u].append(lowercase )
return g
if __name__ == "__main__":
# Test
__snake_case = 7
__snake_case = [0, 0, 1, 2, 3, 3, 4, 4, 6]
__snake_case = [1, 3, 2, 0, 1, 4, 5, 6, 5]
__snake_case = [(u, v) for u, v in zip(source, target)]
__snake_case = create_graph(n_vertices, edges)
assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
| 117 |
"""simple docstring"""
from __future__ import annotations
__snake_case = list[tuple[int, int]]
__snake_case = [
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
]
__snake_case = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right
class _lowerCAmelCase :
def __init__( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , ) -> str:
'''simple docstring'''
snake_case : int = pos_x
snake_case : List[str] = pos_y
snake_case : List[Any] = (pos_y, pos_x)
snake_case : Optional[int] = goal_x
snake_case : Dict = goal_y
snake_case : Any = g_cost
snake_case : List[Any] = parent
snake_case : Union[str, Any] = self.calculate_heuristic()
def lowerCamelCase ( self ) -> float:
'''simple docstring'''
snake_case : Optional[Any] = abs(self.pos_x - self.goal_x )
snake_case : Dict = abs(self.pos_y - self.goal_y )
return dx + dy
def __lt__( self , UpperCamelCase__ ) -> bool:
'''simple docstring'''
return self.f_cost < other.f_cost
class _lowerCAmelCase :
def __init__( self , UpperCamelCase__ , UpperCamelCase__ ) -> List[Any]:
'''simple docstring'''
snake_case : int = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , UpperCamelCase__ )
snake_case : List[Any] = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_9999 , UpperCamelCase__ )
snake_case : Tuple = [self.start]
snake_case : list[Node] = []
snake_case : Dict = False
def lowerCamelCase ( self ) -> Path | None:
'''simple docstring'''
while self.open_nodes:
# Open Nodes are sorted using __lt__
self.open_nodes.sort()
snake_case : str = self.open_nodes.pop(0 )
if current_node.pos == self.target.pos:
snake_case : Tuple = True
return self.retrace_path(UpperCamelCase__ )
self.closed_nodes.append(UpperCamelCase__ )
snake_case : Optional[Any] = self.get_successors(UpperCamelCase__ )
for child_node in successors:
if child_node in self.closed_nodes:
continue
if child_node not in self.open_nodes:
self.open_nodes.append(UpperCamelCase__ )
else:
# retrieve the best current path
snake_case : Dict = self.open_nodes.pop(self.open_nodes.index(UpperCamelCase__ ) )
if child_node.g_cost < better_node.g_cost:
self.open_nodes.append(UpperCamelCase__ )
else:
self.open_nodes.append(UpperCamelCase__ )
if not self.reached:
return [self.start.pos]
return None
def lowerCamelCase ( self , UpperCamelCase__ ) -> list[Node]:
'''simple docstring'''
snake_case : Dict = []
for action in delta:
snake_case : Union[str, Any] = parent.pos_x + action[1]
snake_case : str = parent.pos_y + action[0]
if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(UpperCamelCase__ ) - 1):
continue
if grid[pos_y][pos_x] != 0:
continue
successors.append(
Node(
UpperCamelCase__ , UpperCamelCase__ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , UpperCamelCase__ , ) )
return successors
def lowerCamelCase ( self , UpperCamelCase__ ) -> Path:
'''simple docstring'''
snake_case : Optional[int] = node
snake_case : int = []
while current_node is not None:
path.append((current_node.pos_y, current_node.pos_x) )
snake_case : Any = current_node.parent
path.reverse()
return path
if __name__ == "__main__":
__snake_case = (0, 0)
__snake_case = (len(grid) - 1, len(grid[0]) - 1)
for elem in grid:
print(elem)
print("""------""")
__snake_case = GreedyBestFirst(init, goal)
__snake_case = greedy_bf.search()
if path:
for pos_x, pos_y in path:
__snake_case = 2
for elem in grid:
print(elem)
| 117 | 1 |
import unittest
from queue import Empty
from threading import Thread
from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available
from transformers.testing_utils import CaptureStdout, require_torch, torch_device
from ..test_modeling_common import ids_tensor
if is_torch_available():
import torch
from transformers import AutoModelForCausalLM
@require_torch
class lowerCAmelCase_ ( unittest.TestCase ):
def __snake_case ( self : Any ):
lowerCAmelCase__ = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' )
lowerCAmelCase__ = AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ).to(SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = -1
lowerCAmelCase__ = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = model.generate(SCREAMING_SNAKE_CASE_ , max_new_tokens=10 , do_sample=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = tokenizer.decode(greedy_ids[0] )
with CaptureStdout() as cs:
lowerCAmelCase__ = TextStreamer(SCREAMING_SNAKE_CASE_ )
model.generate(SCREAMING_SNAKE_CASE_ , max_new_tokens=10 , do_sample=SCREAMING_SNAKE_CASE_ , streamer=SCREAMING_SNAKE_CASE_ )
# The greedy text should be printed to stdout, except for the final "\n" in the streamer
lowerCAmelCase__ = cs.out[:-1]
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
def __snake_case ( self : Union[str, Any] ):
lowerCAmelCase__ = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' )
lowerCAmelCase__ = AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ).to(SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = -1
lowerCAmelCase__ = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = model.generate(SCREAMING_SNAKE_CASE_ , max_new_tokens=10 , do_sample=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = tokenizer.decode(greedy_ids[0] )
lowerCAmelCase__ = TextIteratorStreamer(SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = {'''input_ids''': input_ids, '''max_new_tokens''': 10, '''do_sample''': False, '''streamer''': streamer}
lowerCAmelCase__ = Thread(target=model.generate , kwargs=SCREAMING_SNAKE_CASE_ )
thread.start()
lowerCAmelCase__ = ''''''
for new_text in streamer:
streamer_text += new_text
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
def __snake_case ( self : Dict ):
lowerCAmelCase__ = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' )
lowerCAmelCase__ = AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ).to(SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = -1
lowerCAmelCase__ = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = model.generate(SCREAMING_SNAKE_CASE_ , max_new_tokens=10 , do_sample=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = greedy_ids[:, input_ids.shape[1] :]
lowerCAmelCase__ = tokenizer.decode(new_greedy_ids[0] )
with CaptureStdout() as cs:
lowerCAmelCase__ = TextStreamer(SCREAMING_SNAKE_CASE_ , skip_prompt=SCREAMING_SNAKE_CASE_ )
model.generate(SCREAMING_SNAKE_CASE_ , max_new_tokens=10 , do_sample=SCREAMING_SNAKE_CASE_ , streamer=SCREAMING_SNAKE_CASE_ )
# The greedy text should be printed to stdout, except for the final "\n" in the streamer
lowerCAmelCase__ = cs.out[:-1]
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
def __snake_case ( self : List[str] ):
# Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested
# with actual models -- the dummy models' tokenizers are not aligned with their models, and
# `skip_special_tokens=True` has no effect on them
lowerCAmelCase__ = AutoTokenizer.from_pretrained('''distilgpt2''' )
lowerCAmelCase__ = AutoModelForCausalLM.from_pretrained('''distilgpt2''' ).to(SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = -1
lowerCAmelCase__ = torch.ones((1, 5) , device=SCREAMING_SNAKE_CASE_ ).long() * model.config.bos_token_id
with CaptureStdout() as cs:
lowerCAmelCase__ = TextStreamer(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ )
model.generate(SCREAMING_SNAKE_CASE_ , max_new_tokens=1 , do_sample=SCREAMING_SNAKE_CASE_ , streamer=SCREAMING_SNAKE_CASE_ )
# The prompt contains a special token, so the streamer should not print it. As such, the output text, when
# re-tokenized, must only contain one token
lowerCAmelCase__ = cs.out[:-1] # Remove the final "\n"
lowerCAmelCase__ = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' )
self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1) )
def __snake_case ( self : List[str] ):
lowerCAmelCase__ = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' )
lowerCAmelCase__ = AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ).to(SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = -1
lowerCAmelCase__ = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(SCREAMING_SNAKE_CASE_ )
lowerCAmelCase__ = TextIteratorStreamer(SCREAMING_SNAKE_CASE_ , timeout=0.001 )
lowerCAmelCase__ = {'''input_ids''': input_ids, '''max_new_tokens''': 10, '''do_sample''': False, '''streamer''': streamer}
lowerCAmelCase__ = Thread(target=model.generate , kwargs=SCREAMING_SNAKE_CASE_ )
thread.start()
# The streamer will timeout after 0.001 seconds, so an exception will be raised
with self.assertRaises(SCREAMING_SNAKE_CASE_ ):
lowerCAmelCase__ = ''''''
for new_text in streamer:
streamer_text += new_text
| 668 |
"""simple docstring"""
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union
import pyarrow as pa
if TYPE_CHECKING:
from .features import FeatureType
@dataclass
class __lowerCamelCase :
a__: List[str]
a__: Optional[str] = None
# Automatically constructed
a__: ClassVar[str] = "dict"
a__: ClassVar[Any] = None
a__: str = field(default='Translation' , init=lowerCAmelCase , repr=lowerCAmelCase )
def __call__( self ):
return pa.struct({lang: pa.string() for lang in sorted(self.languages )} )
def UpperCAmelCase__ ( self ):
from .features import Value
return {k: Value('''string''' ) for k in sorted(self.languages )}
@dataclass
class __lowerCamelCase :
a__: Optional[List] = None
a__: Optional[int] = None
a__: Optional[str] = None
# Automatically constructed
a__: ClassVar[str] = "dict"
a__: ClassVar[Any] = None
a__: str = field(default='TranslationVariableLanguages' , init=lowerCAmelCase , repr=lowerCAmelCase )
def UpperCAmelCase__ ( self ):
lowerCamelCase_ = sorted(set(self.languages ) ) if self.languages else None
lowerCamelCase_ = len(self.languages ) if self.languages else None
def __call__( self ):
return pa.struct({'''language''': pa.list_(pa.string() ), '''translation''': pa.list_(pa.string() )} )
def UpperCAmelCase__ ( self , UpperCAmelCase ):
lowerCamelCase_ = set(self.languages )
if self.languages and set(UpperCAmelCase ) - lang_set:
raise ValueError(
f"Some languages in example ({', '.join(sorted(set(UpperCAmelCase ) - lang_set ) )}) are not in valid set ({', '.join(UpperCAmelCase )})." )
# Convert dictionary into tuples, splitting out cases where there are
# multiple translations for a single language.
lowerCamelCase_ = []
for lang, text in translation_dict.items():
if isinstance(UpperCAmelCase , UpperCAmelCase ):
translation_tuples.append((lang, text) )
else:
translation_tuples.extend([(lang, el) for el in text] )
# Ensure translations are in ascending order by language code.
lowerCamelCase_ , lowerCamelCase_ = zip(*sorted(UpperCAmelCase ) )
return {"language": languages, "translation": translations}
def UpperCAmelCase__ ( self ):
from .features import Sequence, Value
return {
"language": Sequence(Value('''string''' ) ),
"translation": Sequence(Value('''string''' ) ),
}
| 29 | 0 |
'''simple docstring'''
import argparse
from collections import defaultdict
import yaml
_UpperCamelCase = """docs/source/en/_toctree.yml"""
def _lowerCAmelCase( UpperCAmelCase_ : str ) -> Optional[int]:
lowerCAmelCase__ = defaultdict(UpperCAmelCase_ )
for doc in model_doc:
counts[doc["local"]] += 1
lowerCAmelCase__ = [key for key, value in counts.items() if value > 1]
lowerCAmelCase__ = []
for duplicate_key in duplicates:
lowerCAmelCase__ = list({doc["""title"""] for doc in model_doc if doc["""local"""] == duplicate_key} )
if len(UpperCAmelCase_ ) > 1:
raise ValueError(
F'''{duplicate_key} is present several times in the documentation table of content at '''
"""`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the """
"""others.""" )
# Only add this once
new_doc.append({"""local""": duplicate_key, """title""": titles[0]} )
# Add none duplicate-keys
new_doc.extend([doc for doc in model_doc if counts[doc["""local"""]] == 1] )
# Sort
return sorted(UpperCAmelCase_ , key=lambda UpperCAmelCase_ : s["title"].lower() )
def _lowerCAmelCase( UpperCAmelCase_ : int=False ) -> int:
with open(UpperCAmelCase_ , encoding="""utf-8""" ) as f:
lowerCAmelCase__ = yaml.safe_load(f.read() )
# Get to the API doc
lowerCAmelCase__ = 0
while content[api_idx]["title"] != "API":
api_idx += 1
lowerCAmelCase__ = content[api_idx]["""sections"""]
# Then to the model doc
lowerCAmelCase__ = 0
while api_doc[model_idx]["title"] != "Models":
model_idx += 1
lowerCAmelCase__ = api_doc[model_idx]["""sections"""]
lowerCAmelCase__ = [(idx, section) for idx, section in enumerate(UpperCAmelCase_ ) if """sections""" in section]
lowerCAmelCase__ = False
for idx, modality_doc in modalities_docs:
lowerCAmelCase__ = modality_doc["""sections"""]
lowerCAmelCase__ = clean_model_doc_toc(UpperCAmelCase_ )
if old_modality_doc != new_modality_doc:
lowerCAmelCase__ = True
if overwrite:
lowerCAmelCase__ = new_modality_doc
if diff:
if overwrite:
lowerCAmelCase__ = model_doc
lowerCAmelCase__ = api_doc
with open(UpperCAmelCase_ , """w""" , encoding="""utf-8""" ) as f:
f.write(yaml.dump(UpperCAmelCase_ , allow_unicode=UpperCAmelCase_ ) )
else:
raise ValueError(
"""The model doc part of the table of content is not properly sorted, run `make style` to fix this.""" )
if __name__ == "__main__":
_UpperCamelCase = argparse.ArgumentParser()
parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
_UpperCamelCase = parser.parse_args()
check_model_doc(args.fix_and_overwrite)
| 211 |
'''simple docstring'''
import inspect
from typing import Callable, List, Optional, Union
import torch
from transformers import (
CLIPImageProcessor,
CLIPTextModel,
CLIPTokenizer,
WhisperForConditionalGeneration,
WhisperProcessor,
)
from diffusers import (
AutoencoderKL,
DDIMScheduler,
DiffusionPipeline,
LMSDiscreteScheduler,
PNDMScheduler,
UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.utils import logging
_UpperCamelCase = logging.get_logger(__name__) # pylint: disable=invalid-name
class lowerCamelCase__ ( _A ):
'''simple docstring'''
def __init__( self : Optional[int] , __A : WhisperForConditionalGeneration , __A : WhisperProcessor , __A : AutoencoderKL , __A : CLIPTextModel , __A : CLIPTokenizer , __A : UNetaDConditionModel , __A : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __A : StableDiffusionSafetyChecker , __A : CLIPImageProcessor , ) -> List[Any]:
'''simple docstring'''
super().__init__()
if safety_checker is None:
logger.warning(
f'''You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure'''
""" that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"""
""" results in services or applications open to the public. Both the diffusers team and Hugging Face"""
""" strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"""
""" it only for use-cases that involve analyzing network behavior or auditing its results. For more"""
""" information, please have a look at https://github.com/huggingface/diffusers/pull/254 .""" )
self.register_modules(
speech_model=__A , speech_processor=__A , vae=__A , text_encoder=__A , tokenizer=__A , unet=__A , scheduler=__A , feature_extractor=__A , )
def lowercase__ ( self : Optional[Any] , __A : Optional[Union[str, int]] = "auto" ) -> Any:
'''simple docstring'''
if slice_size == "auto":
lowerCAmelCase__ = self.unet.config.attention_head_dim // 2
self.unet.set_attention_slice(__A )
def lowercase__ ( self : List[str] ) -> List[Any]:
'''simple docstring'''
self.enable_attention_slicing(__A )
@torch.no_grad()
def __call__( self : Optional[int] , __A : List[str] , __A : Tuple=1_6000 , __A : int = 512 , __A : int = 512 , __A : int = 50 , __A : float = 7.5 , __A : Optional[Union[str, List[str]]] = None , __A : Optional[int] = 1 , __A : float = 0.0 , __A : Optional[torch.Generator] = None , __A : Optional[torch.FloatTensor] = None , __A : Optional[str] = "pil" , __A : bool = True , __A : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __A : int = 1 , **__A : str , ) -> Union[str, Any]:
'''simple docstring'''
lowerCAmelCase__ = self.speech_processor.feature_extractor(
__A , return_tensors="""pt""" , sampling_rate=__A ).input_features.to(self.device )
lowerCAmelCase__ = self.speech_model.generate(__A , max_length=48_0000 )
lowerCAmelCase__ = self.speech_processor.tokenizer.batch_decode(__A , skip_special_tokens=__A , normalize=__A )[
0
]
if isinstance(__A , __A ):
lowerCAmelCase__ = 1
elif isinstance(__A , __A ):
lowerCAmelCase__ = len(__A )
else:
raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(__A )}''' )
if height % 8 != 0 or width % 8 != 0:
raise ValueError(f'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' )
if (callback_steps is None) or (
callback_steps is not None and (not isinstance(__A , __A ) or callback_steps <= 0)
):
raise ValueError(
f'''`callback_steps` has to be a positive integer but is {callback_steps} of type'''
f''' {type(__A )}.''' )
# get prompt text embeddings
lowerCAmelCase__ = self.tokenizer(
__A , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , )
lowerCAmelCase__ = text_inputs.input_ids
if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
lowerCAmelCase__ = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] )
logger.warning(
"""The following part of your input was truncated because CLIP can only handle sequences up to"""
f''' {self.tokenizer.model_max_length} tokens: {removed_text}''' )
lowerCAmelCase__ = text_input_ids[:, : self.tokenizer.model_max_length]
lowerCAmelCase__ = self.text_encoder(text_input_ids.to(self.device ) )[0]
# duplicate text embeddings for each generation per prompt, using mps friendly method
lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = text_embeddings.shape
lowerCAmelCase__ = text_embeddings.repeat(1 , __A , 1 )
lowerCAmelCase__ = text_embeddings.view(bs_embed * num_images_per_prompt , __A , -1 )
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
# corresponds to doing no classifier free guidance.
lowerCAmelCase__ = guidance_scale > 1.0
# get unconditional embeddings for classifier free guidance
if do_classifier_free_guidance:
lowerCAmelCase__ = 42
if negative_prompt is None:
lowerCAmelCase__ = [""""""] * batch_size
elif type(__A ) is not type(__A ):
raise TypeError(
f'''`negative_prompt` should be the same type to `prompt`, but got {type(__A )} !='''
f''' {type(__A )}.''' )
elif isinstance(__A , __A ):
lowerCAmelCase__ = [negative_prompt]
elif batch_size != len(__A ):
raise ValueError(
f'''`negative_prompt`: {negative_prompt} has batch size {len(__A )}, but `prompt`:'''
f''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches'''
""" the batch size of `prompt`.""" )
else:
lowerCAmelCase__ = negative_prompt
lowerCAmelCase__ = text_input_ids.shape[-1]
lowerCAmelCase__ = self.tokenizer(
__A , padding="""max_length""" , max_length=__A , truncation=__A , return_tensors="""pt""" , )
lowerCAmelCase__ = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0]
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
lowerCAmelCase__ = uncond_embeddings.shape[1]
lowerCAmelCase__ = uncond_embeddings.repeat(1 , __A , 1 )
lowerCAmelCase__ = uncond_embeddings.view(batch_size * num_images_per_prompt , __A , -1 )
# For classifier free guidance, we need to do two forward passes.
# Here we concatenate the unconditional and text embeddings into a single batch
# to avoid doing two forward passes
lowerCAmelCase__ = torch.cat([uncond_embeddings, text_embeddings] )
# get the initial random noise unless the user supplied it
# Unlike in other pipelines, latents need to be generated in the target device
# for 1-to-1 results reproducibility with the CompVis implementation.
# However this currently doesn't work in `mps`.
lowerCAmelCase__ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
lowerCAmelCase__ = text_embeddings.dtype
if latents is None:
if self.device.type == "mps":
# randn does not exist on mps
lowerCAmelCase__ = torch.randn(__A , generator=__A , device="""cpu""" , dtype=__A ).to(
self.device )
else:
lowerCAmelCase__ = torch.randn(__A , generator=__A , device=self.device , dtype=__A )
else:
if latents.shape != latents_shape:
raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' )
lowerCAmelCase__ = latents.to(self.device )
# set timesteps
self.scheduler.set_timesteps(__A )
# Some schedulers like PNDM have timesteps as arrays
# It's more optimized to move all timesteps to correct device beforehand
lowerCAmelCase__ = self.scheduler.timesteps.to(self.device )
# scale the initial noise by the standard deviation required by the scheduler
lowerCAmelCase__ = latents * self.scheduler.init_noise_sigma
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
# and should be between [0, 1]
lowerCAmelCase__ = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() )
lowerCAmelCase__ = {}
if accepts_eta:
lowerCAmelCase__ = eta
for i, t in enumerate(self.progress_bar(__A ) ):
# expand the latents if we are doing classifier free guidance
lowerCAmelCase__ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
lowerCAmelCase__ = self.scheduler.scale_model_input(__A , __A )
# predict the noise residual
lowerCAmelCase__ = self.unet(__A , __A , encoder_hidden_states=__A ).sample
# perform guidance
if do_classifier_free_guidance:
lowerCAmelCase__ ,lowerCAmelCase__ = noise_pred.chunk(2 )
lowerCAmelCase__ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
# compute the previous noisy sample x_t -> x_t-1
lowerCAmelCase__ = self.scheduler.step(__A , __A , __A , **__A ).prev_sample
# call the callback, if provided
if callback is not None and i % callback_steps == 0:
callback(__A , __A , __A )
lowerCAmelCase__ = 1 / 0.1_8_2_1_5 * latents
lowerCAmelCase__ = self.vae.decode(__A ).sample
lowerCAmelCase__ = (image / 2 + 0.5).clamp(0 , 1 )
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
lowerCAmelCase__ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy()
if output_type == "pil":
lowerCAmelCase__ = self.numpy_to_pil(__A )
if not return_dict:
return image
return StableDiffusionPipelineOutput(images=__A , nsfw_content_detected=__A )
| 211 | 1 |
import requests
from bsa import BeautifulSoup
def _A ( _lowercase , _lowercase ) -> str:
"""simple docstring"""
__UpperCamelCase = BeautifulSoup(requests.get(_lowercase , params=_lowercase ).content , 'html.parser' )
__UpperCamelCase = soup.find('div' , attrs={'class': 'gs_ri'} )
__UpperCamelCase = div.find('div' , attrs={'class': 'gs_fl'} ).find_all('a' )
return anchors[2].get_text()
if __name__ == "__main__":
__snake_case = {
'''title''': (
'''Precisely geometry controlled microsupercapacitors for ultrahigh areal '''
'''capacitance, volumetric capacitance, and energy density'''
),
'''journal''': '''Chem. Mater.''',
'''volume''': 3_0,
'''pages''': '''3979-3990''',
'''year''': 2_0_1_8,
'''hl''': '''en''',
}
print(get_citation('''https://scholar.google.com/scholar_lookup''', params=params))
| 1 |
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 __lowerCamelCase (_a , unittest.TestCase ):
_lowercase = VideoToVideoSDPipeline
_lowercase = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"""video"""} ) - {"""image""", """width""", """height"""}
_lowercase = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"""video"""} ) - {"""image"""}
_lowercase = PipelineTesterMixin.required_optional_params - {"""latents"""}
_lowercase = False
# No `output_type`.
_lowercase = frozenset(
[
"""num_inference_steps""",
"""generator""",
"""latents""",
"""return_dict""",
"""callback""",
"""callback_steps""",
] )
def snake_case_ ( self: List[str] ):
'''simple docstring'''
torch.manual_seed(0 )
__UpperCamelCase = UNetaDConditionModel(
block_out_channels=(32, 64, 64, 64),layers_per_block=2,sample_size=32,in_channels=4,out_channels=4,down_block_types=('CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'DownBlock3D'),up_block_types=('UpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D'),cross_attention_dim=32,attention_head_dim=4,)
__UpperCamelCase = DDIMScheduler(
beta_start=0.0_0_0_8_5,beta_end=0.0_1_2,beta_schedule='scaled_linear',clip_sample=A_,set_alpha_to_one=A_,)
torch.manual_seed(0 )
__UpperCamelCase = AutoencoderKL(
block_out_channels=[32, 64],in_channels=3,out_channels=3,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'],up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'],latent_channels=4,sample_size=128,)
torch.manual_seed(0 )
__UpperCamelCase = CLIPTextConfig(
bos_token_id=0,eos_token_id=2,hidden_size=32,intermediate_size=37,layer_norm_eps=1E-05,num_attention_heads=4,num_hidden_layers=5,pad_token_id=1,vocab_size=1000,hidden_act='gelu',projection_dim=512,)
__UpperCamelCase = CLIPTextModel(A_ )
__UpperCamelCase = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )
__UpperCamelCase = {
'unet': unet,
'scheduler': scheduler,
'vae': vae,
'text_encoder': text_encoder,
'tokenizer': tokenizer,
}
return components
def snake_case_ ( self: Union[str, Any],A_: Any,A_: Any=0 ):
'''simple docstring'''
__UpperCamelCase = floats_tensor((1, 3, 3, 32, 32),rng=random.Random(A_ ) ).to(A_ )
if str(A_ ).startswith('mps' ):
__UpperCamelCase = torch.manual_seed(A_ )
else:
__UpperCamelCase = torch.Generator(device=A_ ).manual_seed(A_ )
__UpperCamelCase = {
'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 snake_case_ ( self: Union[str, Any] ):
'''simple docstring'''
__UpperCamelCase = 'cpu' # ensure determinism for the device-dependent torch.Generator
__UpperCamelCase = self.get_dummy_components()
__UpperCamelCase = VideoToVideoSDPipeline(**A_ )
__UpperCamelCase = sd_pipe.to(A_ )
sd_pipe.set_progress_bar_config(disable=A_ )
__UpperCamelCase = self.get_dummy_inputs(A_ )
__UpperCamelCase = 'np'
__UpperCamelCase = sd_pipe(**A_ ).frames
__UpperCamelCase = frames[0][-3:, -3:, -1]
assert frames[0].shape == (32, 32, 3)
__UpperCamelCase = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] )
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 snake_case_ ( self: Any ):
'''simple docstring'''
self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=A_,expected_max_diff=5E-3 )
@unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.' )
def snake_case_ ( self: str ):
'''simple docstring'''
pass
@unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.' )
def snake_case_ ( self: Optional[Any] ):
'''simple docstring'''
pass
@unittest.skip(reason='`num_images_per_prompt` argument is not supported for this pipeline.' )
def snake_case_ ( self: int ):
'''simple docstring'''
pass
def snake_case_ ( self: Any ):
'''simple docstring'''
return super().test_progress_bar()
@slow
@skip_mps
class __lowerCamelCase (unittest.TestCase ):
def snake_case_ ( self: Tuple ):
'''simple docstring'''
__UpperCamelCase = VideoToVideoSDPipeline.from_pretrained('cerspense/zeroscope_v2_XL',torch_dtype=torch.floataa )
pipe.enable_model_cpu_offload()
# 10 frames
__UpperCamelCase = torch.Generator(device='cpu' ).manual_seed(0 )
__UpperCamelCase = torch.randn((1, 10, 3, 1024, 576),generator=A_ )
__UpperCamelCase = video.to('cuda' )
__UpperCamelCase = 'Spiderman is surfing'
__UpperCamelCase = pipe(A_,video=A_,generator=A_,num_inference_steps=3,output_type='pt' ).frames
__UpperCamelCase = np.array([-1.0_4_5_8_9_8_4, -1.1_2_7_9_2_9_7, -0.9_6_6_3_0_8_6, -0.9_1_5_0_3_9_0_6, -0.7_5_0_9_7_6_5_6] )
assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1E-2
| 1 | 1 |
import inspect
import unittest
from transformers import MobileViTVaConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
from transformers.models.mobilevitva.modeling_mobilevitva import (
MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
make_divisible,
)
if is_vision_available():
from PIL import Image
from transformers import MobileViTImageProcessor
class lowercase ( _SCREAMING_SNAKE_CASE ):
def __UpperCamelCase ( self ) -> List[str]:
"""simple docstring"""
UpperCamelCase = self.config_class(**self.inputs_dict )
self.parent.assertTrue(hasattr(A_ , 'width_multiplier' ) )
class lowercase :
def __init__( self , A_ , A_=13 , A_=64 , A_=2 , A_=3 , A_="swish" , A_=3 , A_=32 , A_=0.1 , A_=0.02 , A_=True , A_=True , A_=10 , A_=None , A_=0.25 , A_=0.0 , A_=0.0 , ) -> Dict:
"""simple docstring"""
UpperCamelCase = parent
UpperCamelCase = batch_size
UpperCamelCase = image_size
UpperCamelCase = patch_size
UpperCamelCase = num_channels
UpperCamelCase = make_divisible(512 * width_multiplier , divisor=8 )
UpperCamelCase = hidden_act
UpperCamelCase = conv_kernel_size
UpperCamelCase = output_stride
UpperCamelCase = classifier_dropout_prob
UpperCamelCase = use_labels
UpperCamelCase = is_training
UpperCamelCase = num_labels
UpperCamelCase = initializer_range
UpperCamelCase = scope
UpperCamelCase = width_multiplier
UpperCamelCase = ffn_dropout
UpperCamelCase = attn_dropout
def __UpperCamelCase ( self ) -> int:
"""simple docstring"""
UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
UpperCamelCase = None
UpperCamelCase = None
if self.use_labels:
UpperCamelCase = ids_tensor([self.batch_size] , self.num_labels )
UpperCamelCase = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels )
UpperCamelCase = self.get_config()
return config, pixel_values, labels, pixel_labels
def __UpperCamelCase ( self ) -> Optional[int]:
"""simple docstring"""
return MobileViTVaConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , )
def __UpperCamelCase ( self , A_ , A_ , A_ , A_ ) -> List[Any]:
"""simple docstring"""
UpperCamelCase = MobileViTVaModel(config=A_ )
model.to(A_ )
model.eval()
UpperCamelCase = model(A_ )
self.parent.assertEqual(
result.last_hidden_state.shape , (
self.batch_size,
self.last_hidden_size,
self.image_size // self.output_stride,
self.image_size // self.output_stride,
) , )
def __UpperCamelCase ( self , A_ , A_ , A_ , A_ ) -> str:
"""simple docstring"""
UpperCamelCase = self.num_labels
UpperCamelCase = MobileViTVaForImageClassification(A_ )
model.to(A_ )
model.eval()
UpperCamelCase = model(A_ , labels=A_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def __UpperCamelCase ( self , A_ , A_ , A_ , A_ ) -> Tuple:
"""simple docstring"""
UpperCamelCase = self.num_labels
UpperCamelCase = MobileViTVaForSemanticSegmentation(A_ )
model.to(A_ )
model.eval()
UpperCamelCase = model(A_ )
self.parent.assertEqual(
result.logits.shape , (
self.batch_size,
self.num_labels,
self.image_size // self.output_stride,
self.image_size // self.output_stride,
) , )
UpperCamelCase = model(A_ , labels=A_ )
self.parent.assertEqual(
result.logits.shape , (
self.batch_size,
self.num_labels,
self.image_size // self.output_stride,
self.image_size // self.output_stride,
) , )
def __UpperCamelCase ( self ) -> int:
"""simple docstring"""
UpperCamelCase = self.prepare_config_and_inputs()
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = config_and_inputs
UpperCamelCase = {'pixel_values': pixel_values}
return config, inputs_dict
@require_torch
class lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , unittest.TestCase ):
__lowercase : int = (
(MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
if is_torch_available()
else ()
)
__lowercase : Dict = (
{
"feature-extraction": MobileViTVaModel,
"image-classification": MobileViTVaForImageClassification,
"image-segmentation": MobileViTVaForSemanticSegmentation,
}
if is_torch_available()
else {}
)
__lowercase : str = False
__lowercase : int = False
__lowercase : Optional[int] = False
__lowercase : Optional[Any] = False
def __UpperCamelCase ( self ) -> Dict:
"""simple docstring"""
UpperCamelCase = MobileViTVaModelTester(self )
UpperCamelCase = MobileViTVaConfigTester(self , config_class=A_ , has_text_modality=A_ )
def __UpperCamelCase ( self ) -> List[str]:
"""simple docstring"""
self.config_tester.run_common_tests()
@unittest.skip(reason='MobileViTV2 does not use inputs_embeds' )
def __UpperCamelCase ( self ) -> Dict:
"""simple docstring"""
pass
@unittest.skip(reason='MobileViTV2 does not support input and output embeddings' )
def __UpperCamelCase ( self ) -> Optional[Any]:
"""simple docstring"""
pass
@unittest.skip(reason='MobileViTV2 does not output attentions' )
def __UpperCamelCase ( self ) -> Optional[Any]:
"""simple docstring"""
pass
@require_torch_multi_gpu
@unittest.skip(reason='Got `CUDA error: misaligned address` for tests after this one being run.' )
def __UpperCamelCase ( self ) -> int:
"""simple docstring"""
pass
@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' )
def __UpperCamelCase ( self ) -> List[str]:
"""simple docstring"""
pass
def __UpperCamelCase ( self ) -> List[Any]:
"""simple docstring"""
UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase = model_class(A_ )
UpperCamelCase = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
UpperCamelCase = [*signature.parameters.keys()]
UpperCamelCase = ['pixel_values']
self.assertListEqual(arg_names[:1] , A_ )
def __UpperCamelCase ( self ) -> Any:
"""simple docstring"""
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*A_ )
def __UpperCamelCase ( self ) -> str:
"""simple docstring"""
def check_hidden_states_output(A_ , A_ , A_ ):
UpperCamelCase = model_class(A_ )
model.to(A_ )
model.eval()
with torch.no_grad():
UpperCamelCase = model(**self._prepare_for_class(A_ , A_ ) )
UpperCamelCase = outputs.hidden_states
UpperCamelCase = 5
self.assertEqual(len(A_ ) , A_ )
# MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
# with the width and height being successively divided by 2.
UpperCamelCase = 2
for i in range(len(A_ ) ):
self.assertListEqual(
list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , )
divisor *= 2
self.assertEqual(self.model_tester.output_stride , divisor // 2 )
UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase = True
check_hidden_states_output(A_ , A_ , A_ )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
UpperCamelCase = True
check_hidden_states_output(A_ , A_ , A_ )
def __UpperCamelCase ( self ) -> Dict:
"""simple docstring"""
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*A_ )
def __UpperCamelCase ( self ) -> Optional[Any]:
"""simple docstring"""
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_semantic_segmentation(*A_ )
@slow
def __UpperCamelCase ( self ) -> Dict:
"""simple docstring"""
for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
UpperCamelCase = MobileViTVaModel.from_pretrained(A_ )
self.assertIsNotNone(A_ )
def A ( ) -> int:
'''simple docstring'''
UpperCamelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
return image
@require_torch
@require_vision
class lowercase ( unittest.TestCase ):
@cached_property
def __UpperCamelCase ( self ) -> Any:
"""simple docstring"""
return (
MobileViTImageProcessor.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256' )
if is_vision_available()
else None
)
@slow
def __UpperCamelCase ( self ) -> str:
"""simple docstring"""
UpperCamelCase = MobileViTVaForImageClassification.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256' ).to(
A_ )
UpperCamelCase = self.default_image_processor
UpperCamelCase = prepare_img()
UpperCamelCase = image_processor(images=A_ , return_tensors='pt' ).to(A_ )
# forward pass
with torch.no_grad():
UpperCamelCase = model(**A_ )
# verify the logits
UpperCamelCase = torch.Size((1, 1_000) )
self.assertEqual(outputs.logits.shape , A_ )
UpperCamelCase = torch.tensor([-1.6336e00, -7.3204e-02, -5.1883e-01] ).to(A_ )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , A_ , atol=1e-4 ) )
@slow
def __UpperCamelCase ( self ) -> List[Any]:
"""simple docstring"""
UpperCamelCase = MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3' )
UpperCamelCase = model.to(A_ )
UpperCamelCase = MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3' )
UpperCamelCase = prepare_img()
UpperCamelCase = image_processor(images=A_ , return_tensors='pt' ).to(A_ )
# forward pass
with torch.no_grad():
UpperCamelCase = model(**A_ )
UpperCamelCase = outputs.logits
# verify the logits
UpperCamelCase = torch.Size((1, 21, 32, 32) )
self.assertEqual(logits.shape , A_ )
UpperCamelCase = torch.tensor(
[
[[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]],
[[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]],
[[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]],
] , device=A_ , )
self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , A_ , atol=1e-4 ) )
@slow
def __UpperCamelCase ( self ) -> List[Any]:
"""simple docstring"""
UpperCamelCase = MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3' )
UpperCamelCase = model.to(A_ )
UpperCamelCase = MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3' )
UpperCamelCase = prepare_img()
UpperCamelCase = image_processor(images=A_ , return_tensors='pt' ).to(A_ )
# forward pass
with torch.no_grad():
UpperCamelCase = model(**A_ )
UpperCamelCase = outputs.logits.detach().cpu()
UpperCamelCase = image_processor.post_process_semantic_segmentation(outputs=A_ , target_sizes=[(50, 60)] )
UpperCamelCase = torch.Size((50, 60) )
self.assertEqual(segmentation[0].shape , A_ )
UpperCamelCase = image_processor.post_process_semantic_segmentation(outputs=A_ )
UpperCamelCase = torch.Size((32, 32) )
self.assertEqual(segmentation[0].shape , A_ )
| 3 |
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
# @@protoc_insertion_point(imports)
_UpperCAmelCase : Tuple = _symbol_database.Default()
_UpperCAmelCase : List[Any] = _descriptor_pool.Default().AddSerializedFile(
b"\n\x19sentencepiece_model.proto\x12\rsentencepiece\"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12\"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12\"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18\" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18. \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse\"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32\".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL\"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03"
)
_UpperCAmelCase : int = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "sentencepiece_model_pb2", _globals)
if _descriptor._USE_C_DESCRIPTORS is False:
_UpperCAmelCase : int = None
_UpperCAmelCase : List[str] = b"H\003"
# (generated by protobuf compiler, but `_TRAINERSPEC` is not defined)
# _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None
# _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001"
# _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None
# _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001"
_UpperCAmelCase : Optional[Any] = 45
_UpperCAmelCase : Any = 1_581
_UpperCAmelCase : Tuple = 1_517
_UpperCAmelCase : List[str] = 1_570
_UpperCAmelCase : int = 1_584
_UpperCAmelCase : List[Any] = 1_793
_UpperCAmelCase : Optional[int] = 1_795
_UpperCAmelCase : Any = 1_916
_UpperCAmelCase : Tuple = 1_864
_UpperCAmelCase : List[Any] = 1_905
_UpperCAmelCase : Union[str, Any] = 1_919
_UpperCAmelCase : str = 2_429
_UpperCAmelCase : Any = 2_208
_UpperCAmelCase : Dict = 2_418
_UpperCAmelCase : Optional[Any] = 2_323
_UpperCAmelCase : Tuple = 2_407
# @@protoc_insertion_point(module_scope)
| 3 | 1 |
"""simple docstring"""
def UpperCAmelCase__ (snake_case__ : str ):
"""simple docstring"""
return [
txt[:a] + txt[a].upper() + txt[a + 1 :]
for a in range(len(UpperCamelCase__ ) )
if txt[a].isalpha()
]
if __name__ == "__main__":
__import__('''doctest''').testmod()
| 609 |
def lowerCamelCase_ ( UpperCamelCase__ : str ) -> bool:
"""simple docstring"""
__lowerCamelCase = 0
for ch in input_str:
__lowerCamelCase = ord(UpperCamelCase__ )
__lowerCamelCase = pow(2 , UpperCamelCase__ )
# If we already turned on bit for current character's unicode
if bitmap >> ch_unicode & 1 == 1:
return False
bitmap |= ch_bit_index_on
return True
if __name__ == "__main__":
import doctest
doctest.testmod()
| 469 | 0 |
"""simple docstring"""
def __lowerCAmelCase( __UpperCAmelCase ,__UpperCAmelCase ):
"""simple docstring"""
return int((input_a, input_a).count(0 ) == 0 )
def __lowerCAmelCase( ):
"""simple docstring"""
assert and_gate(0 ,0 ) == 0
assert and_gate(0 ,1 ) == 0
assert and_gate(1 ,0 ) == 0
assert and_gate(1 ,1 ) == 1
if __name__ == "__main__":
test_and_gate()
print(and_gate(1, 0))
print(and_gate(0, 0))
print(and_gate(0, 1))
print(and_gate(1, 1))
| 283 | """simple docstring"""
from __future__ import annotations
SCREAMING_SNAKE_CASE = [
[-1, 0], # left
[0, -1], # down
[1, 0], # right
[0, 1], # up
]
def __lowerCAmelCase( __UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,):
"""simple docstring"""
_lowercase : List[str] = [
[0 for col in range(len(grid[0] ) )] for row in range(len(__UpperCAmelCase ) )
] # the reference grid
_lowercase : Optional[Any] = 1
_lowercase : Any = [
[0 for col in range(len(grid[0] ) )] for row in range(len(__UpperCAmelCase ) )
] # the action grid
_lowercase : List[Any] = init[0]
_lowercase : Optional[Any] = init[1]
_lowercase : Union[str, Any] = 0
_lowercase : Union[str, Any] = g + heuristic[x][y] # cost from starting cell to destination cell
_lowercase : Dict = [[f, g, x, y]]
_lowercase : Tuple = False # flag that is set when search is complete
_lowercase : Tuple = False # flag set if we can't find expand
while not found and not resign:
if len(__UpperCAmelCase ) == 0:
raise ValueError('Algorithm is unable to find solution' )
else: # to choose the least costliest action so as to move closer to the goal
cell.sort()
cell.reverse()
_lowercase : List[Any] = cell.pop()
_lowercase : Optional[Any] = next_cell[2]
_lowercase : List[str] = next_cell[3]
_lowercase : Optional[int] = next_cell[1]
if x == goal[0] and y == goal[1]:
_lowercase : Optional[Any] = True
else:
for i in range(len(__UpperCAmelCase ) ): # to try out different valid actions
_lowercase : Any = x + DIRECTIONS[i][0]
_lowercase : Union[str, Any] = y + DIRECTIONS[i][1]
if xa >= 0 and xa < len(__UpperCAmelCase ) and ya >= 0 and ya < len(grid[0] ):
if closed[xa][ya] == 0 and grid[xa][ya] == 0:
_lowercase : int = g + cost
_lowercase : List[str] = ga + heuristic[xa][ya]
cell.append([fa, ga, xa, ya] )
_lowercase : List[Any] = 1
_lowercase : Dict = i
_lowercase : Union[str, Any] = []
_lowercase : Optional[int] = goal[0]
_lowercase : Any = goal[1]
invpath.append([x, y] ) # we get the reverse path from here
while x != init[0] or y != init[1]:
_lowercase : str = x - DIRECTIONS[action[x][y]][0]
_lowercase : Any = y - DIRECTIONS[action[x][y]][1]
_lowercase : Dict = xa
_lowercase : Tuple = ya
invpath.append([x, y] )
_lowercase : List[str] = []
for i in range(len(__UpperCAmelCase ) ):
path.append(invpath[len(__UpperCAmelCase ) - 1 - i] )
return path, action
if __name__ == "__main__":
SCREAMING_SNAKE_CASE = [
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 1, 0],
]
SCREAMING_SNAKE_CASE = [0, 0]
# all coordinates are given in format [y,x]
SCREAMING_SNAKE_CASE = [len(grid) - 1, len(grid[0]) - 1]
SCREAMING_SNAKE_CASE = 1
# the cost map which pushes the path closer to the goal
SCREAMING_SNAKE_CASE = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]
for i in range(len(grid)):
for j in range(len(grid[0])):
SCREAMING_SNAKE_CASE = abs(i - goal[0]) + abs(j - goal[1])
if grid[i][j] == 1:
# added extra penalty in the heuristic map
SCREAMING_SNAKE_CASE = 99
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = search(grid, init, goal, cost, heuristic)
print('ACTION MAP')
for i in range(len(action)):
print(action[i])
for i in range(len(path)):
print(path[i])
| 283 | 1 |
'''simple docstring'''
from typing import Dict, List
from nltk.translate import gleu_score
import datasets
from datasets import MetricInfo
__SCREAMING_SNAKE_CASE :Optional[int] = '''\
@misc{wu2016googles,
title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},
author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey
and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin
Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto
Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and
Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes
and Jeffrey Dean},
year={2016},
eprint={1609.08144},
archivePrefix={arXiv},
primaryClass={cs.CL}
}
'''
__SCREAMING_SNAKE_CASE :str = '''\
The BLEU score has some undesirable properties when used for single
sentences, as it was designed to be a corpus measure. We therefore
use a slightly different score for our RL experiments which we call
the \'GLEU score\'. For the GLEU score, we record all sub-sequences of
1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then
compute a recall, which is the ratio of the number of matching n-grams
to the number of total n-grams in the target (ground truth) sequence,
and a precision, which is the ratio of the number of matching n-grams
to the number of total n-grams in the generated output sequence. Then
GLEU score is simply the minimum of recall and precision. This GLEU
score\'s range is always between 0 (no matches) and 1 (all match) and
it is symmetrical when switching output and target. According to
our experiments, GLEU score correlates quite well with the BLEU
metric on a corpus level but does not have its drawbacks for our per
sentence reward objective.
'''
__SCREAMING_SNAKE_CASE :int = '''\
Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.
Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching
tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.
Args:
predictions (list of str): list of translations to score.
Each translation should be tokenized into a list of tokens.
references (list of list of str): list of lists of references for each translation.
Each reference should be tokenized into a list of tokens.
min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.
max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.
Returns:
\'google_bleu\': google_bleu score
Examples:
Example 1:
>>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',
... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',
... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']
>>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',
... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',
... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']
>>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',
... \'interested\', \'in\', \'world\', \'history\']
>>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',
... \'because\', \'he\', \'read\', \'the\', \'book\']
>>> list_of_references = [[ref1a], [ref2a]]
>>> hypotheses = [hyp1, hyp2]
>>> google_bleu = datasets.load_metric("google_bleu")
>>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
>>> print(round(results["google_bleu"], 2))
0.44
Example 2:
>>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',
... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',
... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']
>>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',
... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',
... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']
>>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',
... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',
... \'heed\', \'the\', \'cat\', \'commands\']
>>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',
... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',
... \'of\', \'the\', \'cat\']
>>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',
... \'interested\', \'in\', \'world\', \'history\']
>>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',
... \'because\', \'he\', \'read\', \'the\', \'book\']
>>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
>>> hypotheses = [hyp1, hyp2]
>>> google_bleu = datasets.load_metric("google_bleu")
>>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
>>> print(round(results["google_bleu"], 2))
0.61
Example 3:
>>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',
... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',
... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']
>>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',
... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',
... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']
>>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',
... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',
... \'heed\', \'the\', \'cat\', \'commands\']
>>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',
... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',
... \'of\', \'the\', \'cat\']
>>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',
... \'interested\', \'in\', \'world\', \'history\']
>>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',
... \'because\', \'he\', \'read\', \'the\', \'book\']
>>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
>>> hypotheses = [hyp1, hyp2]
>>> google_bleu = datasets.load_metric("google_bleu")
>>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)
>>> print(round(results["google_bleu"], 2))
0.53
Example 4:
>>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',
... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',
... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']
>>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',
... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',
... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']
>>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',
... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',
... \'heed\', \'the\', \'cat\', \'commands\']
>>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',
... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',
... \'of\', \'the\', \'cat\']
>>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',
... \'interested\', \'in\', \'world\', \'history\']
>>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',
... \'because\', \'he\', \'read\', \'the\', \'book\']
>>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
>>> hypotheses = [hyp1, hyp2]
>>> google_bleu = datasets.load_metric("google_bleu")
>>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)
>>> print(round(results["google_bleu"], 2))
0.4
'''
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class A_ ( datasets.Metric ):
def lowercase ( self : int ):
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"predictions": datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ),
"references": datasets.Sequence(
datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ) , id="references" ),
} ) , )
def lowercase ( self : Union[str, Any] , snake_case_ : List[List[List[str]]] , snake_case_ : List[List[str]] , snake_case_ : int = 1 , snake_case_ : int = 4 , ):
return {
"google_bleu": gleu_score.corpus_gleu(
list_of_references=snake_case_ , hypotheses=snake_case_ , min_len=snake_case_ , max_len=snake_case_ )
}
| 236 |
'''simple docstring'''
import math
import tensorflow as tf
from packaging import version
def UpperCAmelCase_ ( __lowercase : Optional[Any] ) -> List[str]:
'''simple docstring'''
_UpperCAmelCase = tf.convert_to_tensor(__lowercase )
_UpperCAmelCase = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) , x.dtype ) ))
return x * cdf
def UpperCAmelCase_ ( __lowercase : Optional[Any] ) -> List[str]:
'''simple docstring'''
_UpperCAmelCase = tf.convert_to_tensor(__lowercase )
_UpperCAmelCase = tf.cast(math.pi , x.dtype )
_UpperCAmelCase = tf.cast(0.04_4715 , x.dtype )
_UpperCAmelCase = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(__lowercase , 3 )) ))
return x * cdf
def UpperCAmelCase_ ( __lowercase : str ) -> List[str]:
'''simple docstring'''
_UpperCAmelCase = tf.convert_to_tensor(__lowercase )
return x * tf.tanh(tf.math.softplus(__lowercase ) )
def UpperCAmelCase_ ( __lowercase : Optional[int] ) -> Optional[int]:
'''simple docstring'''
_UpperCAmelCase = tf.convert_to_tensor(__lowercase )
_UpperCAmelCase = tf.cast(0.04_4715 , x.dtype )
_UpperCAmelCase = tf.cast(0.79_7884_5608 , x.dtype )
return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) ))
def UpperCAmelCase_ ( __lowercase : Optional[Any] ) -> List[Any]:
'''simple docstring'''
_UpperCAmelCase = tf.convert_to_tensor(__lowercase )
_UpperCAmelCase = tf.cast(1.702 , x.dtype )
return x * tf.math.sigmoid(coeff * x )
def UpperCAmelCase_ ( __lowercase : List[str] ) -> Optional[int]:
'''simple docstring'''
return tf.clip_by_value(_gelu(__lowercase ) , -10 , 10 )
def UpperCAmelCase_ ( __lowercase : int , __lowercase : str=-1 ) -> str:
'''simple docstring'''
_UpperCAmelCase , _UpperCAmelCase = tf.split(__lowercase , 2 , axis=__lowercase )
return a * tf.math.sigmoid(__lowercase )
if version.parse(tf.version.VERSION) >= version.parse('''2.4'''):
def UpperCAmelCase_ ( __lowercase : Dict ) -> int:
'''simple docstring'''
return tf.keras.activations.gelu(__lowercase , approximate=__lowercase )
__SCREAMING_SNAKE_CASE :Dict = tf.keras.activations.gelu
__SCREAMING_SNAKE_CASE :str = approximate_gelu_wrap
else:
__SCREAMING_SNAKE_CASE :Optional[int] = _gelu
__SCREAMING_SNAKE_CASE :str = _gelu_new
__SCREAMING_SNAKE_CASE :Tuple = {
'''gelu''': gelu,
'''gelu_10''': gelu_aa,
'''gelu_fast''': gelu_fast,
'''gelu_new''': gelu_new,
'''glu''': glu,
'''mish''': mish,
'''quick_gelu''': quick_gelu,
'''relu''': tf.keras.activations.relu,
'''sigmoid''': tf.keras.activations.sigmoid,
'''silu''': tf.keras.activations.swish,
'''swish''': tf.keras.activations.swish,
'''tanh''': tf.keras.activations.tanh,
}
def UpperCAmelCase_ ( __lowercase : Optional[Any] ) -> Any:
'''simple docstring'''
if activation_string in ACTaFN:
return ACTaFN[activation_string]
else:
raise KeyError(f'function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}' )
| 236 | 1 |
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():
_lowerCamelCase : Optional[Any] = '''pt'''
elif is_tf_available():
_lowerCamelCase : List[str] = '''tf'''
else:
_lowerCamelCase : List[str] = '''jax'''
class lowercase ( a , unittest.TestCase ):
lowercase__ : Union[str, Any] = ByTaTokenizer
lowercase__ : str = False
def __snake_case( self : Tuple ) -> int:
'''simple docstring'''
super().setUp()
SCREAMING_SNAKE_CASE = ByTaTokenizer()
tokenizer.save_pretrained(self.tmpdirname )
@cached_property
def __snake_case( self : int ) -> Optional[int]:
'''simple docstring'''
return ByTaTokenizer.from_pretrained("google/byt5-small" )
def __snake_case( self : List[str] , **_UpperCamelCase : str ) -> ByTaTokenizer:
'''simple docstring'''
return self.tokenizer_class.from_pretrained(self.tmpdirname , **_UpperCamelCase )
def __snake_case( self : int , _UpperCamelCase : Dict , _UpperCamelCase : Union[str, Any]=False , _UpperCamelCase : Optional[int]=20 , _UpperCamelCase : Dict=5 ) -> Tuple[str, list]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = []
for i in range(len(_UpperCamelCase ) ):
try:
SCREAMING_SNAKE_CASE = tokenizer.decode([i] , clean_up_tokenization_spaces=_UpperCamelCase )
except UnicodeDecodeError:
pass
toks.append((i, tok) )
SCREAMING_SNAKE_CASE = list(filter(lambda _UpperCamelCase : re.match(R"^[ a-zA-Z]+$" , t[1] ) , _UpperCamelCase ) )
SCREAMING_SNAKE_CASE = list(filter(lambda _UpperCamelCase : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=_UpperCamelCase ) , _UpperCamelCase ) )
if max_length is not None and len(_UpperCamelCase ) > max_length:
SCREAMING_SNAKE_CASE = toks[:max_length]
if min_length is not None and len(_UpperCamelCase ) < min_length and len(_UpperCamelCase ) > 0:
while len(_UpperCamelCase ) < min_length:
SCREAMING_SNAKE_CASE = toks + toks
# toks_str = [t[1] for t in toks]
SCREAMING_SNAKE_CASE = [t[0] for t in toks]
# Ensure consistency
SCREAMING_SNAKE_CASE = tokenizer.decode(_UpperCamelCase , clean_up_tokenization_spaces=_UpperCamelCase )
if " " not in output_txt and len(_UpperCamelCase ) > 1:
SCREAMING_SNAKE_CASE = (
tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=_UpperCamelCase )
+ " "
+ tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=_UpperCamelCase )
)
if with_prefix_space:
SCREAMING_SNAKE_CASE = " " + output_txt
SCREAMING_SNAKE_CASE = tokenizer.encode(_UpperCamelCase , add_special_tokens=_UpperCamelCase )
return output_txt, output_ids
def __snake_case( self : List[str] ) -> Optional[int]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = self.ta_base_tokenizer
SCREAMING_SNAKE_CASE = tokenizer(["hi</s>", "I went to the gym</s>", "</s>"] )
SCREAMING_SNAKE_CASE = tokenizer(["hi", "I went to the gym", ""] )
self.assertListEqual(batch_with_eos_added["input_ids"] , batch_without_eos_added["input_ids"] )
def __snake_case( self : int ) -> List[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = self.ta_base_tokenizer
SCREAMING_SNAKE_CASE = "Unicode €."
SCREAMING_SNAKE_CASE = tokenizer(_UpperCamelCase )
SCREAMING_SNAKE_CASE = [88, 113, 108, 102, 114, 103, 104, 35, 229, 133, 175, 49, 1]
self.assertEqual(encoded["input_ids"] , _UpperCamelCase )
# decoding
SCREAMING_SNAKE_CASE = tokenizer.decode(_UpperCamelCase )
self.assertEqual(_UpperCamelCase , "Unicode €.</s>" )
SCREAMING_SNAKE_CASE = tokenizer("e è é ê ë" )
SCREAMING_SNAKE_CASE = [104, 35, 198, 171, 35, 198, 172, 35, 198, 173, 35, 198, 174, 1]
self.assertEqual(encoded["input_ids"] , _UpperCamelCase )
# decoding
SCREAMING_SNAKE_CASE = tokenizer.decode(_UpperCamelCase )
self.assertEqual(_UpperCamelCase , "e è é ê ë</s>" )
# encode/decode, but with `encode` instead of `__call__`
self.assertEqual(tokenizer.decode(tokenizer.encode("e è é ê ë" ) ) , "e è é ê ë</s>" )
def __snake_case( self : Optional[Any] ) -> Any:
'''simple docstring'''
SCREAMING_SNAKE_CASE = self.ta_base_tokenizer
SCREAMING_SNAKE_CASE = ["A long paragraph for summarization.", "Another paragraph for summarization."]
# fmt: off
SCREAMING_SNAKE_CASE = [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 1, 0]
# fmt: on
SCREAMING_SNAKE_CASE = tokenizer(_UpperCamelCase , padding=_UpperCamelCase , return_tensors=_UpperCamelCase )
self.assertIsInstance(_UpperCamelCase , _UpperCamelCase )
if FRAMEWORK != "jax":
SCREAMING_SNAKE_CASE = list(batch.input_ids.numpy()[0] )
else:
SCREAMING_SNAKE_CASE = list(batch.input_ids.tolist()[0] )
self.assertListEqual(_UpperCamelCase , _UpperCamelCase )
self.assertEqual((2, 37) , batch.input_ids.shape )
self.assertEqual((2, 37) , batch.attention_mask.shape )
def __snake_case( self : str ) -> Dict:
'''simple docstring'''
SCREAMING_SNAKE_CASE = self.ta_base_tokenizer
SCREAMING_SNAKE_CASE = ["A long paragraph for summarization.", "Another paragraph for summarization."]
SCREAMING_SNAKE_CASE = tokenizer(_UpperCamelCase , padding=_UpperCamelCase , return_tensors=_UpperCamelCase )
# check if input_ids are returned and no decoder_input_ids
self.assertIn("input_ids" , _UpperCamelCase )
self.assertIn("attention_mask" , _UpperCamelCase )
self.assertNotIn("decoder_input_ids" , _UpperCamelCase )
self.assertNotIn("decoder_attention_mask" , _UpperCamelCase )
def __snake_case( self : Optional[Any] ) -> Optional[int]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = self.ta_base_tokenizer
SCREAMING_SNAKE_CASE = [
"Summary of the text.",
"Another summary.",
]
SCREAMING_SNAKE_CASE = tokenizer(
text_target=_UpperCamelCase , max_length=32 , padding="max_length" , truncation=_UpperCamelCase , return_tensors=_UpperCamelCase )
self.assertEqual(32 , targets["input_ids"].shape[1] )
def __snake_case( self : List[Any] ) -> List[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = self.ta_base_tokenizer
SCREAMING_SNAKE_CASE = ["A long paragraph for summarization. </s>"]
SCREAMING_SNAKE_CASE = ["Summary of the text. </s>"]
# fmt: off
SCREAMING_SNAKE_CASE = [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 35, 1]
SCREAMING_SNAKE_CASE = [86, 120, 112, 112, 100, 117, 124, 35, 114, 105, 35, 119, 107, 104, 35, 119, 104, 123, 119, 49, 35, 1]
# fmt: on
SCREAMING_SNAKE_CASE = tokenizer(_UpperCamelCase , text_target=_UpperCamelCase )
self.assertEqual(_UpperCamelCase , batch["input_ids"][0] )
self.assertEqual(_UpperCamelCase , batch["labels"][0] )
def __snake_case( self : Tuple ) -> Tuple:
'''simple docstring'''
SCREAMING_SNAKE_CASE = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(F"{tokenizer.__class__.__name__}" ):
self.assertNotEqual(tokenizer.model_max_length , 42 )
# Now let's start the test
SCREAMING_SNAKE_CASE = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(F"{tokenizer.__class__.__name__}" ):
# Isolate this from the other tests because we save additional tokens/etc
SCREAMING_SNAKE_CASE = tempfile.mkdtemp()
SCREAMING_SNAKE_CASE = " He is very happy, UNwant\u00E9d,running"
SCREAMING_SNAKE_CASE = tokenizer.encode(_UpperCamelCase , add_special_tokens=_UpperCamelCase )
tokenizer.save_pretrained(_UpperCamelCase )
SCREAMING_SNAKE_CASE = tokenizer.__class__.from_pretrained(_UpperCamelCase )
SCREAMING_SNAKE_CASE = after_tokenizer.encode(_UpperCamelCase , add_special_tokens=_UpperCamelCase )
self.assertListEqual(_UpperCamelCase , _UpperCamelCase )
shutil.rmtree(_UpperCamelCase )
SCREAMING_SNAKE_CASE = self.get_tokenizers(model_max_length=42 )
for tokenizer in tokenizers:
with self.subTest(F"{tokenizer.__class__.__name__}" ):
# Isolate this from the other tests because we save additional tokens/etc
SCREAMING_SNAKE_CASE = tempfile.mkdtemp()
SCREAMING_SNAKE_CASE = " He is very happy, UNwant\u00E9d,running"
tokenizer.add_tokens(["bim", "bambam"] )
SCREAMING_SNAKE_CASE = tokenizer.additional_special_tokens
additional_special_tokens.append("new_additional_special_token" )
tokenizer.add_special_tokens({"additional_special_tokens": additional_special_tokens} )
SCREAMING_SNAKE_CASE = tokenizer.encode(_UpperCamelCase , add_special_tokens=_UpperCamelCase )
tokenizer.save_pretrained(_UpperCamelCase )
SCREAMING_SNAKE_CASE = tokenizer.__class__.from_pretrained(_UpperCamelCase )
SCREAMING_SNAKE_CASE = after_tokenizer.encode(_UpperCamelCase , add_special_tokens=_UpperCamelCase )
self.assertListEqual(_UpperCamelCase , _UpperCamelCase )
self.assertIn("new_additional_special_token" , after_tokenizer.additional_special_tokens )
self.assertEqual(after_tokenizer.model_max_length , 42 )
SCREAMING_SNAKE_CASE = tokenizer.__class__.from_pretrained(_UpperCamelCase , model_max_length=43 )
self.assertEqual(tokenizer.model_max_length , 43 )
shutil.rmtree(_UpperCamelCase )
def __snake_case( self : str ) -> Union[str, Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = []
if self.test_slow_tokenizer:
tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) )
if self.test_rust_tokenizer:
tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) )
for tokenizer_class, tokenizer_utils in tokenizer_list:
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer_utils.save_pretrained(_UpperCamelCase )
with open(os.path.join(_UpperCamelCase , "special_tokens_map.json" ) , encoding="utf-8" ) as json_file:
SCREAMING_SNAKE_CASE = json.load(_UpperCamelCase )
with open(os.path.join(_UpperCamelCase , "tokenizer_config.json" ) , encoding="utf-8" ) as json_file:
SCREAMING_SNAKE_CASE = json.load(_UpperCamelCase )
SCREAMING_SNAKE_CASE = [F"<extra_id_{i}>" for i in range(125 )]
SCREAMING_SNAKE_CASE = added_tokens_extra_ids + [
"an_additional_special_token"
]
SCREAMING_SNAKE_CASE = added_tokens_extra_ids + [
"an_additional_special_token"
]
with open(os.path.join(_UpperCamelCase , "special_tokens_map.json" ) , "w" , encoding="utf-8" ) as outfile:
json.dump(_UpperCamelCase , _UpperCamelCase )
with open(os.path.join(_UpperCamelCase , "tokenizer_config.json" ) , "w" , encoding="utf-8" ) as outfile:
json.dump(_UpperCamelCase , _UpperCamelCase )
# 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
SCREAMING_SNAKE_CASE = tokenizer_class.from_pretrained(
_UpperCamelCase , )
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
SCREAMING_SNAKE_CASE = added_tokens_extra_ids + [AddedToken("a_new_additional_special_token" , lstrip=_UpperCamelCase )]
SCREAMING_SNAKE_CASE = tokenizer_class.from_pretrained(
_UpperCamelCase , additional_special_tokens=_UpperCamelCase , )
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 __snake_case( self : Optional[Any] ) -> List[str]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = []
if self.test_slow_tokenizer:
tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) )
if self.test_rust_tokenizer:
tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) )
for tokenizer_class, tokenizer_utils in tokenizer_list:
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer_utils.save_pretrained(_UpperCamelCase )
SCREAMING_SNAKE_CASE = tokenizer_class.from_pretrained(_UpperCamelCase )
self.assertTrue(tokenizer.decode([255] ) == "" )
def __snake_case( self : str ) -> Optional[int]:
'''simple docstring'''
pass
def __snake_case( self : List[Any] ) -> str:
'''simple docstring'''
pass
def __snake_case( self : Any ) -> int:
'''simple docstring'''
pass
def __snake_case( self : Dict ) -> int:
'''simple docstring'''
pass
def __snake_case( self : Optional[Any] ) -> Optional[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = self.get_tokenizers(fast=_UpperCamelCase , do_lower_case=_UpperCamelCase )
for tokenizer in tokenizers:
with self.subTest(F"{tokenizer.__class__.__name__}" ):
SCREAMING_SNAKE_CASE = ["t", "h", "i", "s", " ", "i", "s", " ", "a", " ", "t", "e", "x", "t", "</s>"]
SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_string(_UpperCamelCase )
self.assertIsInstance(_UpperCamelCase , _UpperCamelCase )
def __snake_case( self : int ) -> str:
'''simple docstring'''
SCREAMING_SNAKE_CASE = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(F"{tokenizer.__class__.__name__}" ):
SCREAMING_SNAKE_CASE = [
"bos_token",
"eos_token",
"unk_token",
"sep_token",
"pad_token",
"cls_token",
"mask_token",
]
SCREAMING_SNAKE_CASE = 0
SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(
_UpperCamelCase , skip_special_tokens=_UpperCamelCase )
for attr in attributes_list:
setattr(_UpperCamelCase , attr + "_id" , _UpperCamelCase )
self.assertEqual(getattr(_UpperCamelCase , _UpperCamelCase ) , _UpperCamelCase )
self.assertEqual(getattr(_UpperCamelCase , attr + "_id" ) , _UpperCamelCase )
setattr(_UpperCamelCase , attr + "_id" , _UpperCamelCase )
self.assertEqual(getattr(_UpperCamelCase , _UpperCamelCase ) , _UpperCamelCase )
self.assertEqual(getattr(_UpperCamelCase , attr + "_id" ) , _UpperCamelCase )
setattr(_UpperCamelCase , "additional_special_tokens_ids" , [] )
self.assertListEqual(getattr(_UpperCamelCase , "additional_special_tokens" ) , [] )
self.assertListEqual(getattr(_UpperCamelCase , "additional_special_tokens_ids" ) , [] )
setattr(_UpperCamelCase , "additional_special_tokens_ids" , [token_id_to_test_setters] )
self.assertListEqual(getattr(_UpperCamelCase , "additional_special_tokens" ) , [token_to_test_setters] )
self.assertListEqual(getattr(_UpperCamelCase , "additional_special_tokens_ids" ) , [token_id_to_test_setters] )
| 647 | import functools
def __lowerCamelCase (UpperCAmelCase__ : list[int] , UpperCAmelCase__ : list[int] ):
# Validation
if not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) or not all(isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) for day in days ):
raise ValueError("The parameter days should be a list of integers" )
if len(UpperCAmelCase__ ) != 3 or not all(isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) for cost in costs ):
raise ValueError("The parameter costs should be a list of three integers" )
if len(UpperCAmelCase__ ) == 0:
return 0
if min(UpperCAmelCase__ ) <= 0:
raise ValueError("All days elements should be greater than 0" )
if max(UpperCAmelCase__ ) >= 3_6_6:
raise ValueError("All days elements should be less than 366" )
SCREAMING_SNAKE_CASE = set(UpperCAmelCase__ )
@functools.cache
def dynamic_programming(UpperCAmelCase__ : int ) -> int:
if index > 3_6_5:
return 0
if index not in days_set:
return dynamic_programming(index + 1 )
return min(
costs[0] + dynamic_programming(index + 1 ) , costs[1] + dynamic_programming(index + 7 ) , costs[2] + dynamic_programming(index + 3_0 ) , )
return dynamic_programming(1 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 647 | 1 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__snake_case :Optional[Any] =logging.get_logger(__name__)
__snake_case :Tuple ={
'transfo-xl-wt103': 'https://huggingface.co/transfo-xl-wt103/resolve/main/config.json',
}
class lowerCAmelCase__ ( _lowerCamelCase ):
A_ : Any = 'transfo-xl'
A_ : Dict = ['mems']
A_ : int = {
'n_token': 'vocab_size',
'hidden_size': 'd_model',
'num_attention_heads': 'n_head',
'num_hidden_layers': 'n_layer',
}
def __init__( self : Optional[Any] , __UpperCamelCase : str=267_735 , __UpperCamelCase : int=[20_000, 40_000, 200_000] , __UpperCamelCase : List[str]=1_024 , __UpperCamelCase : Union[str, Any]=1_024 , __UpperCamelCase : Optional[Any]=16 , __UpperCamelCase : Dict=64 , __UpperCamelCase : Optional[Any]=4_096 , __UpperCamelCase : int=4 , __UpperCamelCase : List[str]=False , __UpperCamelCase : Optional[int]=18 , __UpperCamelCase : int=1_600 , __UpperCamelCase : Dict=1_000 , __UpperCamelCase : Optional[Any]=True , __UpperCamelCase : Optional[Any]=True , __UpperCamelCase : Optional[Any]=0 , __UpperCamelCase : Any=-1 , __UpperCamelCase : Any=True , __UpperCamelCase : List[Any]=0.1 , __UpperCamelCase : str=0.0 , __UpperCamelCase : Dict=True , __UpperCamelCase : int="normal" , __UpperCamelCase : List[Any]=0.0_1 , __UpperCamelCase : str=0.0_1 , __UpperCamelCase : Any=0.0_2 , __UpperCamelCase : str=1e-5 , __UpperCamelCase : Optional[int]=0 , **__UpperCamelCase : Any , ) -> int:
A = vocab_size
A = []
self.cutoffs.extend(__UpperCamelCase )
if proj_share_all_but_first:
A = [False] + [True] * len(self.cutoffs )
else:
A = [False] + [False] * len(self.cutoffs )
A = d_model
A = d_embed
A = d_head
A = d_inner
A = div_val
A = pre_lnorm
A = n_layer
A = n_head
A = mem_len
A = same_length
A = attn_type
A = clamp_len
A = sample_softmax
A = adaptive
A = dropout
A = dropatt
A = untie_r
A = init
A = init_range
A = proj_init_std
A = init_std
A = layer_norm_epsilon
super().__init__(eos_token_id=__UpperCamelCase , **__UpperCamelCase )
@property
def __UpperCamelCase ( self : Any ) -> Optional[int]:
# Message copied from Transformer-XL documentation
logger.info(f'''The model {self.model_type} is one of the few models that has no sequence length limit.''' )
return -1
@max_position_embeddings.setter
def __UpperCamelCase ( self : List[Any] , __UpperCamelCase : List[Any] ) -> List[Any]:
# Message copied from Transformer-XL documentation
raise NotImplementedError(
f'''The model {self.model_type} is one of the few models that has no sequence length limit.''' ) | 106 |
import unittest
from diffusers.pipelines.pipeline_utils import is_safetensors_compatible
class lowerCAmelCase__ ( unittest.TestCase ):
def __UpperCamelCase ( self : List[str] ) -> Any:
A = [
'safety_checker/pytorch_model.bin',
'safety_checker/model.safetensors',
'vae/diffusion_pytorch_model.bin',
'vae/diffusion_pytorch_model.safetensors',
'text_encoder/pytorch_model.bin',
'text_encoder/model.safetensors',
'unet/diffusion_pytorch_model.bin',
'unet/diffusion_pytorch_model.safetensors',
]
self.assertTrue(is_safetensors_compatible(__UpperCamelCase ) )
def __UpperCamelCase ( self : str ) -> List[Any]:
A = [
'unet/diffusion_pytorch_model.bin',
'unet/diffusion_pytorch_model.safetensors',
]
self.assertTrue(is_safetensors_compatible(__UpperCamelCase ) )
def __UpperCamelCase ( self : Any ) -> Tuple:
A = [
'safety_checker/pytorch_model.bin',
'safety_checker/model.safetensors',
'vae/diffusion_pytorch_model.bin',
'vae/diffusion_pytorch_model.safetensors',
'text_encoder/pytorch_model.bin',
'text_encoder/model.safetensors',
'unet/diffusion_pytorch_model.bin',
# Removed: 'unet/diffusion_pytorch_model.safetensors',
]
self.assertFalse(is_safetensors_compatible(__UpperCamelCase ) )
def __UpperCamelCase ( self : Dict ) -> Any:
A = [
'text_encoder/pytorch_model.bin',
'text_encoder/model.safetensors',
]
self.assertTrue(is_safetensors_compatible(__UpperCamelCase ) )
def __UpperCamelCase ( self : Optional[int] ) -> List[str]:
A = [
'safety_checker/pytorch_model.bin',
'safety_checker/model.safetensors',
'vae/diffusion_pytorch_model.bin',
'vae/diffusion_pytorch_model.safetensors',
'text_encoder/pytorch_model.bin',
# Removed: 'text_encoder/model.safetensors',
'unet/diffusion_pytorch_model.bin',
'unet/diffusion_pytorch_model.safetensors',
]
self.assertFalse(is_safetensors_compatible(__UpperCamelCase ) )
def __UpperCamelCase ( self : List[str] ) -> List[str]:
A = [
'safety_checker/pytorch_model.fp16.bin',
'safety_checker/model.fp16.safetensors',
'vae/diffusion_pytorch_model.fp16.bin',
'vae/diffusion_pytorch_model.fp16.safetensors',
'text_encoder/pytorch_model.fp16.bin',
'text_encoder/model.fp16.safetensors',
'unet/diffusion_pytorch_model.fp16.bin',
'unet/diffusion_pytorch_model.fp16.safetensors',
]
A = 'fp16'
self.assertTrue(is_safetensors_compatible(__UpperCamelCase , variant=__UpperCamelCase ) )
def __UpperCamelCase ( self : Optional[Any] ) -> Optional[Any]:
A = [
'unet/diffusion_pytorch_model.fp16.bin',
'unet/diffusion_pytorch_model.fp16.safetensors',
]
A = 'fp16'
self.assertTrue(is_safetensors_compatible(__UpperCamelCase , variant=__UpperCamelCase ) )
def __UpperCamelCase ( self : int ) -> Optional[int]:
# pass variant but use the non-variant filenames
A = [
'unet/diffusion_pytorch_model.bin',
'unet/diffusion_pytorch_model.safetensors',
]
A = 'fp16'
self.assertTrue(is_safetensors_compatible(__UpperCamelCase , variant=__UpperCamelCase ) )
def __UpperCamelCase ( self : Any ) -> List[str]:
A = [
'safety_checker/pytorch_model.fp16.bin',
'safety_checker/model.fp16.safetensors',
'vae/diffusion_pytorch_model.fp16.bin',
'vae/diffusion_pytorch_model.fp16.safetensors',
'text_encoder/pytorch_model.fp16.bin',
'text_encoder/model.fp16.safetensors',
'unet/diffusion_pytorch_model.fp16.bin',
# Removed: 'unet/diffusion_pytorch_model.fp16.safetensors',
]
A = 'fp16'
self.assertFalse(is_safetensors_compatible(__UpperCamelCase , variant=__UpperCamelCase ) )
def __UpperCamelCase ( self : Optional[Any] ) -> Optional[int]:
A = [
'text_encoder/pytorch_model.fp16.bin',
'text_encoder/model.fp16.safetensors',
]
A = 'fp16'
self.assertTrue(is_safetensors_compatible(__UpperCamelCase , variant=__UpperCamelCase ) )
def __UpperCamelCase ( self : List[str] ) -> int:
# pass variant but use the non-variant filenames
A = [
'text_encoder/pytorch_model.bin',
'text_encoder/model.safetensors',
]
A = 'fp16'
self.assertTrue(is_safetensors_compatible(__UpperCamelCase , variant=__UpperCamelCase ) )
def __UpperCamelCase ( self : List[str] ) -> Optional[Any]:
A = [
'safety_checker/pytorch_model.fp16.bin',
'safety_checker/model.fp16.safetensors',
'vae/diffusion_pytorch_model.fp16.bin',
'vae/diffusion_pytorch_model.fp16.safetensors',
'text_encoder/pytorch_model.fp16.bin',
# 'text_encoder/model.fp16.safetensors',
'unet/diffusion_pytorch_model.fp16.bin',
'unet/diffusion_pytorch_model.fp16.safetensors',
]
A = 'fp16'
self.assertFalse(is_safetensors_compatible(__UpperCamelCase , variant=__UpperCamelCase ) ) | 106 | 1 |
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import RoFormerConfig, is_tf_available
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TFRoFormerForCausalLM,
TFRoFormerForMaskedLM,
TFRoFormerForMultipleChoice,
TFRoFormerForQuestionAnswering,
TFRoFormerForSequenceClassification,
TFRoFormerForTokenClassification,
TFRoFormerModel,
)
from transformers.models.roformer.modeling_tf_roformer import (
TFRoFormerSelfAttention,
TFRoFormerSinusoidalPositionalEmbedding,
)
class UpperCamelCase :
"""simple docstring"""
def __init__( self , lowercase__ , lowercase__=13 , lowercase__=7 , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=99 , lowercase__=32 , lowercase__=2 , lowercase__=4 , lowercase__=37 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=512 , lowercase__=16 , lowercase__=2 , lowercase__=0.02 , lowercase__=3 , lowercase__=4 , lowercase__=None , ) -> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE = parent
SCREAMING_SNAKE_CASE = 13
SCREAMING_SNAKE_CASE = 7
SCREAMING_SNAKE_CASE = True
SCREAMING_SNAKE_CASE = True
SCREAMING_SNAKE_CASE = True
SCREAMING_SNAKE_CASE = True
SCREAMING_SNAKE_CASE = 99
SCREAMING_SNAKE_CASE = 32
SCREAMING_SNAKE_CASE = 2
SCREAMING_SNAKE_CASE = 4
SCREAMING_SNAKE_CASE = 37
SCREAMING_SNAKE_CASE = 'gelu'
SCREAMING_SNAKE_CASE = 0.1
SCREAMING_SNAKE_CASE = 0.1
SCREAMING_SNAKE_CASE = 512
SCREAMING_SNAKE_CASE = 16
SCREAMING_SNAKE_CASE = 2
SCREAMING_SNAKE_CASE = 0.02
SCREAMING_SNAKE_CASE = 3
SCREAMING_SNAKE_CASE = 4
SCREAMING_SNAKE_CASE = None
def A ( self ) -> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
SCREAMING_SNAKE_CASE = None
if self.use_input_mask:
SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] )
SCREAMING_SNAKE_CASE = None
if self.use_token_type_ids:
SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
SCREAMING_SNAKE_CASE = None
SCREAMING_SNAKE_CASE = None
SCREAMING_SNAKE_CASE = None
if self.use_labels:
SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size )
SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices )
SCREAMING_SNAKE_CASE = RoFormerConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=lowercase__ , )
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def A ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) -> List[str]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = TFRoFormerModel(config=lowercase__ )
SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
SCREAMING_SNAKE_CASE = [input_ids, input_mask]
SCREAMING_SNAKE_CASE = model(lowercase__ )
SCREAMING_SNAKE_CASE = model(lowercase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def A ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) -> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE = True
SCREAMING_SNAKE_CASE = TFRoFormerForCausalLM(config=lowercase__ )
SCREAMING_SNAKE_CASE = {
'input_ids': input_ids,
'attention_mask': input_mask,
'token_type_ids': token_type_ids,
}
SCREAMING_SNAKE_CASE = model(lowercase__ )['logits']
self.parent.assertListEqual(
list(prediction_scores.numpy().shape ) , [self.batch_size, self.seq_length, self.vocab_size] )
def A ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) -> List[str]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = TFRoFormerForMaskedLM(config=lowercase__ )
SCREAMING_SNAKE_CASE = {
'input_ids': input_ids,
'attention_mask': input_mask,
'token_type_ids': token_type_ids,
}
SCREAMING_SNAKE_CASE = model(lowercase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def A ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) -> List[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.num_labels
SCREAMING_SNAKE_CASE = TFRoFormerForSequenceClassification(config=lowercase__ )
SCREAMING_SNAKE_CASE = {
'input_ids': input_ids,
'attention_mask': input_mask,
'token_type_ids': token_type_ids,
}
SCREAMING_SNAKE_CASE = model(lowercase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def A ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) -> Optional[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.num_choices
SCREAMING_SNAKE_CASE = TFRoFormerForMultipleChoice(config=lowercase__ )
SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(lowercase__ , 1 ) , (1, self.num_choices, 1) )
SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(lowercase__ , 1 ) , (1, self.num_choices, 1) )
SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(lowercase__ , 1 ) , (1, self.num_choices, 1) )
SCREAMING_SNAKE_CASE = {
'input_ids': multiple_choice_inputs_ids,
'attention_mask': multiple_choice_input_mask,
'token_type_ids': multiple_choice_token_type_ids,
}
SCREAMING_SNAKE_CASE = model(lowercase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def A ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.num_labels
SCREAMING_SNAKE_CASE = TFRoFormerForTokenClassification(config=lowercase__ )
SCREAMING_SNAKE_CASE = {
'input_ids': input_ids,
'attention_mask': input_mask,
'token_type_ids': token_type_ids,
}
SCREAMING_SNAKE_CASE = model(lowercase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def A ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) -> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = TFRoFormerForQuestionAnswering(config=lowercase__ )
SCREAMING_SNAKE_CASE = {
'input_ids': input_ids,
'attention_mask': input_mask,
'token_type_ids': token_type_ids,
}
SCREAMING_SNAKE_CASE = model(lowercase__ )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def A ( self ) -> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs()
(
(
SCREAMING_SNAKE_CASE
) , (
SCREAMING_SNAKE_CASE
) , (
SCREAMING_SNAKE_CASE
) , (
SCREAMING_SNAKE_CASE
) , (
SCREAMING_SNAKE_CASE
) , (
SCREAMING_SNAKE_CASE
) , (
SCREAMING_SNAKE_CASE
) ,
) = config_and_inputs
SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
return config, inputs_dict
@require_tf
class UpperCamelCase ( __magic_name__ , __magic_name__ , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase_ : Optional[int] = (
(
TFRoFormerModel,
TFRoFormerForCausalLM,
TFRoFormerForMaskedLM,
TFRoFormerForQuestionAnswering,
TFRoFormerForSequenceClassification,
TFRoFormerForTokenClassification,
TFRoFormerForMultipleChoice,
)
if is_tf_available()
else ()
)
UpperCAmelCase_ : Any = (
{
"feature-extraction": TFRoFormerModel,
"fill-mask": TFRoFormerForMaskedLM,
"question-answering": TFRoFormerForQuestionAnswering,
"text-classification": TFRoFormerForSequenceClassification,
"text-generation": TFRoFormerForCausalLM,
"token-classification": TFRoFormerForTokenClassification,
"zero-shot": TFRoFormerForSequenceClassification,
}
if is_tf_available()
else {}
)
UpperCAmelCase_ : List[str] = False
UpperCAmelCase_ : Tuple = False
def A ( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) -> Tuple:
"""simple docstring"""
if pipeline_test_casse_name == "TextGenerationPipelineTests":
return True
return False
def A ( self ) -> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE = TFRoFormerModelTester(self )
SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=lowercase__ , hidden_size=37 )
def A ( self ) -> str:
"""simple docstring"""
self.config_tester.run_common_tests()
def A ( self ) -> Optional[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowercase__ )
def A ( self ) -> Tuple:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*lowercase__ )
def A ( self ) -> List[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_lm_head(*lowercase__ )
def A ( self ) -> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*lowercase__ )
def A ( self ) -> Tuple:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*lowercase__ )
def A ( self ) -> str:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*lowercase__ )
def A ( self ) -> List[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*lowercase__ )
@slow
def A ( self ) -> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = TFRoFormerModel.from_pretrained('junnyu/roformer_chinese_base' )
self.assertIsNotNone(lowercase__ )
@require_tf
class UpperCamelCase ( unittest.TestCase ):
"""simple docstring"""
@slow
def A ( self ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = TFRoFormerForMaskedLM.from_pretrained('junnyu/roformer_chinese_base' )
SCREAMING_SNAKE_CASE = tf.constant([[0, 1, 2, 3, 4, 5]] )
SCREAMING_SNAKE_CASE = model(lowercase__ )[0]
# TODO Replace vocab size
SCREAMING_SNAKE_CASE = 50000
SCREAMING_SNAKE_CASE = [1, 6, vocab_size]
self.assertEqual(output.shape , lowercase__ )
print(output[:, :3, :3] )
# TODO Replace values below with what was printed above.
SCREAMING_SNAKE_CASE = tf.constant(
[
[
[-0.12_053_341, -1.0_264_901, 0.29_221_946],
[-1.5_133_783, 0.197_433, 0.15_190_607],
[-5.0_135_403, -3.900_256, -0.84_038_764],
]
] )
tf.debugging.assert_near(output[:, :3, :3] , lowercase__ , atol=1E-4 )
@require_tf
class UpperCamelCase ( unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase_ : List[Any] = 1e-4
def A ( self ) -> str:
"""simple docstring"""
SCREAMING_SNAKE_CASE = tf.constant([[4, 10]] )
SCREAMING_SNAKE_CASE = TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 , embedding_dim=6 )
SCREAMING_SNAKE_CASE = emba(input_ids.shape )
SCREAMING_SNAKE_CASE = tf.constant(
[[0.0_000, 0.0_000, 0.0_000, 1.0_000, 1.0_000, 1.0_000], [0.8_415, 0.0_464, 0.0_022, 0.5_403, 0.9_989, 1.0_000]] )
tf.debugging.assert_near(lowercase__ , lowercase__ , atol=self.tolerance )
def A ( self ) -> List[str]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = tf.constant(
[
[0.0_000, 0.0_000, 0.0_000, 0.0_000, 0.0_000],
[0.8_415, 0.8_219, 0.8_020, 0.7_819, 0.7_617],
[0.9_093, 0.9_364, 0.9_581, 0.9_749, 0.9_870],
] )
SCREAMING_SNAKE_CASE = TFRoFormerSinusoidalPositionalEmbedding(num_positions=512 , embedding_dim=512 )
emba([2, 16, 512] )
SCREAMING_SNAKE_CASE = emba.weight[:3, :5]
tf.debugging.assert_near(lowercase__ , lowercase__ , atol=self.tolerance )
@require_tf
class UpperCamelCase ( unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase_ : Optional[Any] = 1e-4
def A ( self ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa ) , shape=(2, 12, 16, 64) ) / 100
SCREAMING_SNAKE_CASE = -tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa ) , shape=(2, 12, 16, 64) ) / 100
SCREAMING_SNAKE_CASE = TFRoFormerSinusoidalPositionalEmbedding(num_positions=32 , embedding_dim=64 )
SCREAMING_SNAKE_CASE = embed_positions([2, 16, 768] )[None, None, :, :]
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = TFRoFormerSelfAttention.apply_rotary_position_embeddings(
lowercase__ , lowercase__ , lowercase__ )
SCREAMING_SNAKE_CASE = tf.constant(
[
[0.0_000, 0.0_100, 0.0_200, 0.0_300, 0.0_400, 0.0_500, 0.0_600, 0.0_700],
[-0.2_012, 0.8_897, 0.0_263, 0.9_401, 0.2_074, 0.9_463, 0.3_481, 0.9_343],
[-1.7_057, 0.6_271, -1.2_145, 1.3_897, -0.6_303, 1.7_647, -0.1_173, 1.8_985],
[-2.1_731, -1.6_397, -2.7_358, 0.2_854, -2.1_840, 1.7_183, -1.3_018, 2.4_871],
[0.2_717, -3.6_173, -2.9_206, -2.1_988, -3.6_638, 0.3_858, -2.9_155, 2.2_980],
[3.9_859, -2.1_580, -0.7_984, -4.4_904, -4.1_181, -2.0_252, -4.4_782, 1.1_253],
] )
SCREAMING_SNAKE_CASE = tf.constant(
[
[0.0_000, -0.0_100, -0.0_200, -0.0_300, -0.0_400, -0.0_500, -0.0_600, -0.0_700],
[0.2_012, -0.8_897, -0.0_263, -0.9_401, -0.2_074, -0.9_463, -0.3_481, -0.9_343],
[1.7_057, -0.6_271, 1.2_145, -1.3_897, 0.6_303, -1.7_647, 0.1_173, -1.8_985],
[2.1_731, 1.6_397, 2.7_358, -0.2_854, 2.1_840, -1.7_183, 1.3_018, -2.4_871],
[-0.2_717, 3.6_173, 2.9_206, 2.1_988, 3.6_638, -0.3_858, 2.9_155, -2.2_980],
[-3.9_859, 2.1_580, 0.7_984, 4.4_904, 4.1_181, 2.0_252, 4.4_782, -1.1_253],
] )
tf.debugging.assert_near(query_layer[0, 0, :6, :8] , lowercase__ , atol=self.tolerance )
tf.debugging.assert_near(key_layer[0, 0, :6, :8] , lowercase__ , atol=self.tolerance )
| 406 |
"""simple docstring"""
import argparse
import collections
import os
import re
from transformers.utils import direct_transformers_import
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_table.py
snake_case = 'src/transformers'
snake_case = 'docs/source/en'
snake_case = '.'
def UpperCamelCase_ ( SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ):
with open(SCREAMING_SNAKE_CASE_, 'r', encoding='utf-8', newline='\n' ) as f:
SCREAMING_SNAKE_CASE = f.readlines()
# Find the start prompt.
SCREAMING_SNAKE_CASE = 0
while not lines[start_index].startswith(SCREAMING_SNAKE_CASE_ ):
start_index += 1
start_index += 1
SCREAMING_SNAKE_CASE = start_index
while not lines[end_index].startswith(SCREAMING_SNAKE_CASE_ ):
end_index += 1
end_index -= 1
while len(lines[start_index] ) <= 1:
start_index += 1
while len(lines[end_index] ) <= 1:
end_index -= 1
end_index += 1
return "".join(lines[start_index:end_index] ), start_index, end_index, lines
# Add here suffixes that are used to identify models, separated by |
snake_case = 'Model|Encoder|Decoder|ForConditionalGeneration'
# Regexes that match TF/Flax/PT model names.
snake_case = re.compile(R'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')
snake_case = re.compile(R'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')
# Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes.
snake_case = re.compile(R'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')
# This is to make sure the transformers module imported is the one in the repo.
snake_case = direct_transformers_import(TRANSFORMERS_PATH)
def UpperCamelCase_ ( SCREAMING_SNAKE_CASE_ ):
SCREAMING_SNAKE_CASE = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)', SCREAMING_SNAKE_CASE_ )
return [m.group(0 ) for m in matches]
def UpperCamelCase_ ( SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ):
SCREAMING_SNAKE_CASE = 2 if text == '✅' or text == '❌' else len(SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE = (width - text_length) // 2
SCREAMING_SNAKE_CASE = width - text_length - left_indent
return " " * left_indent + text + " " * right_indent
def UpperCamelCase_ ( ):
SCREAMING_SNAKE_CASE = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
SCREAMING_SNAKE_CASE = {
name: config_maping_names[code]
for code, name in transformers_module.MODEL_NAMES_MAPPING.items()
if code in config_maping_names
}
SCREAMING_SNAKE_CASE = {name: config.replace('Config', '' ) for name, config in model_name_to_config.items()}
# Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax.
SCREAMING_SNAKE_CASE = collections.defaultdict(SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE = collections.defaultdict(SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE = collections.defaultdict(SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE = collections.defaultdict(SCREAMING_SNAKE_CASE_ )
SCREAMING_SNAKE_CASE = collections.defaultdict(SCREAMING_SNAKE_CASE_ )
# Let's lookup through all transformers object (once).
for attr_name in dir(SCREAMING_SNAKE_CASE_ ):
SCREAMING_SNAKE_CASE = None
if attr_name.endswith('Tokenizer' ):
SCREAMING_SNAKE_CASE = slow_tokenizers
SCREAMING_SNAKE_CASE = attr_name[:-9]
elif attr_name.endswith('TokenizerFast' ):
SCREAMING_SNAKE_CASE = fast_tokenizers
SCREAMING_SNAKE_CASE = attr_name[:-1_3]
elif _re_tf_models.match(SCREAMING_SNAKE_CASE_ ) is not None:
SCREAMING_SNAKE_CASE = tf_models
SCREAMING_SNAKE_CASE = _re_tf_models.match(SCREAMING_SNAKE_CASE_ ).groups()[0]
elif _re_flax_models.match(SCREAMING_SNAKE_CASE_ ) is not None:
SCREAMING_SNAKE_CASE = flax_models
SCREAMING_SNAKE_CASE = _re_flax_models.match(SCREAMING_SNAKE_CASE_ ).groups()[0]
elif _re_pt_models.match(SCREAMING_SNAKE_CASE_ ) is not None:
SCREAMING_SNAKE_CASE = pt_models
SCREAMING_SNAKE_CASE = _re_pt_models.match(SCREAMING_SNAKE_CASE_ ).groups()[0]
if lookup_dict is not None:
while len(SCREAMING_SNAKE_CASE_ ) > 0:
if attr_name in model_name_to_prefix.values():
SCREAMING_SNAKE_CASE = True
break
# Try again after removing the last word in the name
SCREAMING_SNAKE_CASE = ''.join(camel_case_split(SCREAMING_SNAKE_CASE_ )[:-1] )
# Let's build that table!
SCREAMING_SNAKE_CASE = list(model_name_to_config.keys() )
model_names.sort(key=str.lower )
SCREAMING_SNAKE_CASE = ['Model', 'Tokenizer slow', 'Tokenizer fast', 'PyTorch support', 'TensorFlow support', 'Flax Support']
# We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side).
SCREAMING_SNAKE_CASE = [len(SCREAMING_SNAKE_CASE_ ) + 2 for c in columns]
SCREAMING_SNAKE_CASE = max([len(SCREAMING_SNAKE_CASE_ ) for name in model_names] ) + 2
# Build the table per se
SCREAMING_SNAKE_CASE = '|' + '|'.join([_center_text(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) for c, w in zip(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ )] ) + '|\n'
# Use ":-----:" format to center-aligned table cell texts
table += "|" + "|".join([':' + '-' * (w - 2) + ':' for w in widths] ) + "|\n"
SCREAMING_SNAKE_CASE = {True: '✅', False: '❌'}
for name in model_names:
SCREAMING_SNAKE_CASE = model_name_to_prefix[name]
SCREAMING_SNAKE_CASE = [
name,
check[slow_tokenizers[prefix]],
check[fast_tokenizers[prefix]],
check[pt_models[prefix]],
check[tf_models[prefix]],
check[flax_models[prefix]],
]
table += "|" + "|".join([_center_text(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) for l, w in zip(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ )] ) + "|\n"
return table
def UpperCamelCase_ ( SCREAMING_SNAKE_CASE_=False ):
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = _find_text_in_file(
filename=os.path.join(SCREAMING_SNAKE_CASE_, 'index.md' ), start_prompt='<!--This table is updated automatically from the auto modules', end_prompt='<!-- End table-->', )
SCREAMING_SNAKE_CASE = get_model_table_from_auto_modules()
if current_table != new_table:
if overwrite:
with open(os.path.join(SCREAMING_SNAKE_CASE_, 'index.md' ), 'w', encoding='utf-8', newline='\n' ) as f:
f.writelines(lines[:start_index] + [new_table] + lines[end_index:] )
else:
raise ValueError(
'The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.' )
if __name__ == "__main__":
snake_case = argparse.ArgumentParser()
parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.')
snake_case = parser.parse_args()
check_model_table(args.fix_and_overwrite)
| 406 | 1 |
from __future__ import annotations
import os
from collections.abc import Mapping
snake_case_ = tuple[int, int]
class SCREAMING_SNAKE_CASE__ :
def __init__( self , a , a):
lowercase__ : set[int] = vertices
lowercase__ : dict[EdgeT, int] = {
(min(a), max(a)): weight for edge, weight in edges.items()
}
def snake_case_ ( self , a , a):
self.vertices.add(edge[0])
self.vertices.add(edge[1])
lowercase__ : Dict = weight
def snake_case_ ( self):
lowercase__ : Graph = Graph({min(self.vertices)} , {})
lowercase__ : EdgeT
lowercase__ : int
lowercase__ : EdgeT
lowercase__ : int
while len(subgraph.vertices) < len(self.vertices):
lowercase__ : Union[str, Any] = max(self.edges.values()) + 1
for edge, weight in self.edges.items():
if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices):
if weight < min_weight:
lowercase__ : List[str] = edge
lowercase__ : Any = weight
subgraph.add_edge(a , a)
return subgraph
def snake_case__ ( SCREAMING_SNAKE_CASE_ : str = "p107_network.txt" ):
'''simple docstring'''
lowercase__ : str = os.path.abspath(os.path.dirname(SCREAMING_SNAKE_CASE_ ) )
lowercase__ : str = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowercase__ : dict[EdgeT, int] = {}
lowercase__ : list[str]
lowercase__ : int
lowercase__ : int
with open(SCREAMING_SNAKE_CASE_ ) as f:
lowercase__ : List[str] = f.read().strip().split('\n' )
lowercase__ : List[str] = [line.split(',' ) for line in data]
for edgea in range(1 , len(SCREAMING_SNAKE_CASE_ ) ):
for edgea in range(SCREAMING_SNAKE_CASE_ ):
if adjaceny_matrix[edgea][edgea] != "-":
lowercase__ : List[Any] = int(adjaceny_matrix[edgea][edgea] )
lowercase__ : Graph = Graph(set(range(len(SCREAMING_SNAKE_CASE_ ) ) ) , SCREAMING_SNAKE_CASE_ )
lowercase__ : Graph = graph.prims_algorithm()
lowercase__ : int = sum(graph.edges.values() )
lowercase__ : int = sum(subgraph.edges.values() )
return initial_total - optimal_total
if __name__ == "__main__":
print(F'''{solution() = }''')
| 164 |
from scipy.stats import spearmanr
import datasets
snake_case_ = '''
The Spearman rank-order correlation coefficient is a measure of the
relationship between two datasets. Like other correlation coefficients,
this one varies between -1 and +1 with 0 implying no correlation.
Positive correlations imply that as data in dataset x increases, so
does data in dataset y. Negative correlations imply that as x increases,
y decreases. Correlations of -1 or +1 imply an exact monotonic relationship.
Unlike the Pearson correlation, the Spearman correlation does not
assume that both datasets are normally distributed.
The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Spearman correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.
'''
snake_case_ = '''
Args:
predictions (`List[float]`): Predicted labels, as returned by a model.
references (`List[float]`): Ground truth labels.
return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns
only the spearmanr score. Defaults to `False`.
Returns:
spearmanr (`float`): Spearman correlation coefficient.
p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.
Examples:
Example 1:
>>> spearmanr_metric = datasets.load_metric("spearmanr")
>>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])
>>> print(results)
{\'spearmanr\': -0.7}
Example 2:
>>> spearmanr_metric = datasets.load_metric("spearmanr")
>>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],
... predictions=[10, 9, 2.5, 6, 4],
... return_pvalue=True)
>>> print(results[\'spearmanr\'])
-0.7
>>> print(round(results[\'spearmanr_pvalue\'], 2))
0.19
'''
snake_case_ = r'''\
@book{kokoska2000crc,
title={CRC standard probability and statistics tables and formulae},
author={Kokoska, Stephen and Zwillinger, Daniel},
year={2000},
publisher={Crc Press}
}
@article{2020SciPy-NMeth,
author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
Haberland, Matt and Reddy, Tyler and Cournapeau, David and
Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
Kern, Robert and Larson, Eric and Carey, C J and
Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and
{VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
Harris, Charles R. and Archibald, Anne M. and
Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and
{van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
Computing in Python}},
journal = {Nature Methods},
year = {2020},
volume = {17},
pages = {261--272},
adsurl = {https://rdcu.be/b08Wh},
doi = {10.1038/s41592-019-0686-2},
}
'''
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class SCREAMING_SNAKE_CASE__ (datasets.Metric ):
def snake_case_ ( self):
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'predictions': datasets.Value('float'),
'references': datasets.Value('float'),
}) , reference_urls=['https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html'] , )
def snake_case_ ( self , a , a , a=False):
lowercase__ : int = spearmanr(a , a)
if return_pvalue:
return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
else:
return {"spearmanr": results[0]}
| 164 | 1 |
"""simple docstring"""
def a ( __UpperCAmelCase : Any ) -> bool:
__magic_name__: List[str] = [int(__UpperCAmelCase ) for i in ip_va_address.split(""".""" ) if i.isdigit()]
return len(__UpperCAmelCase ) == 4 and all(0 <= int(__UpperCAmelCase ) <= 2_5_4 for octet in octets )
if __name__ == "__main__":
__lowerCamelCase = input().strip()
__lowerCamelCase = 'valid' if is_ip_va_address_valid(ip) else 'invalid'
print(f'''{ip} is a {valid_or_invalid} IP v4 address.''')
| 718 |
"""simple docstring"""
from __future__ import annotations
def a ( __UpperCAmelCase : list[int] , __UpperCAmelCase : int ) -> list[int]:
__magic_name__: int = 0
__magic_name__: List[str] = len(__UpperCAmelCase ) - 1
while i < j:
if nums[i] + nums[j] == target:
return [i, j]
elif nums[i] + nums[j] < target:
__magic_name__: Dict = i + 1
else:
__magic_name__: Tuple = j - 1
return []
if __name__ == "__main__":
import doctest
doctest.testmod()
print(f'''{two_pointer([2, 7, 11, 15], 9) = }''')
| 213 | 0 |
import math
from typing import Any, Callable, List, Optional, Tuple, Union
import numpy as np
import torch
from ...models import TaFilmDecoder
from ...schedulers import DDPMScheduler
from ...utils import is_onnx_available, logging, randn_tensor
if is_onnx_available():
from ..onnx_utils import OnnxRuntimeModel
from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline
from .continous_encoder import SpectrogramContEncoder
from .notes_encoder import SpectrogramNotesEncoder
SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) # pylint: disable=invalid-name
SCREAMING_SNAKE_CASE__ = 2_5_6
class __lowerCAmelCase ( _lowercase ):
"""simple docstring"""
A__ : Optional[Any] = ["melgan"]
def __init__( self : List[Any] , _snake_case : SpectrogramNotesEncoder , _snake_case : SpectrogramContEncoder , _snake_case : TaFilmDecoder , _snake_case : DDPMScheduler , _snake_case : OnnxRuntimeModel if is_onnx_available() else Any , ):
"""simple docstring"""
super().__init__()
# From MELGAN
A__ = math.log(1E-5 ) # Matches MelGAN training.
A__ = 4.0 # Largest value for most examples
A__ = 1_28
self.register_modules(
notes_encoder=__lowerCAmelCase , continuous_encoder=__lowerCAmelCase , decoder=__lowerCAmelCase , scheduler=__lowerCAmelCase , melgan=__lowerCAmelCase , )
def _a ( self : List[str] , _snake_case : Union[str, Any] , _snake_case : List[Any]=(-1.0, 1.0) , _snake_case : Union[str, Any]=False ):
"""simple docstring"""
A__ = output_range
if clip:
A__ = torch.clip(__lowerCAmelCase , self.min_value , self.max_value )
# Scale to [0, 1].
A__ = (features - self.min_value) / (self.max_value - self.min_value)
# Scale to [min_out, max_out].
return zero_one * (max_out - min_out) + min_out
def _a ( self : Union[str, Any] , _snake_case : List[Any] , _snake_case : Optional[Any]=(-1.0, 1.0) , _snake_case : Optional[int]=False ):
"""simple docstring"""
A__ = input_range
A__ = torch.clip(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if clip else outputs
# Scale to [0, 1].
A__ = (outputs - min_out) / (max_out - min_out)
# Scale to [self.min_value, self.max_value].
return zero_one * (self.max_value - self.min_value) + self.min_value
def _a ( self : List[Any] , _snake_case : List[str] , _snake_case : Optional[Any] , _snake_case : List[str] ):
"""simple docstring"""
A__ = input_tokens > 0
A__ = self.notes_encoder(
encoder_input_tokens=__lowerCAmelCase , encoder_inputs_mask=__lowerCAmelCase )
A__ = self.continuous_encoder(
encoder_inputs=__lowerCAmelCase , encoder_inputs_mask=__lowerCAmelCase )
return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)]
def _a ( self : Any , _snake_case : Dict , _snake_case : List[str] , _snake_case : Optional[int] ):
"""simple docstring"""
A__ = noise_time
if not torch.is_tensor(__lowerCAmelCase ):
A__ = torch.tensor([timesteps] , dtype=torch.long , device=input_tokens.device )
elif torch.is_tensor(__lowerCAmelCase ) and len(timesteps.shape ) == 0:
A__ = timesteps[None].to(input_tokens.device )
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
A__ = timesteps * torch.ones(input_tokens.shape[0] , dtype=timesteps.dtype , device=timesteps.device )
A__ = self.decoder(
encodings_and_masks=__lowerCAmelCase , decoder_input_tokens=__lowerCAmelCase , decoder_noise_time=__lowerCAmelCase )
return logits
@torch.no_grad()
def __call__( self : str , _snake_case : List[List[int]] , _snake_case : Optional[torch.Generator] = None , _snake_case : int = 1_00 , _snake_case : bool = True , _snake_case : str = "numpy" , _snake_case : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , _snake_case : int = 1 , ):
"""simple docstring"""
if (callback_steps is None) or (
callback_steps is not None and (not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or callback_steps <= 0)
):
raise ValueError(
F'''`callback_steps` has to be a positive integer but is {callback_steps} of type'''
F''' {type(__lowerCAmelCase )}.''' )
A__ = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] , dtype=np.floataa )
A__ = np.zeros([1, 0, self.n_dims] , np.floataa )
A__ = torch.ones((1, TARGET_FEATURE_LENGTH) , dtype=__lowerCAmelCase , device=self.device )
for i, encoder_input_tokens in enumerate(__lowerCAmelCase ):
if i == 0:
A__ = torch.from_numpy(pred_mel[:1].copy() ).to(
device=self.device , dtype=self.decoder.dtype )
# The first chunk has no previous context.
A__ = torch.zeros((1, TARGET_FEATURE_LENGTH) , dtype=__lowerCAmelCase , device=self.device )
else:
# The full song pipeline does not feed in a context feature, so the mask
# will be all 0s after the feature converter. Because we know we're
# feeding in a full context chunk from the previous prediction, set it
# to all 1s.
A__ = ones
A__ = self.scale_features(
__lowerCAmelCase , output_range=[-1.0, 1.0] , clip=__lowerCAmelCase )
A__ = self.encode(
input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device ) , continuous_inputs=__lowerCAmelCase , continuous_mask=__lowerCAmelCase , )
# Sample encoder_continuous_inputs shaped gaussian noise to begin loop
A__ = randn_tensor(
shape=encoder_continuous_inputs.shape , generator=__lowerCAmelCase , device=self.device , dtype=self.decoder.dtype , )
# set step values
self.scheduler.set_timesteps(__lowerCAmelCase )
# Denoising diffusion loop
for j, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ):
A__ = self.decode(
encodings_and_masks=__lowerCAmelCase , input_tokens=__lowerCAmelCase , noise_time=t / self.scheduler.config.num_train_timesteps , )
# Compute previous output: x_t -> x_t-1
A__ = self.scheduler.step(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , generator=__lowerCAmelCase ).prev_sample
A__ = self.scale_to_features(__lowerCAmelCase , input_range=[-1.0, 1.0] )
A__ = mel[:1]
A__ = mel.cpu().float().numpy()
A__ = np.concatenate([full_pred_mel, pred_mel[:1]] , axis=1 )
# call the callback, if provided
if callback is not None and i % callback_steps == 0:
callback(__lowerCAmelCase , __lowerCAmelCase )
logger.info('Generated segment' , __lowerCAmelCase )
if output_type == "numpy" and not is_onnx_available():
raise ValueError(
'Cannot return output in \'np\' format if ONNX is not available. Make sure to have ONNX installed or set \'output_type\' to \'mel\'.' )
elif output_type == "numpy" and self.melgan is None:
raise ValueError(
'Cannot return output in \'np\' format if melgan component is not defined. Make sure to define `self.melgan` or set \'output_type\' to \'mel\'.' )
if output_type == "numpy":
A__ = self.melgan(input_features=full_pred_mel.astype(np.floataa ) )
else:
A__ = full_pred_mel
if not return_dict:
return (output,)
return AudioPipelineOutput(audios=__lowerCAmelCase )
| 9 |
"""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 snake_case_ ( A_ : Tuple, A_ : List[str], A_ : Optional[Any], A_ : Dict, A_ : Dict=True, A_ : int="pt" ):
'''simple docstring'''
_lowerCamelCase : str = {'''add_prefix_space''': True} if isinstance(A_, A_ ) and not line.startswith(''' ''' ) else {}
_lowerCamelCase : Union[str, Any] = padding_side
return tokenizer(
[line], max_length=A_, padding='''max_length''' if pad_to_max_length else None, truncation=A_, return_tensors=A_, add_special_tokens=A_, **A_, )
def snake_case_ ( A_ : Any, A_ : Optional[int], A_ : List[Any]=None, ):
'''simple docstring'''
_lowerCamelCase : Optional[int] = input_ids.ne(A_ ).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 ( _lowercase):
def __init__( self : Tuple , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Tuple="train" , __lowerCAmelCase : List[str]=None , __lowerCAmelCase : Optional[int]=None , __lowerCAmelCase : Any=None , __lowerCAmelCase : Union[str, Any]="" , ):
"""simple docstring"""
super().__init__()
_lowerCamelCase : Optional[int] = Path(__lowerCAmelCase ).joinpath(type_path + '''.source''' )
_lowerCamelCase : List[str] = Path(__lowerCAmelCase ).joinpath(type_path + '''.target''' )
_lowerCamelCase : List[Any] = self.get_char_lens(self.src_file )
_lowerCamelCase : Optional[int] = max_source_length
_lowerCamelCase : Optional[Any] = max_target_length
assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}'''
_lowerCamelCase : List[Any] = tokenizer
_lowerCamelCase : List[Any] = prefix
if n_obs is not None:
_lowerCamelCase : List[str] = self.src_lens[:n_obs]
_lowerCamelCase : int = src_lang
_lowerCamelCase : Union[str, Any] = tgt_lang
def __len__( self : int ):
"""simple docstring"""
return len(self.src_lens )
def __getitem__( self : Dict , __lowerCAmelCase : Optional[Any] ):
"""simple docstring"""
_lowerCamelCase : str = index + 1 # linecache starts at 1
_lowerCamelCase : Union[str, Any] = self.prefix + linecache.getline(str(self.src_file ) , __lowerCAmelCase ).rstrip('''\n''' )
_lowerCamelCase : Optional[Any] = 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
_lowerCamelCase : Optional[int] = (
self.tokenizer.question_encoder if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer
)
_lowerCamelCase : Union[str, Any] = self.tokenizer.generator if isinstance(self.tokenizer , __lowerCAmelCase ) else self.tokenizer
_lowerCamelCase : List[str] = encode_line(__lowerCAmelCase , __lowerCAmelCase , self.max_source_length , '''right''' )
_lowerCamelCase : List[str] = encode_line(__lowerCAmelCase , __lowerCAmelCase , self.max_target_length , '''right''' )
_lowerCamelCase : Optional[Any] = source_inputs['''input_ids'''].squeeze()
_lowerCamelCase : Union[str, Any] = target_inputs['''input_ids'''].squeeze()
_lowerCamelCase : Any = 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 : str ):
"""simple docstring"""
return [len(__lowerCAmelCase ) for x in Path(__lowerCAmelCase ).open().readlines()]
def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : Any ):
"""simple docstring"""
_lowerCamelCase : List[Any] = torch.stack([x['''input_ids'''] for x in batch] )
_lowerCamelCase : Tuple = torch.stack([x['''attention_mask'''] for x in batch] )
_lowerCamelCase : Union[str, Any] = torch.stack([x['''decoder_input_ids'''] for x in batch] )
_lowerCamelCase : Tuple = (
self.tokenizer.generator.pad_token_id
if isinstance(self.tokenizer , __lowerCAmelCase )
else self.tokenizer.pad_token_id
)
_lowerCamelCase : Tuple = (
self.tokenizer.question_encoder.pad_token_id
if isinstance(self.tokenizer , __lowerCAmelCase )
else self.tokenizer.pad_token_id
)
_lowerCamelCase : Union[str, Any] = trim_batch(__lowerCAmelCase , __lowerCAmelCase )
_lowerCamelCase , _lowerCamelCase : List[str] = trim_batch(__lowerCAmelCase , __lowerCAmelCase , attention_mask=__lowerCAmelCase )
_lowerCamelCase : Optional[int] = {
'''input_ids''': source_ids,
'''attention_mask''': source_mask,
'''decoder_input_ids''': y,
}
return batch
lowerCAmelCase__ = getLogger(__name__)
def snake_case_ ( A_ : List[List] ):
'''simple docstring'''
return list(itertools.chain.from_iterable(A_ ) )
def snake_case_ ( A_ : str ):
'''simple docstring'''
_lowerCamelCase : Dict = get_git_info()
save_json(A_, os.path.join(A_, '''git_log.json''' ) )
def snake_case_ ( A_ : str, A_ : Union[str, Any], A_ : int=4, **A_ : Optional[int] ):
'''simple docstring'''
with open(A_, '''w''' ) as f:
json.dump(A_, A_, indent=A_, **A_ )
def snake_case_ ( A_ : Any ):
'''simple docstring'''
with open(A_ ) as f:
return json.load(A_ )
def snake_case_ ( ):
'''simple docstring'''
_lowerCamelCase : List[str] = git.Repo(search_parent_directories=A_ )
_lowerCamelCase : str = {
'''repo_id''': str(A_ ),
'''repo_sha''': str(repo.head.object.hexsha ),
'''repo_branch''': str(repo.active_branch ),
'''hostname''': str(socket.gethostname() ),
}
return repo_infos
def snake_case_ ( A_ : Callable, A_ : Iterable ):
'''simple docstring'''
return list(map(A_, A_ ) )
def snake_case_ ( A_ : str, A_ : Tuple ):
'''simple docstring'''
with open(A_, '''wb''' ) as f:
return pickle.dump(A_, A_ )
def snake_case_ ( A_ : List[str] ):
'''simple docstring'''
def remove_articles(A_ : str ):
return re.sub(R'''\b(a|an|the)\b''', ''' ''', A_ )
def white_space_fix(A_ : Any ):
return " ".join(text.split() )
def remove_punc(A_ : List[Any] ):
_lowerCamelCase : Any = set(string.punctuation )
return "".join(ch for ch in text if ch not in exclude )
def lower(A_ : Optional[int] ):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(A_ ) ) ) )
def snake_case_ ( A_ : int, A_ : List[Any] ):
'''simple docstring'''
_lowerCamelCase : str = normalize_answer(A_ ).split()
_lowerCamelCase : int = normalize_answer(A_ ).split()
_lowerCamelCase : str = Counter(A_ ) & Counter(A_ )
_lowerCamelCase : Any = sum(common.values() )
if num_same == 0:
return 0
_lowerCamelCase : int = 1.0 * num_same / len(A_ )
_lowerCamelCase : str = 1.0 * num_same / len(A_ )
_lowerCamelCase : List[Any] = (2 * precision * recall) / (precision + recall)
return fa
def snake_case_ ( A_ : Dict, A_ : str ):
'''simple docstring'''
return normalize_answer(A_ ) == normalize_answer(A_ )
def snake_case_ ( A_ : List[str], A_ : List[str] ):
'''simple docstring'''
assert len(A_ ) == len(A_ )
_lowerCamelCase : Optional[Any] = 0
for hypo, pred in zip(A_, A_ ):
em += exact_match_score(A_, A_ )
if len(A_ ) > 0:
em /= len(A_ )
return {"em": em}
def snake_case_ ( A_ : Optional[int] ):
'''simple docstring'''
return model_prefix.startswith('''rag''' )
def snake_case_ ( A_ : Dict, A_ : int, A_ : List[Any] ):
'''simple docstring'''
_lowerCamelCase : Dict = {p: p for p in extra_params}
# T5 models don't have `dropout` param, they have `dropout_rate` instead
_lowerCamelCase : Tuple = '''dropout_rate'''
for p in extra_params:
if getattr(A_, A_, A_ ):
if not hasattr(A_, A_ ) and not hasattr(A_, equivalent_param[p] ):
logger.info('''config doesn\'t have a `{}` attribute'''.format(A_ ) )
delattr(A_, A_ )
continue
_lowerCamelCase : Union[str, Any] = p if hasattr(A_, A_ ) else equivalent_param[p]
setattr(A_, A_, getattr(A_, A_ ) )
delattr(A_, A_ )
return hparams, config
| 83 | 0 |
'''simple docstring'''
import unittest
from transformers import XLMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
XLMForMultipleChoice,
XLMForQuestionAnswering,
XLMForQuestionAnsweringSimple,
XLMForSequenceClassification,
XLMForTokenClassification,
XLMModel,
XLMWithLMHeadModel,
)
from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST
class _SCREAMING_SNAKE_CASE :
def __init__( self : Tuple , __UpperCamelCase : Optional[int] , __UpperCamelCase : Union[str, Any]=13 , __UpperCamelCase : Tuple=7 , __UpperCamelCase : int=True , __UpperCamelCase : List[Any]=True , __UpperCamelCase : Optional[Any]=True , __UpperCamelCase : int=True , __UpperCamelCase : Dict=True , __UpperCamelCase : Tuple=False , __UpperCamelCase : Any=False , __UpperCamelCase : List[Any]=False , __UpperCamelCase : int=2 , __UpperCamelCase : Optional[Any]=99 , __UpperCamelCase : Any=0 , __UpperCamelCase : Union[str, Any]=32 , __UpperCamelCase : List[Any]=5 , __UpperCamelCase : List[str]=4 , __UpperCamelCase : int=0.1 , __UpperCamelCase : Optional[int]=0.1 , __UpperCamelCase : Union[str, Any]=512 , __UpperCamelCase : List[Any]=2 , __UpperCamelCase : Union[str, Any]=0.02 , __UpperCamelCase : List[Any]=2 , __UpperCamelCase : List[str]=4 , __UpperCamelCase : int="last" , __UpperCamelCase : int=True , __UpperCamelCase : Optional[Any]=None , __UpperCamelCase : Optional[Any]=0 , ) -> Optional[int]:
"""simple docstring"""
snake_case__ : Any = parent
snake_case__ : List[Any] = batch_size
snake_case__ : Dict = seq_length
snake_case__ : Optional[int] = is_training
snake_case__ : Union[str, Any] = use_input_lengths
snake_case__ : List[Any] = use_token_type_ids
snake_case__ : str = use_labels
snake_case__ : str = gelu_activation
snake_case__ : Union[str, Any] = sinusoidal_embeddings
snake_case__ : int = causal
snake_case__ : List[Any] = asm
snake_case__ : Optional[Any] = n_langs
snake_case__ : Tuple = vocab_size
snake_case__ : Optional[Any] = n_special
snake_case__ : Optional[int] = hidden_size
snake_case__ : List[Any] = num_hidden_layers
snake_case__ : List[Any] = num_attention_heads
snake_case__ : Any = hidden_dropout_prob
snake_case__ : int = attention_probs_dropout_prob
snake_case__ : List[Any] = max_position_embeddings
snake_case__ : Dict = type_sequence_label_size
snake_case__ : int = initializer_range
snake_case__ : Optional[Any] = num_labels
snake_case__ : List[Any] = num_choices
snake_case__ : str = summary_type
snake_case__ : Optional[Any] = use_proj
snake_case__ : str = scope
snake_case__ : Tuple = bos_token_id
def lowerCAmelCase ( self : List[str] ) -> List[Any]:
"""simple docstring"""
snake_case__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
snake_case__ : Dict = random_attention_mask([self.batch_size, self.seq_length] )
snake_case__ : Optional[int] = None
if self.use_input_lengths:
snake_case__ : List[Any] = (
ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2
) # small variation of seq_length
snake_case__ : str = None
if self.use_token_type_ids:
snake_case__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs )
snake_case__ : Optional[int] = None
snake_case__ : Dict = None
snake_case__ : Union[str, Any] = None
if self.use_labels:
snake_case__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size )
snake_case__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
snake_case__ : List[Any] = ids_tensor([self.batch_size] , 2 ).float()
snake_case__ : int = ids_tensor([self.batch_size] , self.num_choices )
snake_case__ : Tuple = self.get_config()
return (
config,
input_ids,
token_type_ids,
input_lengths,
sequence_labels,
token_labels,
is_impossible_labels,
choice_labels,
input_mask,
)
def lowerCAmelCase ( self : List[str] ) -> str:
"""simple docstring"""
return XLMConfig(
vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , )
def lowerCAmelCase ( self : str , __UpperCamelCase : str , __UpperCamelCase : Tuple , __UpperCamelCase : int , __UpperCamelCase : Optional[int] , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : List[Any] , __UpperCamelCase : List[Any] , __UpperCamelCase : Optional[int] , __UpperCamelCase : str , ) -> Union[str, Any]:
"""simple docstring"""
snake_case__ : List[str] = XLMModel(config=__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
snake_case__ : Any = model(__UpperCamelCase , lengths=__UpperCamelCase , langs=__UpperCamelCase )
snake_case__ : Optional[int] = model(__UpperCamelCase , langs=__UpperCamelCase )
snake_case__ : int = model(__UpperCamelCase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def lowerCAmelCase ( self : Optional[int] , __UpperCamelCase : Any , __UpperCamelCase : Dict , __UpperCamelCase : List[Any] , __UpperCamelCase : Tuple , __UpperCamelCase : str , __UpperCamelCase : List[Any] , __UpperCamelCase : Any , __UpperCamelCase : List[str] , __UpperCamelCase : List[Any] , ) -> int:
"""simple docstring"""
snake_case__ : Union[str, Any] = XLMWithLMHeadModel(__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
snake_case__ : int = model(__UpperCamelCase , token_type_ids=__UpperCamelCase , labels=__UpperCamelCase )
self.parent.assertEqual(result.loss.shape , () )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def lowerCAmelCase ( self : List[str] , __UpperCamelCase : List[Any] , __UpperCamelCase : List[str] , __UpperCamelCase : List[Any] , __UpperCamelCase : Tuple , __UpperCamelCase : Optional[int] , __UpperCamelCase : Any , __UpperCamelCase : Optional[Any] , __UpperCamelCase : Optional[Any] , __UpperCamelCase : Union[str, Any] , ) -> Union[str, Any]:
"""simple docstring"""
snake_case__ : Any = XLMForQuestionAnsweringSimple(__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
snake_case__ : Optional[Any] = model(__UpperCamelCase )
snake_case__ : Tuple = model(__UpperCamelCase , start_positions=__UpperCamelCase , end_positions=__UpperCamelCase )
snake_case__ : Union[str, Any] = outputs
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def lowerCAmelCase ( self : Tuple , __UpperCamelCase : str , __UpperCamelCase : Optional[int] , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : Optional[Any] , __UpperCamelCase : List[Any] , __UpperCamelCase : Tuple , __UpperCamelCase : Optional[int] , __UpperCamelCase : Any , __UpperCamelCase : List[Any] , ) -> int:
"""simple docstring"""
snake_case__ : Dict = XLMForQuestionAnswering(__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
snake_case__ : Tuple = model(__UpperCamelCase )
snake_case__ : Optional[int] = model(
__UpperCamelCase , start_positions=__UpperCamelCase , end_positions=__UpperCamelCase , cls_index=__UpperCamelCase , is_impossible=__UpperCamelCase , p_mask=__UpperCamelCase , )
snake_case__ : Dict = model(
__UpperCamelCase , start_positions=__UpperCamelCase , end_positions=__UpperCamelCase , cls_index=__UpperCamelCase , is_impossible=__UpperCamelCase , )
(snake_case__ ) : Any = result_with_labels.to_tuple()
snake_case__ : Dict = model(__UpperCamelCase , start_positions=__UpperCamelCase , end_positions=__UpperCamelCase )
(snake_case__ ) : Optional[Any] = result_with_labels.to_tuple()
self.parent.assertEqual(result_with_labels.loss.shape , () )
self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) )
self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) )
self.parent.assertEqual(
result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) )
self.parent.assertEqual(
result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) )
self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) )
def lowerCAmelCase ( self : List[Any] , __UpperCamelCase : Optional[Any] , __UpperCamelCase : List[str] , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : Optional[Any] , __UpperCamelCase : Any , __UpperCamelCase : Dict , __UpperCamelCase : int , __UpperCamelCase : Optional[Any] , __UpperCamelCase : int , ) -> List[str]:
"""simple docstring"""
snake_case__ : Dict = XLMForSequenceClassification(__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
snake_case__ : List[str] = model(__UpperCamelCase )
snake_case__ : Optional[Any] = model(__UpperCamelCase , labels=__UpperCamelCase )
self.parent.assertEqual(result.loss.shape , () )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def lowerCAmelCase ( self : Optional[Any] , __UpperCamelCase : str , __UpperCamelCase : Optional[int] , __UpperCamelCase : Dict , __UpperCamelCase : Tuple , __UpperCamelCase : str , __UpperCamelCase : str , __UpperCamelCase : Optional[int] , __UpperCamelCase : int , __UpperCamelCase : str , ) -> List[Any]:
"""simple docstring"""
snake_case__ : int = self.num_labels
snake_case__ : Optional[int] = XLMForTokenClassification(__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
snake_case__ : int = model(__UpperCamelCase , attention_mask=__UpperCamelCase , labels=__UpperCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def lowerCAmelCase ( self : Optional[int] , __UpperCamelCase : List[str] , __UpperCamelCase : Any , __UpperCamelCase : str , __UpperCamelCase : Optional[Any] , __UpperCamelCase : str , __UpperCamelCase : Any , __UpperCamelCase : int , __UpperCamelCase : Any , __UpperCamelCase : Tuple , ) -> Dict:
"""simple docstring"""
snake_case__ : int = self.num_choices
snake_case__ : int = XLMForMultipleChoice(config=__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
snake_case__ : str = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
snake_case__ : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
snake_case__ : Optional[Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
snake_case__ : Tuple = model(
__UpperCamelCase , attention_mask=__UpperCamelCase , token_type_ids=__UpperCamelCase , labels=__UpperCamelCase , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def lowerCAmelCase ( self : Any ) -> Any:
"""simple docstring"""
snake_case__ : Any = self.prepare_config_and_inputs()
(
snake_case__
) : str = config_and_inputs
snake_case__ : Tuple = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''lengths''': input_lengths}
return config, inputs_dict
@require_torch
class _SCREAMING_SNAKE_CASE (lowercase__, lowercase__, lowercase__, unittest.TestCase ):
A__ = (
(
XLMModel,
XLMWithLMHeadModel,
XLMForQuestionAnswering,
XLMForSequenceClassification,
XLMForQuestionAnsweringSimple,
XLMForTokenClassification,
XLMForMultipleChoice,
)
if is_torch_available()
else ()
)
A__ = (
(XLMWithLMHeadModel,) if is_torch_available() else ()
) # TODO (PVP): Check other models whether language generation is also applicable
A__ = (
{
'feature-extraction': XLMModel,
'fill-mask': XLMWithLMHeadModel,
'question-answering': XLMForQuestionAnsweringSimple,
'text-classification': XLMForSequenceClassification,
'text-generation': XLMWithLMHeadModel,
'token-classification': XLMForTokenClassification,
'zero-shot': XLMForSequenceClassification,
}
if is_torch_available()
else {}
)
def lowerCAmelCase ( self : Any , __UpperCamelCase : Dict , __UpperCamelCase : List[str] , __UpperCamelCase : Any , __UpperCamelCase : Dict , __UpperCamelCase : List[str] ) -> Any:
"""simple docstring"""
if (
pipeline_test_casse_name == "QAPipelineTests"
and tokenizer_name is not None
and not tokenizer_name.endswith('''Fast''' )
):
# `QAPipelineTests` fails for a few models when the slower tokenizer are used.
# (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
# TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
return True
return False
def lowerCAmelCase ( self : Tuple , __UpperCamelCase : List[Any] , __UpperCamelCase : List[Any] , __UpperCamelCase : Optional[Any]=False ) -> List[Any]:
"""simple docstring"""
snake_case__ : List[str] = super()._prepare_for_class(__UpperCamelCase , __UpperCamelCase , return_labels=__UpperCamelCase )
if return_labels:
if model_class.__name__ == "XLMForQuestionAnswering":
snake_case__ : Dict = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=__UpperCamelCase )
snake_case__ : Tuple = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=__UpperCamelCase )
return inputs_dict
def lowerCAmelCase ( self : List[Any] ) -> Tuple:
"""simple docstring"""
snake_case__ : Any = XLMModelTester(self )
snake_case__ : int = ConfigTester(self , config_class=__UpperCamelCase , emb_dim=37 )
def lowerCAmelCase ( self : int ) -> Optional[Any]:
"""simple docstring"""
self.config_tester.run_common_tests()
def lowerCAmelCase ( self : Any ) -> Union[str, Any]:
"""simple docstring"""
snake_case__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_model(*__UpperCamelCase )
def lowerCAmelCase ( self : Any ) -> List[str]:
"""simple docstring"""
snake_case__ : str = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_lm_head(*__UpperCamelCase )
def lowerCAmelCase ( self : Dict ) -> List[Any]:
"""simple docstring"""
snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_simple_qa(*__UpperCamelCase )
def lowerCAmelCase ( self : Dict ) -> Tuple:
"""simple docstring"""
snake_case__ : str = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_qa(*__UpperCamelCase )
def lowerCAmelCase ( self : int ) -> Dict:
"""simple docstring"""
snake_case__ : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_sequence_classif(*__UpperCamelCase )
def lowerCAmelCase ( self : Any ) -> List[str]:
"""simple docstring"""
snake_case__ : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_token_classif(*__UpperCamelCase )
def lowerCAmelCase ( self : List[str] ) -> Dict:
"""simple docstring"""
snake_case__ : Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_xlm_for_multiple_choice(*__UpperCamelCase )
def lowerCAmelCase ( self : Optional[Any] , __UpperCamelCase : List[str] , __UpperCamelCase : List[str] , __UpperCamelCase : str , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : str , __UpperCamelCase : str=False , __UpperCamelCase : Union[str, Any]=1 ) -> List[Any]:
"""simple docstring"""
self.assertIsInstance(__UpperCamelCase , __UpperCamelCase )
self.assertListEqual(
[isinstance(__UpperCamelCase , __UpperCamelCase ) for iter_attentions in attentions] , [True] * len(__UpperCamelCase ) )
self.assertEqual(len(__UpperCamelCase ) , (max_length - min_length) * num_beam_groups )
for idx, iter_attentions in enumerate(__UpperCamelCase ):
# adds PAD dummy token
snake_case__ : List[str] = min_length + idx + 1
snake_case__ : Any = min_length + idx + 1
snake_case__ : List[Any] = (
batch_size * num_beam_groups,
config.num_attention_heads,
tgt_len,
src_len,
)
# check attn size
self.assertListEqual(
[layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(__UpperCamelCase ) )
def lowerCAmelCase ( self : Optional[int] , __UpperCamelCase : str , __UpperCamelCase : List[Any] , __UpperCamelCase : List[Any] , __UpperCamelCase : Tuple , __UpperCamelCase : int , __UpperCamelCase : Optional[int]=False , __UpperCamelCase : Optional[int]=1 ) -> Any:
"""simple docstring"""
self.assertIsInstance(__UpperCamelCase , __UpperCamelCase )
self.assertListEqual(
[isinstance(__UpperCamelCase , __UpperCamelCase ) for iter_hidden_states in hidden_states] , [True] * len(__UpperCamelCase ) , )
self.assertEqual(len(__UpperCamelCase ) , (max_length - min_length) * num_beam_groups )
for idx, iter_hidden_states in enumerate(__UpperCamelCase ):
# adds PAD dummy token
snake_case__ : List[Any] = min_length + idx + 1
snake_case__ : int = (batch_size * num_beam_groups, seq_len, config.hidden_size)
# check hidden size
self.assertListEqual(
[layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(__UpperCamelCase ) , )
pass
@slow
def lowerCAmelCase ( self : Dict ) -> Union[str, Any]:
"""simple docstring"""
for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
snake_case__ : int = XLMModel.from_pretrained(__UpperCamelCase )
self.assertIsNotNone(__UpperCamelCase )
@require_torch
class _SCREAMING_SNAKE_CASE (unittest.TestCase ):
@slow
def lowerCAmelCase ( self : Any ) -> Tuple:
"""simple docstring"""
snake_case__ : Dict = XLMWithLMHeadModel.from_pretrained('''xlm-mlm-en-2048''' )
model.to(__UpperCamelCase )
snake_case__ : Optional[Any] = torch.tensor([[14, 447]] , dtype=torch.long , device=__UpperCamelCase ) # the president
snake_case__ : List[Any] = [
14,
447,
14,
447,
14,
447,
14,
447,
14,
447,
14,
447,
14,
447,
14,
447,
14,
447,
14,
447,
] # the president the president the president the president the president the president the president the president the president the president
# TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference
snake_case__ : List[str] = model.generate(__UpperCamelCase , do_sample=__UpperCamelCase )
self.assertListEqual(output_ids[0].cpu().numpy().tolist() , __UpperCamelCase )
| 703 |
'''simple docstring'''
import argparse
import os
import re
_lowercase : str ="src/transformers"
# Pattern that looks at the indentation in a line.
_lowercase : List[Any] =re.compile(R"^(\s*)\S")
# Pattern that matches `"key":" and puts `key` in group 0.
_lowercase : Optional[Any] =re.compile(R"^\s*\"([^\"]+)\":")
# Pattern that matches `_import_structure["key"]` and puts `key` in group 0.
_lowercase : Tuple =re.compile(R"^\s*_import_structure\[\"([^\"]+)\"\]")
# Pattern that matches `"key",` and puts `key` in group 0.
_lowercase : List[Any] =re.compile(R"^\s*\"([^\"]+)\",\s*$")
# Pattern that matches any `[stuff]` and puts `stuff` in group 0.
_lowercase : int =re.compile(R"\[([^\]]+)\]")
def __UpperCAmelCase ( UpperCamelCase__ :List[str] ) -> Tuple:
snake_case__ : str = _re_indent.search(UpperCamelCase__ )
return "" if search is None else search.groups()[0]
def __UpperCAmelCase ( UpperCamelCase__ :int , UpperCamelCase__ :int="" , UpperCamelCase__ :Optional[int]=None , UpperCamelCase__ :str=None ) -> int:
snake_case__ : Union[str, Any] = 0
snake_case__ : int = code.split('''\n''' )
if start_prompt is not None:
while not lines[index].startswith(UpperCamelCase__ ):
index += 1
snake_case__ : Dict = ['''\n'''.join(lines[:index] )]
else:
snake_case__ : Union[str, Any] = []
# We split into blocks until we get to the `end_prompt` (or the end of the block).
snake_case__ : int = [lines[index]]
index += 1
while index < len(UpperCamelCase__ ) and (end_prompt is None or not lines[index].startswith(UpperCamelCase__ )):
if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level:
if len(UpperCamelCase__ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + ''' ''' ):
current_block.append(lines[index] )
blocks.append('''\n'''.join(UpperCamelCase__ ) )
if index < len(UpperCamelCase__ ) - 1:
snake_case__ : Any = [lines[index + 1]]
index += 1
else:
snake_case__ : Any = []
else:
blocks.append('''\n'''.join(UpperCamelCase__ ) )
snake_case__ : List[str] = [lines[index]]
else:
current_block.append(lines[index] )
index += 1
# Adds current block if it's nonempty.
if len(UpperCamelCase__ ) > 0:
blocks.append('''\n'''.join(UpperCamelCase__ ) )
# Add final block after end_prompt if provided.
if end_prompt is not None and index < len(UpperCamelCase__ ):
blocks.append('''\n'''.join(lines[index:] ) )
return blocks
def __UpperCAmelCase ( UpperCamelCase__ :Union[str, Any] ) -> int:
def _inner(UpperCamelCase__ :Dict ):
return key(UpperCamelCase__ ).lower().replace('''_''' , '''''' )
return _inner
def __UpperCAmelCase ( UpperCamelCase__ :str , UpperCamelCase__ :List[str]=None ) -> Optional[Any]:
# If no key is provided, we use a noop.
def noop(UpperCamelCase__ :List[str] ):
return x
if key is None:
snake_case__ : Optional[Any] = noop
# Constants are all uppercase, they go first.
snake_case__ : Dict = [obj for obj in objects if key(UpperCamelCase__ ).isupper()]
# Classes are not all uppercase but start with a capital, they go second.
snake_case__ : Optional[int] = [obj for obj in objects if key(UpperCamelCase__ )[0].isupper() and not key(UpperCamelCase__ ).isupper()]
# Functions begin with a lowercase, they go last.
snake_case__ : Any = [obj for obj in objects if not key(UpperCamelCase__ )[0].isupper()]
snake_case__ : Union[str, Any] = ignore_underscore(UpperCamelCase__ )
return sorted(UpperCamelCase__ , key=UpperCamelCase__ ) + sorted(UpperCamelCase__ , key=UpperCamelCase__ ) + sorted(UpperCamelCase__ , key=UpperCamelCase__ )
def __UpperCAmelCase ( UpperCamelCase__ :List[Any] ) -> List[Any]:
# This inner function sort imports between [ ].
def _replace(UpperCamelCase__ :Union[str, Any] ):
snake_case__ : Union[str, Any] = match.groups()[0]
if "," not in imports:
return F'''[{imports}]'''
snake_case__ : Dict = [part.strip().replace('''"''' , '''''' ) for part in imports.split(''',''' )]
# We will have a final empty element if the line finished with a comma.
if len(keys[-1] ) == 0:
snake_case__ : Tuple = keys[:-1]
return "[" + ", ".join([F'''"{k}"''' for k in sort_objects(UpperCamelCase__ )] ) + "]"
snake_case__ : Optional[int] = import_statement.split('''\n''' )
if len(UpperCamelCase__ ) > 3:
# Here we have to sort internal imports that are on several lines (one per name):
# key: [
# "object1",
# "object2",
# ...
# ]
# We may have to ignore one or two lines on each side.
snake_case__ : Optional[Any] = 2 if lines[1].strip() == '''[''' else 1
snake_case__ : Union[str, Any] = [(i, _re_strip_line.search(UpperCamelCase__ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )]
snake_case__ : Dict = sort_objects(UpperCamelCase__ , key=lambda UpperCamelCase__ : x[1] )
snake_case__ : Any = [lines[x[0] + idx] for x in sorted_indices]
return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] )
elif len(UpperCamelCase__ ) == 3:
# Here we have to sort internal imports that are on one separate line:
# key: [
# "object1", "object2", ...
# ]
if _re_bracket_content.search(lines[1] ) is not None:
snake_case__ : Union[str, Any] = _re_bracket_content.sub(_replace , lines[1] )
else:
snake_case__ : Any = [part.strip().replace('''"''' , '''''' ) for part in lines[1].split(''',''' )]
# We will have a final empty element if the line finished with a comma.
if len(keys[-1] ) == 0:
snake_case__ : Dict = keys[:-1]
snake_case__ : Union[str, Any] = get_indent(lines[1] ) + ''', '''.join([F'''"{k}"''' for k in sort_objects(UpperCamelCase__ )] )
return "\n".join(UpperCamelCase__ )
else:
# Finally we have to deal with imports fitting on one line
snake_case__ : Dict = _re_bracket_content.sub(_replace , UpperCamelCase__ )
return import_statement
def __UpperCAmelCase ( UpperCamelCase__ :Optional[int] , UpperCamelCase__ :Dict=True ) -> Dict:
with open(UpperCamelCase__ , encoding='''utf-8''' ) as f:
snake_case__ : Optional[int] = f.read()
if "_import_structure" not in code:
return
# Blocks of indent level 0
snake_case__ : Optional[Any] = split_code_in_indented_blocks(
UpperCamelCase__ , start_prompt='''_import_structure = {''' , end_prompt='''if TYPE_CHECKING:''' )
# We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt).
for block_idx in range(1 , len(UpperCamelCase__ ) - 1 ):
# Check if the block contains some `_import_structure`s thingy to sort.
snake_case__ : Any = main_blocks[block_idx]
snake_case__ : Dict = block.split('''\n''' )
# Get to the start of the imports.
snake_case__ : List[str] = 0
while line_idx < len(UpperCamelCase__ ) and "_import_structure" not in block_lines[line_idx]:
# Skip dummy import blocks
if "import dummy" in block_lines[line_idx]:
snake_case__ : List[Any] = len(UpperCamelCase__ )
else:
line_idx += 1
if line_idx >= len(UpperCamelCase__ ):
continue
# Ignore beginning and last line: they don't contain anything.
snake_case__ : Optional[Any] = '''\n'''.join(block_lines[line_idx:-1] )
snake_case__ : Dict = get_indent(block_lines[1] )
# Slit the internal block into blocks of indent level 1.
snake_case__ : List[str] = split_code_in_indented_blocks(UpperCamelCase__ , indent_level=UpperCamelCase__ )
# We have two categories of import key: list or _import_structure[key].append/extend
snake_case__ : Tuple = _re_direct_key if '''_import_structure = {''' in block_lines[0] else _re_indirect_key
# Grab the keys, but there is a trap: some lines are empty or just comments.
snake_case__ : Optional[int] = [(pattern.search(UpperCamelCase__ ).groups()[0] if pattern.search(UpperCamelCase__ ) is not None else None) for b in internal_blocks]
# We only sort the lines with a key.
snake_case__ : Any = [(i, key) for i, key in enumerate(UpperCamelCase__ ) if key is not None]
snake_case__ : Optional[int] = [x[0] for x in sorted(UpperCamelCase__ , key=lambda UpperCamelCase__ : x[1] )]
# We reorder the blocks by leaving empty lines/comments as they were and reorder the rest.
snake_case__ : Dict = 0
snake_case__ : Dict = []
for i in range(len(UpperCamelCase__ ) ):
if keys[i] is None:
reorderded_blocks.append(internal_blocks[i] )
else:
snake_case__ : Tuple = sort_objects_in_import(internal_blocks[sorted_indices[count]] )
reorderded_blocks.append(UpperCamelCase__ )
count += 1
# And we put our main block back together with its first and last line.
snake_case__ : int = '''\n'''.join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] )
if code != "\n".join(UpperCamelCase__ ):
if check_only:
return True
else:
print(F'''Overwriting {file}.''' )
with open(UpperCamelCase__ , '''w''' , encoding='''utf-8''' ) as f:
f.write('''\n'''.join(UpperCamelCase__ ) )
def __UpperCAmelCase ( UpperCamelCase__ :Optional[Any]=True ) -> Union[str, Any]:
snake_case__ : str = []
for root, _, files in os.walk(UpperCamelCase__ ):
if "__init__.py" in files:
snake_case__ : int = sort_imports(os.path.join(UpperCamelCase__ , '''__init__.py''' ) , check_only=UpperCamelCase__ )
if result:
snake_case__ : Optional[Any] = [os.path.join(UpperCamelCase__ , '''__init__.py''' )]
if len(UpperCamelCase__ ) > 0:
raise ValueError(F'''Would overwrite {len(UpperCamelCase__ )} files, run `make style`.''' )
if __name__ == "__main__":
_lowercase : Optional[Any] =argparse.ArgumentParser()
parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.")
_lowercase : Tuple =parser.parse_args()
sort_imports_in_all_inits(check_only=args.check_only)
| 574 | 0 |
"""simple docstring"""
import numpy as np
def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase ):
return np.where(vector > 0 , __UpperCamelCase , (alpha * (np.exp(__UpperCamelCase ) - 1)) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 76 |
"""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': 2_5_6,
}
a_ = {
'Pregnancy': 1_6_8_6_2_9,
'Christianity': 7_6_7_5,
'Explain': 1_0_6_4_2_3,
'Fitness': 6_3_4_4_0,
'Saving': 6_3_1_6_3,
'Ask': 2_7_1_7_1,
'Ass': 9_5_9_8_5,
'Joke': 1_6_3_5_0_9,
'Questions': 4_5_6_2_2,
'Thoughts': 4_9_6_0_5,
'Retail': 5_2_3_4_2,
'Feminism': 1_6_4_3_3_8,
'Writing': 1_1_9_9_2,
'Atheism': 1_9_2_2_6_3,
'Netflix': 4_8_6_1_6,
'Computing': 3_9_6_3_9,
'Opinion': 4_3_2_1_3,
'Alone': 4_4_9_6_7,
'Funny': 5_8_9_1_7,
'Gaming': 4_0_3_5_8,
'Human': 4_0_8_8,
'India': 1_3_3_1,
'Joker': 7_7_1_3_8,
'Diet': 3_6_2_0_6,
'Legal': 1_1_8_5_9,
'Norman': 4_9_3_9,
'Tip': 7_2_6_8_9,
'Weight': 5_2_3_4_3,
'Movies': 4_6_2_7_3,
'Running': 2_3_4_2_5,
'Science': 2_0_9_0,
'Horror': 3_7_7_9_3,
'Confession': 6_0_5_7_2,
'Finance': 1_2_2_5_0,
'Politics': 1_6_3_6_0,
'Scary': 1_9_1_9_8_5,
'Support': 1_2_6_5_4,
'Technologies': 3_2_5_1_6,
'Teenage': 6_6_1_6_0,
'Event': 3_2_7_6_9,
'Learned': 6_7_4_6_0,
'Notion': 1_8_2_7_7_0,
'Wikipedia': 3_7_5_8_3,
'Books': 6_6_6_5,
'Extract': 7_6_0_5_0,
'Confessions': 1_0_2_7_0_1,
'Conspiracy': 7_5_9_3_2,
'Links': 6_3_6_7_4,
'Narcissus': 1_5_0_4_2_5,
'Relationship': 5_4_7_6_6,
'Relationships': 1_3_4_7_9_6,
'Reviews': 4_1_6_7_1,
'News': 4_2_5_6,
'Translation': 2_6_8_2_0,
'multilingual': 1_2_8_4_0_6,
}
def __UpperCAmelCase ( __UpperCamelCase ):
__lowercase : Any = set()
__lowercase : Tuple = word[0]
for char in word[1:]:
pairs.add((prev_char, char) )
__lowercase : Any = char
__lowercase : List[Any] = set(__UpperCamelCase )
return pairs
class UpperCAmelCase_ ( snake_case ):
UpperCamelCase =VOCAB_FILES_NAMES
UpperCamelCase =PRETRAINED_VOCAB_FILES_MAP
UpperCamelCase =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
UpperCamelCase =CONTROL_CODES
def __init__( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_="<unk>" , **UpperCamelCase_ ) -> int:
super().__init__(unk_token=UpperCamelCase_ , **UpperCamelCase_ )
with open(UpperCamelCase_ , encoding='''utf-8''' ) as vocab_handle:
__lowercase : List[Any] = json.load(UpperCamelCase_ )
__lowercase : Any = {v: k for k, v in self.encoder.items()}
with open(UpperCamelCase_ , encoding='''utf-8''' ) as merges_handle:
__lowercase : Optional[Any] = merges_handle.read().split('''\n''' )[1:-1]
__lowercase : Optional[Any] = [tuple(merge.split() ) for merge in merges]
__lowercase : Optional[int] = dict(zip(UpperCamelCase_ , range(len(UpperCamelCase_ ) ) ) )
__lowercase : Optional[Any] = {}
@property
def _lowerCamelCase ( self ) -> Union[str, Any]:
return len(self.encoder )
def _lowerCamelCase ( self ) -> Tuple:
return dict(self.encoder , **self.added_tokens_encoder )
def _lowerCamelCase ( self , UpperCamelCase_ ) -> str:
if token in self.cache:
return self.cache[token]
__lowercase : str = tuple(UpperCamelCase_ )
__lowercase : str = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] )
__lowercase : Optional[Any] = get_pairs(UpperCamelCase_ )
if not pairs:
return token
while True:
__lowercase : Dict = min(UpperCamelCase_ , key=lambda UpperCamelCase_ : self.bpe_ranks.get(UpperCamelCase_ , float('''inf''' ) ) )
if bigram not in self.bpe_ranks:
break
__lowercase ,__lowercase : Tuple = bigram
__lowercase : int = []
__lowercase : Union[str, Any] = 0
while i < len(UpperCamelCase_ ):
try:
__lowercase : Optional[int] = word.index(UpperCamelCase_ , UpperCamelCase_ )
except ValueError:
new_word.extend(word[i:] )
break
else:
new_word.extend(word[i:j] )
__lowercase : Tuple = 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
__lowercase : List[str] = tuple(UpperCamelCase_ )
__lowercase : str = new_word
if len(UpperCamelCase_ ) == 1:
break
else:
__lowercase : List[str] = get_pairs(UpperCamelCase_ )
__lowercase : Optional[Any] = '''@@ '''.join(UpperCamelCase_ )
__lowercase : Dict = word[:-4]
__lowercase : str = word
return word
def _lowerCamelCase ( self , UpperCamelCase_ ) -> str:
__lowercase : List[Any] = []
__lowercase : int = re.findall(R'''\S+\n?''' , UpperCamelCase_ )
for token in words:
split_tokens.extend(list(self.bpe(UpperCamelCase_ ).split(''' ''' ) ) )
return split_tokens
def _lowerCamelCase ( self , UpperCamelCase_ ) -> Optional[Any]:
return self.encoder.get(UpperCamelCase_ , self.encoder.get(self.unk_token ) )
def _lowerCamelCase ( self , UpperCamelCase_ ) -> int:
return self.decoder.get(UpperCamelCase_ , self.unk_token )
def _lowerCamelCase ( self , UpperCamelCase_ ) -> Optional[int]:
__lowercase : Tuple = ''' '''.join(UpperCamelCase_ ).replace('''@@ ''' , '''''' ).strip()
return out_string
def _lowerCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ = None ) -> Tuple[str]:
if not os.path.isdir(UpperCamelCase_ ):
logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" )
return
__lowercase : Optional[Any] = os.path.join(
UpperCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
__lowercase : Optional[int] = 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''' )
__lowercase : List[str] = 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!''' )
__lowercase : Union[str, Any] = 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)
| 76 | 1 |
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer
from ...utils import logging
__magic_name__ =logging.get_logger(__name__)
__magic_name__ ='''▁'''
__magic_name__ ={'''vocab_file''': '''sentencepiece.bpe.model'''}
__magic_name__ ={
'''vocab_file''': {
'''facebook/nllb-200-distilled-600M''': (
'''https://huggingface.co/facebook/nllb-200-distilled-600M/blob/main/sentencepiece.bpe.model'''
),
}
}
__magic_name__ ={
'''facebook/nllb-200-distilled-600M''': 1024,
}
# fmt: off
__magic_name__ =['''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 _A ( __UpperCamelCase ):
SCREAMING_SNAKE_CASE_ : List[Any] =VOCAB_FILES_NAMES
SCREAMING_SNAKE_CASE_ : List[str] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
SCREAMING_SNAKE_CASE_ : Dict =PRETRAINED_VOCAB_FILES_MAP
SCREAMING_SNAKE_CASE_ : List[str] =["input_ids", "attention_mask"]
SCREAMING_SNAKE_CASE_ : List[int] =[]
SCREAMING_SNAKE_CASE_ : List[int] =[]
def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ , ) -> str:
'''simple docstring'''
UpperCamelCase__ = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else mask_token
UpperCamelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs
UpperCamelCase__ = legacy_behaviour
super().__init__(
bos_token=SCREAMING_SNAKE_CASE_ , eos_token=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , src_lang=SCREAMING_SNAKE_CASE_ , tgt_lang=SCREAMING_SNAKE_CASE_ , additional_special_tokens=SCREAMING_SNAKE_CASE_ , sp_model_kwargs=self.sp_model_kwargs , legacy_behaviour=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , )
UpperCamelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(str(SCREAMING_SNAKE_CASE_ ) )
UpperCamelCase__ = vocab_file
# Original fairseq vocab and spm vocab must be "aligned":
# Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
# -------- | ------- | ------- | ------ | ------- | ---- | ---- | ---- | ---- | ---- | ----
# fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | 'an' | '▁n' | '▁m' | '▁t' | '▁k' | '▁a'
# spm | '<unk>' | '<s>' | '</s>' | 'an' | '▁n' | '▁m' | '▁t' | '▁k' | '▁a' | '▁s'
# Mimic fairseq token-to-id alignment for the first 4 token
UpperCamelCase__ = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3}
# The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
UpperCamelCase__ = 1
UpperCamelCase__ = len(self.sp_model )
UpperCamelCase__ = {
code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(SCREAMING_SNAKE_CASE_ )
}
UpperCamelCase__ = {v: k for k, v in self.lang_code_to_id.items()}
UpperCamelCase__ = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset
self.fairseq_tokens_to_ids.update(self.lang_code_to_id )
UpperCamelCase__ = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
UpperCamelCase__ = list(self.lang_code_to_id.keys() )
if additional_special_tokens is not None:
# Only add those special tokens if they are not already there.
self._additional_special_tokens.extend(
[t for t in additional_special_tokens if t not in self._additional_special_tokens] )
UpperCamelCase__ = src_lang if src_lang is not None else '''eng_Latn'''
UpperCamelCase__ = self.lang_code_to_id[self._src_lang]
UpperCamelCase__ = tgt_lang
self.set_src_lang_special_tokens(self._src_lang )
def __getstate__(self ) -> Any:
'''simple docstring'''
UpperCamelCase__ = self.__dict__.copy()
UpperCamelCase__ = None
UpperCamelCase__ = self.sp_model.serialized_model_proto()
return state
def __setstate__(self , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]:
'''simple docstring'''
UpperCamelCase__ = d
# for backward compatibility
if not hasattr(self , '''sp_model_kwargs''' ):
UpperCamelCase__ = {}
UpperCamelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.LoadFromSerializedProto(self.sp_model_proto )
@property
def _a (self ) -> Tuple:
'''simple docstring'''
return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token
@property
def _a (self ) -> str:
'''simple docstring'''
return self._src_lang
@src_lang.setter
def _a (self , SCREAMING_SNAKE_CASE_ ) -> None:
'''simple docstring'''
UpperCamelCase__ = new_src_lang
self.set_src_lang_special_tokens(self._src_lang )
def _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ) -> List[int]:
'''simple docstring'''
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=SCREAMING_SNAKE_CASE_ , token_ids_a=SCREAMING_SNAKE_CASE_ , already_has_special_tokens=SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = [1] * len(self.prefix_tokens )
UpperCamelCase__ = [1] * len(self.suffix_tokens )
if token_ids_a is None:
return prefix_ones + ([0] * len(SCREAMING_SNAKE_CASE_ )) + suffix_ones
return prefix_ones + ([0] * len(SCREAMING_SNAKE_CASE_ )) + ([0] * len(SCREAMING_SNAKE_CASE_ )) + suffix_ones
def _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]:
'''simple docstring'''
if token_ids_a is None:
return self.prefix_tokens + token_ids_a + self.suffix_tokens
# We don't expect to process pairs, but leave the pair logic for API consistency
return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens
def _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]:
'''simple docstring'''
UpperCamelCase__ = [self.sep_token_id]
UpperCamelCase__ = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
def _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> List[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''' )
UpperCamelCase__ = src_lang
UpperCamelCase__ = self(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = self.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = tgt_lang_id
return inputs
def _a (self ) -> str:
'''simple docstring'''
UpperCamelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def _a (self , SCREAMING_SNAKE_CASE_ ) -> List[str]:
'''simple docstring'''
return self.sp_model.encode(SCREAMING_SNAKE_CASE_ , out_type=SCREAMING_SNAKE_CASE_ )
def _a (self , SCREAMING_SNAKE_CASE_ ) -> Optional[int]:
'''simple docstring'''
if token in self.fairseq_tokens_to_ids:
return self.fairseq_tokens_to_ids[token]
UpperCamelCase__ = self.sp_model.PieceToId(SCREAMING_SNAKE_CASE_ )
# Need to return unknown token if the SP model returned 0
return spm_id + self.fairseq_offset if spm_id else self.unk_token_id
def _a (self , SCREAMING_SNAKE_CASE_ ) -> str:
'''simple docstring'''
if index in self.fairseq_ids_to_tokens:
return self.fairseq_ids_to_tokens[index]
return self.sp_model.IdToPiece(index - self.fairseq_offset )
def _a (self , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]:
'''simple docstring'''
UpperCamelCase__ = ''''''.join(SCREAMING_SNAKE_CASE_ ).replace(SCREAMING_SNAKE_CASE_ , ''' ''' ).strip()
return out_string
def _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]:
'''simple docstring'''
if not os.path.isdir(SCREAMING_SNAKE_CASE_ ):
logger.error(F"Vocabulary path ({save_directory}) should be a directory" )
return
UpperCamelCase__ = 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_ ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , SCREAMING_SNAKE_CASE_ )
elif not os.path.isfile(self.vocab_file ):
with open(SCREAMING_SNAKE_CASE_ , '''wb''' ) as fi:
UpperCamelCase__ = self.sp_model.serialized_model_proto()
fi.write(SCREAMING_SNAKE_CASE_ )
return (out_vocab_file,)
def _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = "eng_Latn" , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "fra_Latn" , **SCREAMING_SNAKE_CASE_ , ) -> BatchEncoding:
'''simple docstring'''
UpperCamelCase__ = src_lang
UpperCamelCase__ = tgt_lang
return super().prepare_seqaseq_batch(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
def _a (self ) -> Union[str, Any]:
'''simple docstring'''
return self.set_src_lang_special_tokens(self.src_lang )
def _a (self ) -> Dict:
'''simple docstring'''
return self.set_tgt_lang_special_tokens(self.tgt_lang )
def _a (self , SCREAMING_SNAKE_CASE_ ) -> None:
'''simple docstring'''
UpperCamelCase__ = self.lang_code_to_id[src_lang]
if self.legacy_behaviour:
UpperCamelCase__ = []
UpperCamelCase__ = [self.eos_token_id, self.cur_lang_code]
else:
UpperCamelCase__ = [self.cur_lang_code]
UpperCamelCase__ = [self.eos_token_id]
def _a (self , SCREAMING_SNAKE_CASE_ ) -> None:
'''simple docstring'''
UpperCamelCase__ = self.lang_code_to_id[lang]
if self.legacy_behaviour:
UpperCamelCase__ = []
UpperCamelCase__ = [self.eos_token_id, self.cur_lang_code]
else:
UpperCamelCase__ = [self.cur_lang_code]
UpperCamelCase__ = [self.eos_token_id]
| 469 | 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 __UpperCamelCase ( A ):
if isinstance(A , collections.abc.Iterable ):
return x
return (x, x)
@require_flax
class _A :
def _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple:
'''simple docstring'''
pass
def _a (self ) -> Optional[int]:
'''simple docstring'''
pass
def _a (self ) -> Tuple:
'''simple docstring'''
pass
def _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any:
'''simple docstring'''
UpperCamelCase__ = np.abs((a - b) ).max()
self.assertLessEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , F"Difference between torch and flax is {diff} (>= {tol})." )
def _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ) -> Dict:
'''simple docstring'''
UpperCamelCase__ = VisionTextDualEncoderConfig.from_vision_text_configs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = FlaxVisionTextDualEncoderModel(SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = model(input_ids=SCREAMING_SNAKE_CASE_ , pixel_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )
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 _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ) -> int:
'''simple docstring'''
UpperCamelCase__ , UpperCamelCase__ = self.get_vision_text_model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = {'''vision_model''': vision_model, '''text_model''': text_model}
UpperCamelCase__ = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = model(input_ids=SCREAMING_SNAKE_CASE_ , pixel_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )
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 _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ) -> List[Any]:
'''simple docstring'''
UpperCamelCase__ , UpperCamelCase__ = self.get_vision_text_model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = {'''vision_model''': vision_model, '''text_model''': text_model}
UpperCamelCase__ = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = model(input_ids=SCREAMING_SNAKE_CASE_ , pixel_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = output[0]
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = FlaxVisionTextDualEncoderModel.from_pretrained(SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = model(input_ids=SCREAMING_SNAKE_CASE_ , pixel_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = after_output[0]
UpperCamelCase__ = np.amax(np.abs(out_a - out_a ) )
self.assertLessEqual(SCREAMING_SNAKE_CASE_ , 1E-3 )
def _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ) -> Any:
'''simple docstring'''
UpperCamelCase__ , UpperCamelCase__ = self.get_vision_text_model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = {'''vision_model''': vision_model, '''text_model''': text_model}
UpperCamelCase__ = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = model(
input_ids=SCREAMING_SNAKE_CASE_ , pixel_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , output_attentions=SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = output.vision_model_output.attentions
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , vision_config.num_hidden_layers )
# in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
UpperCamelCase__ = to_atuple(vision_model.config.image_size )
UpperCamelCase__ = to_atuple(vision_model.config.patch_size )
UpperCamelCase__ = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
UpperCamelCase__ = num_patches + 1
self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) )
UpperCamelCase__ = output.text_model_output.attentions
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 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 _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[str]:
'''simple docstring'''
pt_model.to(SCREAMING_SNAKE_CASE_ )
pt_model.eval()
# prepare inputs
UpperCamelCase__ = inputs_dict
UpperCamelCase__ = {k: torch.tensor(v.tolist() ) for k, v in flax_inputs.items()}
with torch.no_grad():
UpperCamelCase__ = pt_model(**SCREAMING_SNAKE_CASE_ ).to_tuple()
UpperCamelCase__ = fx_model(**SCREAMING_SNAKE_CASE_ ).to_tuple()
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) , '''Output lengths differ between Flax and PyTorch''' )
for fx_output, pt_output in zip(fx_outputs[:4] , pt_outputs[:4] ):
self.assert_almost_equals(SCREAMING_SNAKE_CASE_ , pt_output.numpy() , 4E-2 )
# PT -> Flax
with tempfile.TemporaryDirectory() as tmpdirname:
pt_model.save_pretrained(SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = FlaxVisionTextDualEncoderModel.from_pretrained(SCREAMING_SNAKE_CASE_ , from_pt=SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = fx_model_loaded(**SCREAMING_SNAKE_CASE_ ).to_tuple()
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) , '''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(SCREAMING_SNAKE_CASE_ , pt_output.numpy() , 4E-2 )
# Flax -> PT
with tempfile.TemporaryDirectory() as tmpdirname:
fx_model.save_pretrained(SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = VisionTextDualEncoderModel.from_pretrained(SCREAMING_SNAKE_CASE_ , from_flax=SCREAMING_SNAKE_CASE_ )
pt_model_loaded.to(SCREAMING_SNAKE_CASE_ )
pt_model_loaded.eval()
with torch.no_grad():
UpperCamelCase__ = pt_model_loaded(**SCREAMING_SNAKE_CASE_ ).to_tuple()
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) , '''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(SCREAMING_SNAKE_CASE_ , pt_output_loaded.numpy() , 4E-2 )
def _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple:
'''simple docstring'''
UpperCamelCase__ = VisionTextDualEncoderConfig.from_vision_text_configs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = VisionTextDualEncoderModel(SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = FlaxVisionTextDualEncoderModel(SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = fx_state
self.check_pt_flax_equivalence(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
def _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str:
'''simple docstring'''
UpperCamelCase__ = VisionTextDualEncoderConfig.from_vision_text_configs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = VisionTextDualEncoderModel(SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = FlaxVisionTextDualEncoderModel(SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = load_flax_weights_in_pytorch_model(SCREAMING_SNAKE_CASE_ , fx_model.params )
self.check_pt_flax_equivalence(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
def _a (self ) -> str:
'''simple docstring'''
UpperCamelCase__ = self.prepare_config_and_inputs()
self.check_model_from_pretrained_configs(**SCREAMING_SNAKE_CASE_ )
def _a (self ) -> str:
'''simple docstring'''
UpperCamelCase__ = self.prepare_config_and_inputs()
self.check_vision_text_dual_encoder_from_pretrained(**SCREAMING_SNAKE_CASE_ )
def _a (self ) -> Dict:
'''simple docstring'''
UpperCamelCase__ = self.prepare_config_and_inputs()
self.check_save_load(**SCREAMING_SNAKE_CASE_ )
def _a (self ) -> Union[str, Any]:
'''simple docstring'''
UpperCamelCase__ = self.prepare_config_and_inputs()
self.check_vision_text_output_attention(**SCREAMING_SNAKE_CASE_ )
@is_pt_flax_cross_test
def _a (self ) -> str:
'''simple docstring'''
UpperCamelCase__ = self.prepare_config_and_inputs()
UpperCamelCase__ = config_inputs_dict.pop('''vision_config''' )
UpperCamelCase__ = config_inputs_dict.pop('''text_config''' )
UpperCamelCase__ = config_inputs_dict
self.check_equivalence_pt_to_flax(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.check_equivalence_flax_to_pt(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
@slow
def _a (self ) -> Tuple:
'''simple docstring'''
UpperCamelCase__ , UpperCamelCase__ = self.get_pretrained_model_and_inputs()
UpperCamelCase__ = model_a(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = outputs[0]
with tempfile.TemporaryDirectory() as tmp_dirname:
model_a.save_pretrained(SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = FlaxVisionTextDualEncoderModel.from_pretrained(SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = model_a(**SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = after_outputs[0]
UpperCamelCase__ = np.amax(np.abs(out_a - out_a ) )
self.assertLessEqual(SCREAMING_SNAKE_CASE_ , 1E-5 )
@require_flax
class _A ( __UpperCamelCase , unittest.TestCase ):
def _a (self ) -> Any:
'''simple docstring'''
UpperCamelCase__ = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
'''hf-internal-testing/tiny-random-vit''' , '''hf-internal-testing/tiny-bert''' , vision_from_pt=SCREAMING_SNAKE_CASE_ , text_from_pt=SCREAMING_SNAKE_CASE_ , )
UpperCamelCase__ = 13
UpperCamelCase__ = floats_tensor(
[
batch_size,
model.config.vision_config.num_channels,
model.config.vision_config.image_size,
model.config.vision_config.image_size,
] )
UpperCamelCase__ = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size )
UpperCamelCase__ = random_attention_mask([batch_size, 4] )
UpperCamelCase__ = {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}
return model, inputs
def _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]:
'''simple docstring'''
UpperCamelCase__ = FlaxViTModel(SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = FlaxBertModel(SCREAMING_SNAKE_CASE_ )
return vision_model, text_model
def _a (self ) -> Optional[Any]:
'''simple docstring'''
UpperCamelCase__ = FlaxViTModelTester(self )
UpperCamelCase__ = FlaxBertModelTester(self )
UpperCamelCase__ = vit_model_tester.prepare_config_and_inputs()
UpperCamelCase__ = bert_model_tester.prepare_config_and_inputs()
UpperCamelCase__ , UpperCamelCase__ = vision_config_and_inputs
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = 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 _A ( __UpperCamelCase , unittest.TestCase ):
def _a (self ) -> Dict:
'''simple docstring'''
UpperCamelCase__ = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
'''hf-internal-testing/tiny-random-clip''' , '''hf-internal-testing/tiny-bert''' , vision_from_pt=SCREAMING_SNAKE_CASE_ , text_from_pt=SCREAMING_SNAKE_CASE_ , )
UpperCamelCase__ = 13
UpperCamelCase__ = floats_tensor(
[
batch_size,
model.config.vision_config.num_channels,
model.config.vision_config.image_size,
model.config.vision_config.image_size,
] )
UpperCamelCase__ = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size )
UpperCamelCase__ = random_attention_mask([batch_size, 4] )
UpperCamelCase__ = {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}
return model, inputs
def _a (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> int:
'''simple docstring'''
UpperCamelCase__ = FlaxCLIPVisionModel(SCREAMING_SNAKE_CASE_ )
UpperCamelCase__ = FlaxBertModel(SCREAMING_SNAKE_CASE_ )
return vision_model, text_model
def _a (self ) -> List[Any]:
'''simple docstring'''
UpperCamelCase__ = FlaxCLIPVisionModelTester(self )
UpperCamelCase__ = FlaxBertModelTester(self )
UpperCamelCase__ = clip_model_tester.prepare_config_and_inputs()
UpperCamelCase__ = bert_model_tester.prepare_config_and_inputs()
UpperCamelCase__ , UpperCamelCase__ = vision_config_and_inputs
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = 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 _A ( unittest.TestCase ):
@slow
def _a (self ) -> int:
'''simple docstring'''
UpperCamelCase__ = FlaxVisionTextDualEncoderModel.from_pretrained('''clip-italian/clip-italian''' , logit_scale_init_value=1.0 )
UpperCamelCase__ = VisionTextDualEncoderProcessor.from_pretrained('''clip-italian/clip-italian''' )
UpperCamelCase__ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
UpperCamelCase__ = processor(
text=['''una foto di un gatto''', '''una foto di un cane'''] , images=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' )
UpperCamelCase__ = model(**SCREAMING_SNAKE_CASE_ )
# 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]) , )
UpperCamelCase__ = np.array([[1.2284727, 0.3104122]] )
self.assertTrue(np.allclose(outputs.logits_per_image , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) )
| 469 | 1 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
lowercase__ = {
"""configuration_mctct""": ["""MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MCTCTConfig"""],
"""feature_extraction_mctct""": ["""MCTCTFeatureExtractor"""],
"""processing_mctct""": ["""MCTCTProcessor"""],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase__ = [
"""MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""MCTCTForCTC""",
"""MCTCTModel""",
"""MCTCTPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig
from .feature_extraction_mctct import MCTCTFeatureExtractor
from .processing_mctct import MCTCTProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel
else:
import sys
lowercase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 610 |
"""simple docstring"""
# Lint as: python3
import itertools
import os
import re
lowercase__ = re.compile(r"""([A-Z]+)([A-Z][a-z])""")
lowercase__ = re.compile(r"""([a-z\d])([A-Z])""")
lowercase__ = re.compile(r"""(?<!_)_(?!_)""")
lowercase__ = re.compile(r"""(_{2,})""")
lowercase__ = r"""^\w+(\.\w+)*$"""
lowercase__ = r"""<>:/\|?*"""
def __lowerCamelCase ( __UpperCamelCase ) -> Tuple:
"""simple docstring"""
lowerCAmelCase_ : Tuple = _uppercase_uppercase_re.sub(r"\1_\2" , __UpperCamelCase )
lowerCAmelCase_ : Dict = _lowercase_uppercase_re.sub(r"\1_\2" , __UpperCamelCase )
return name.lower()
def __lowerCamelCase ( __UpperCamelCase ) -> List[Any]:
"""simple docstring"""
lowerCAmelCase_ : Optional[Any] = _single_underscore_re.split(__UpperCamelCase )
lowerCAmelCase_ : str = [_multiple_underscores_re.split(__UpperCamelCase ) for n in name]
return "".join(n.capitalize() for n in itertools.chain.from_iterable(__UpperCamelCase ) if n != "" )
def __lowerCamelCase ( __UpperCamelCase ) -> Optional[int]:
"""simple docstring"""
if os.path.basename(__UpperCamelCase ) != name:
raise ValueError(f'''Should be a dataset name, not a path: {name}''' )
return camelcase_to_snakecase(__UpperCamelCase )
def __lowerCamelCase ( __UpperCamelCase , __UpperCamelCase ) -> Optional[Any]:
"""simple docstring"""
if os.path.basename(__UpperCamelCase ) != name:
raise ValueError(f'''Should be a dataset name, not a path: {name}''' )
if not re.match(_split_re , __UpperCamelCase ):
raise ValueError(f'''Split name should match \'{_split_re}\'\' but got \'{split}\'.''' )
return f'''{filename_prefix_for_name(__UpperCamelCase )}-{split}'''
def __lowerCamelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None ) -> Optional[Any]:
"""simple docstring"""
lowerCAmelCase_ : str = filename_prefix_for_split(__UpperCamelCase , __UpperCamelCase )
if filetype_suffix:
prefix += f'''.{filetype_suffix}'''
lowerCAmelCase_ : List[str] = os.path.join(__UpperCamelCase , __UpperCamelCase )
return f'''{filepath}*'''
def __lowerCamelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None , __UpperCamelCase=None ) -> Tuple:
"""simple docstring"""
lowerCAmelCase_ : int = filename_prefix_for_split(__UpperCamelCase , __UpperCamelCase )
lowerCAmelCase_ : List[Any] = os.path.join(__UpperCamelCase , __UpperCamelCase )
if shard_lengths:
lowerCAmelCase_ : List[Any] = len(__UpperCamelCase )
lowerCAmelCase_ : Any = [f'''{prefix}-{shard_id:05d}-of-{num_shards:05d}''' for shard_id in range(__UpperCamelCase )]
if filetype_suffix:
lowerCAmelCase_ : Dict = [filename + f'''.{filetype_suffix}''' for filename in filenames]
return filenames
else:
lowerCAmelCase_ : Any = prefix
if filetype_suffix:
filename += f'''.{filetype_suffix}'''
return [filename]
| 610 | 1 |
"""simple docstring"""
import json
import os
from typing import Optional, Tuple
import regex as re
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
lowerCAmelCase__ : Optional[Any] = logging.get_logger(__name__)
lowerCAmelCase__ : str = {
"""vocab_file""": """vocab.json""",
"""merges_file""": """merges.txt""",
}
lowerCAmelCase__ : Tuple = {
"""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"""},
}
lowerCAmelCase__ : Optional[int] = {
"""ctrl""": 256,
}
lowerCAmelCase__ : Any = {
"""Pregnancy""": 168_629,
"""Christianity""": 7_675,
"""Explain""": 106_423,
"""Fitness""": 63_440,
"""Saving""": 63_163,
"""Ask""": 27_171,
"""Ass""": 95_985,
"""Joke""": 163_509,
"""Questions""": 45_622,
"""Thoughts""": 49_605,
"""Retail""": 52_342,
"""Feminism""": 164_338,
"""Writing""": 11_992,
"""Atheism""": 192_263,
"""Netflix""": 48_616,
"""Computing""": 39_639,
"""Opinion""": 43_213,
"""Alone""": 44_967,
"""Funny""": 58_917,
"""Gaming""": 40_358,
"""Human""": 4_088,
"""India""": 1_331,
"""Joker""": 77_138,
"""Diet""": 36_206,
"""Legal""": 11_859,
"""Norman""": 4_939,
"""Tip""": 72_689,
"""Weight""": 52_343,
"""Movies""": 46_273,
"""Running""": 23_425,
"""Science""": 2_090,
"""Horror""": 37_793,
"""Confession""": 60_572,
"""Finance""": 12_250,
"""Politics""": 16_360,
"""Scary""": 191_985,
"""Support""": 12_654,
"""Technologies""": 32_516,
"""Teenage""": 66_160,
"""Event""": 32_769,
"""Learned""": 67_460,
"""Notion""": 182_770,
"""Wikipedia""": 37_583,
"""Books""": 6_665,
"""Extract""": 76_050,
"""Confessions""": 102_701,
"""Conspiracy""": 75_932,
"""Links""": 63_674,
"""Narcissus""": 150_425,
"""Relationship""": 54_766,
"""Relationships""": 134_796,
"""Reviews""": 41_671,
"""News""": 4_256,
"""Translation""": 26_820,
"""multilingual""": 128_406,
}
def a_ ( lowerCamelCase ):
UpperCAmelCase__ = set()
UpperCAmelCase__ = word[0]
for char in word[1:]:
pairs.add((prev_char, char) )
UpperCAmelCase__ = char
UpperCAmelCase__ = set(lowerCamelCase )
return pairs
class snake_case ( _snake_case ):
"""simple docstring"""
snake_case__ = VOCAB_FILES_NAMES
snake_case__ = PRETRAINED_VOCAB_FILES_MAP
snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
snake_case__ = CONTROL_CODES
def __init__( self : Optional[Any] ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : int ,lowerCamelCase__ : List[Any]="<unk>" ,**lowerCamelCase__ : int ):
super().__init__(unk_token=snake_case_ ,**snake_case_ )
with open(snake_case_ ,encoding='utf-8' ) as vocab_handle:
UpperCAmelCase__ = json.load(snake_case_ )
UpperCAmelCase__ = {v: k for k, v in self.encoder.items()}
with open(snake_case_ ,encoding='utf-8' ) as merges_handle:
UpperCAmelCase__ = merges_handle.read().split('\n' )[1:-1]
UpperCAmelCase__ = [tuple(merge.split() ) for merge in merges]
UpperCAmelCase__ = dict(zip(snake_case_ ,range(len(snake_case_ ) ) ) )
UpperCAmelCase__ = {}
@property
def __lowerCAmelCase ( self : Union[str, Any] ):
return len(self.encoder )
def __lowerCAmelCase ( self : str ):
return dict(self.encoder ,**self.added_tokens_encoder )
def __lowerCAmelCase ( self : str ,lowerCamelCase__ : Any ):
if token in self.cache:
return self.cache[token]
UpperCAmelCase__ = tuple(snake_case_ )
UpperCAmelCase__ = tuple(list(word[:-1] ) + [word[-1] + '</w>'] )
UpperCAmelCase__ = get_pairs(snake_case_ )
if not pairs:
return token
while True:
UpperCAmelCase__ = min(snake_case_ ,key=lambda lowerCamelCase__ : self.bpe_ranks.get(snake_case_ ,float('inf' ) ) )
if bigram not in self.bpe_ranks:
break
UpperCAmelCase__ = bigram
UpperCAmelCase__ = []
UpperCAmelCase__ = 0
while i < len(snake_case_ ):
try:
UpperCAmelCase__ = word.index(snake_case_ ,snake_case_ )
except ValueError:
new_word.extend(word[i:] )
break
else:
new_word.extend(word[i:j] )
UpperCAmelCase__ = j
if word[i] == first and i < len(snake_case_ ) - 1 and word[i + 1] == second:
new_word.append(first + second )
i += 2
else:
new_word.append(word[i] )
i += 1
UpperCAmelCase__ = tuple(snake_case_ )
UpperCAmelCase__ = new_word
if len(snake_case_ ) == 1:
break
else:
UpperCAmelCase__ = get_pairs(snake_case_ )
UpperCAmelCase__ = "@@ ".join(snake_case_ )
UpperCAmelCase__ = word[:-4]
UpperCAmelCase__ = word
return word
def __lowerCAmelCase ( self : List[str] ,lowerCamelCase__ : Optional[int] ):
UpperCAmelCase__ = []
UpperCAmelCase__ = re.findall(R'\S+\n?' ,snake_case_ )
for token in words:
split_tokens.extend(list(self.bpe(snake_case_ ).split(' ' ) ) )
return split_tokens
def __lowerCAmelCase ( self : int ,lowerCamelCase__ : int ):
return self.encoder.get(snake_case_ ,self.encoder.get(self.unk_token ) )
def __lowerCAmelCase ( self : int ,lowerCamelCase__ : int ):
return self.decoder.get(snake_case_ ,self.unk_token )
def __lowerCAmelCase ( self : Dict ,lowerCamelCase__ : Optional[int] ):
UpperCAmelCase__ = " ".join(snake_case_ ).replace('@@ ' ,'' ).strip()
return out_string
def __lowerCAmelCase ( self : Optional[int] ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : Optional[Any] = None ):
if not os.path.isdir(snake_case_ ):
logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' )
return
UpperCAmelCase__ = os.path.join(
snake_case_ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] )
UpperCAmelCase__ = os.path.join(
snake_case_ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] )
with open(snake_case_ ,'w' ,encoding='utf-8' ) as f:
f.write(json.dumps(self.encoder ,indent=2 ,sort_keys=snake_case_ ,ensure_ascii=snake_case_ ) + '\n' )
UpperCAmelCase__ = 0
with open(snake_case_ ,'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 lowerCamelCase__ : 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!' )
UpperCAmelCase__ = token_index
writer.write(' '.join(snake_case_ ) + '\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)
| 721 | """simple docstring"""
import os
import sys
from contextlib import contextmanager
# Windows only
if os.name == "nt":
import ctypes
import msvcrt # noqa
class snake_case ( ctypes.Structure ):
"""simple docstring"""
snake_case__ = [("size", ctypes.c_int), ("visible", ctypes.c_byte)]
def a_ ( ):
if os.name == "nt":
UpperCAmelCase__ = CursorInfo()
UpperCAmelCase__ = ctypes.windll.kernelaa.GetStdHandle(-1_1 )
ctypes.windll.kernelaa.GetConsoleCursorInfo(lowerCamelCase , ctypes.byref(lowerCamelCase ) )
UpperCAmelCase__ = False
ctypes.windll.kernelaa.SetConsoleCursorInfo(lowerCamelCase , ctypes.byref(lowerCamelCase ) )
elif os.name == "posix":
sys.stdout.write('\033[?25l' )
sys.stdout.flush()
def a_ ( ):
if os.name == "nt":
UpperCAmelCase__ = CursorInfo()
UpperCAmelCase__ = ctypes.windll.kernelaa.GetStdHandle(-1_1 )
ctypes.windll.kernelaa.GetConsoleCursorInfo(lowerCamelCase , ctypes.byref(lowerCamelCase ) )
UpperCAmelCase__ = True
ctypes.windll.kernelaa.SetConsoleCursorInfo(lowerCamelCase , ctypes.byref(lowerCamelCase ) )
elif os.name == "posix":
sys.stdout.write('\033[?25h' )
sys.stdout.flush()
@contextmanager
def a_ ( ):
try:
hide_cursor()
yield
finally:
show_cursor()
| 632 | 0 |
from numpy import exp, pi, sqrt
def A_ ( lowercase_ , lowercase_ = 0.0 , lowercase_ = 1.0 ) -> int:
return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 326 |
from unittest import TestCase
from datasets import Dataset
from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters
def A_ ( ) -> int:
_snake_case : Optional[int] = {
'''repo_name''': ['''test_repo1''', '''test_repo2''', '''test_repo3'''],
'''path''': ['''test_1.py''', '''test_2.py''', '''unit_test.py'''],
'''content''': ['''a ''' * 20, '''a ''' * 30, '''b ''' * 7],
}
_snake_case : Tuple = Dataset.from_dict(lowercase_ )
return dataset
class A (__UpperCAmelCase ):
def __a ( self ) -> Optional[Any]:
'''simple docstring'''
_snake_case : int = get_dataset()
_snake_case : Dict = make_duplicate_clusters(lowercase_ , 0.85 )
self.assertEqual(len(duplicate_clusters[0] ) , 2 )
def __a ( self ) -> Tuple:
'''simple docstring'''
_snake_case : Tuple = get_dataset()
_snake_case , _snake_case : Optional[int] = deduplicate_dataset(lowercase_ )
self.assertEqual(len(lowercase_ ) , 2 )
print(lowercase_ )
self.assertEqual(duplicate_clusters[0][0]['''copies'''] , 2 )
self.assertEqual(duplicate_clusters[0][0]['''is_extreme'''] , lowercase_ )
| 326 | 1 |
'''simple docstring'''
from dataclasses import dataclass, field
from typing import Tuple
from ..utils import cached_property, is_tf_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments
if is_tf_available():
import tensorflow as tf
lowercase_ : Union[str, Any] = logging.get_logger(__name__)
@dataclass
class __UpperCamelCase (_UpperCAmelCase ):
__A = [
'''no_inference''',
'''no_cuda''',
'''no_tpu''',
'''no_speed''',
'''no_memory''',
'''no_env_print''',
'''no_multi_process''',
]
def __init__( self , **_lowerCAmelCase ) -> Optional[int]:
'''simple docstring'''
for deprecated_arg in self.deprecated_args:
if deprecated_arg in kwargs:
lowercase = deprecated_arg[3:]
lowercase = not kwargs.pop(_lowerCAmelCase )
logger.warning(
F"""{deprecated_arg} is depreciated. Please use --no-{positive_arg} or"""
F""" {positive_arg}={kwargs[positive_arg]}""" )
lowercase = kwargs.pop("""tpu_name""" , self.tpu_name )
lowercase = kwargs.pop("""device_idx""" , self.device_idx )
lowercase = kwargs.pop("""eager_mode""" , self.eager_mode )
lowercase = kwargs.pop("""use_xla""" , self.use_xla )
super().__init__(**_lowerCAmelCase )
__A = field(
default=_UpperCAmelCase , metadata={'''help''': '''Name of TPU'''} , )
__A = field(
default=0 , metadata={'''help''': '''CPU / GPU device index. Defaults to 0.'''} , )
__A = field(default=_UpperCAmelCase , metadata={'''help''': '''Benchmark models in eager model.'''} )
__A = field(
default=_UpperCAmelCase , metadata={
'''help''': '''Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.'''
} , )
@cached_property
def _a ( self ) -> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]:
'''simple docstring'''
requires_backends(self , ["""tf"""] )
lowercase = None
if self.tpu:
try:
if self.tpu_name:
lowercase = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name )
else:
lowercase = tf.distribute.cluster_resolver.TPUClusterResolver()
except ValueError:
lowercase = None
return tpu
@cached_property
def _a ( self ) -> Tuple["tf.distribute.Strategy", "tf.distribute.cluster_resolver.TPUClusterResolver"]:
'''simple docstring'''
requires_backends(self , ["""tf"""] )
if self.is_tpu:
tf.config.experimental_connect_to_cluster(self._setup_tpu )
tf.tpu.experimental.initialize_tpu_system(self._setup_tpu )
lowercase = tf.distribute.TPUStrategy(self._setup_tpu )
else:
# currently no multi gpu is allowed
if self.is_gpu:
# TODO: Currently only single GPU is supported
tf.config.set_visible_devices(self.gpu_list[self.device_idx] , """GPU""" )
lowercase = tf.distribute.OneDeviceStrategy(device=F"""/gpu:{self.device_idx}""" )
else:
tf.config.set_visible_devices([] , """GPU""" ) # disable GPU
lowercase = tf.distribute.OneDeviceStrategy(device=F"""/cpu:{self.device_idx}""" )
return strategy
@property
def _a ( self ) -> bool:
'''simple docstring'''
requires_backends(self , ["""tf"""] )
return self._setup_tpu is not None
@property
def _a ( self ) -> "tf.distribute.Strategy":
'''simple docstring'''
requires_backends(self , ["""tf"""] )
return self._setup_strategy
@property
def _a ( self ) -> Tuple:
'''simple docstring'''
requires_backends(self , ["""tf"""] )
return tf.config.list_physical_devices("""GPU""" )
@property
def _a ( self ) -> int:
'''simple docstring'''
requires_backends(self , ["""tf"""] )
if self.cuda:
return len(self.gpu_list )
return 0
@property
def _a ( self ) -> bool:
'''simple docstring'''
return self.n_gpu > 0
| 653 |
'''simple docstring'''
from ... import PretrainedConfig
lowercase_ : int = {
'''sijunhe/nezha-cn-base''': '''https://huggingface.co/sijunhe/nezha-cn-base/resolve/main/config.json''',
}
class __UpperCamelCase (_UpperCAmelCase ):
__A = NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP
__A = '''nezha'''
def __init__( self , _lowerCAmelCase=2_1128 , _lowerCAmelCase=768 , _lowerCAmelCase=12 , _lowerCAmelCase=12 , _lowerCAmelCase=3072 , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.1 , _lowerCAmelCase=512 , _lowerCAmelCase=64 , _lowerCAmelCase=2 , _lowerCAmelCase=0.02 , _lowerCAmelCase=1E-12 , _lowerCAmelCase=0.1 , _lowerCAmelCase=0 , _lowerCAmelCase=2 , _lowerCAmelCase=3 , _lowerCAmelCase=True , **_lowerCAmelCase , ) -> int:
'''simple docstring'''
super().__init__(pad_token_id=_lowerCAmelCase , bos_token_id=_lowerCAmelCase , eos_token_id=_lowerCAmelCase , **_lowerCAmelCase )
lowercase = vocab_size
lowercase = hidden_size
lowercase = num_hidden_layers
lowercase = num_attention_heads
lowercase = hidden_act
lowercase = intermediate_size
lowercase = hidden_dropout_prob
lowercase = attention_probs_dropout_prob
lowercase = max_position_embeddings
lowercase = max_relative_position
lowercase = type_vocab_size
lowercase = initializer_range
lowercase = layer_norm_eps
lowercase = classifier_dropout
lowercase = use_cache
| 653 | 1 |
'''simple docstring'''
import unittest
from transformers import AutoConfig, AutoTokenizer, BertConfig, TensorType, is_flax_available
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, slow
if is_flax_available():
import jax
from transformers.models.auto.modeling_flax_auto import FlaxAutoModel
from transformers.models.bert.modeling_flax_bert import FlaxBertModel
from transformers.models.roberta.modeling_flax_roberta import FlaxRobertaModel
@require_flax
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
@slow
def __UpperCAmelCase ( self : Union[str, Any] ):
"""simple docstring"""
for model_name in ["bert-base-cased", "bert-large-uncased"]:
with self.subTest(SCREAMING_SNAKE_CASE__ ):
_snake_case : Optional[int] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE__ )
self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
_snake_case : Optional[Any] = FlaxAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE__ )
self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
@slow
def __UpperCAmelCase ( self : Dict ):
"""simple docstring"""
for model_name in ["roberta-base", "roberta-large"]:
with self.subTest(SCREAMING_SNAKE_CASE__ ):
_snake_case : Any = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE__ )
self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
_snake_case : str = FlaxAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE__ )
self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
@slow
def __UpperCAmelCase ( self : int ):
"""simple docstring"""
for model_name in ["bert-base-cased", "bert-large-uncased"]:
_snake_case : Dict = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ )
_snake_case : Any = FlaxBertModel.from_pretrained(SCREAMING_SNAKE_CASE__ )
_snake_case : List[Any] = tokenizer('Do you support jax jitted function?' , return_tensors=TensorType.JAX )
@jax.jit
def eval(**snake_case : Any ):
return model(**SCREAMING_SNAKE_CASE__ )
eval(**SCREAMING_SNAKE_CASE__ ).block_until_ready()
@slow
def __UpperCAmelCase ( self : Union[str, Any] ):
"""simple docstring"""
for model_name in ["roberta-base", "roberta-large"]:
_snake_case : Union[str, Any] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ )
_snake_case : Optional[int] = FlaxRobertaModel.from_pretrained(SCREAMING_SNAKE_CASE__ )
_snake_case : Dict = tokenizer('Do you support jax jitted function?' , return_tensors=TensorType.JAX )
@jax.jit
def eval(**snake_case : int ):
return model(**SCREAMING_SNAKE_CASE__ )
eval(**SCREAMING_SNAKE_CASE__ ).block_until_ready()
def __UpperCAmelCase ( self : Optional[Any] ):
"""simple docstring"""
with self.assertRaisesRegex(
SCREAMING_SNAKE_CASE__ , 'bert-base is not a local folder and is not a valid model identifier' ):
_snake_case : Optional[Any] = FlaxAutoModel.from_pretrained('bert-base' )
def __UpperCAmelCase ( self : Optional[int] ):
"""simple docstring"""
with self.assertRaisesRegex(
SCREAMING_SNAKE_CASE__ , r'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)' ):
_snake_case : Dict = FlaxAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__ , revision='aaaaaa' )
def __UpperCAmelCase ( self : Optional[int] ):
"""simple docstring"""
with self.assertRaisesRegex(
SCREAMING_SNAKE_CASE__ , 'hf-internal-testing/config-no-model does not appear to have a file named flax_model.msgpack' , ):
_snake_case : int = FlaxAutoModel.from_pretrained('hf-internal-testing/config-no-model' )
def __UpperCAmelCase ( self : Tuple ):
"""simple docstring"""
with self.assertRaisesRegex(SCREAMING_SNAKE_CASE__ , 'Use `from_pt=True` to load this model' ):
_snake_case : Tuple = FlaxAutoModel.from_pretrained('hf-internal-testing/tiny-bert-pt-only' )
| 517 | from collections import Counter
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
_lowercase : Union[str, Any] =datasets.load_iris()
_lowercase : Dict =np.array(data['''data'''])
_lowercase : List[str] =np.array(data['''target'''])
_lowercase : int =data['''target_names''']
_lowercase , _lowercase , _lowercase , _lowercase : List[str] =train_test_split(X, y)
def A__ ( lowercase: Dict, lowercase: Union[str, Any] ) -> Optional[Any]:
return np.linalg.norm(np.array(lowercase ) - np.array(lowercase ) )
def A__ ( lowercase: Any, lowercase: int, lowercase: Tuple, lowercase: str, lowercase: Dict=5 ) -> int:
A : str =zip(lowercase, lowercase )
# List of distances of all points from the point to be classified
A : Any =[]
for data_point in data:
A : Optional[int] =euclidean_distance(data_point[0], lowercase )
distances.append((distance, data_point[1]) )
# Choosing 'k' points with the least distances.
A : int =[i[1] for i in sorted(lowercase )[:k]]
# Most commonly occurring class among them
# is the class into which the point is classified
A : str =Counter(lowercase ).most_common(1 )[0][0]
return classes[result]
if __name__ == "__main__":
print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
| 305 | 0 |
def UpperCamelCase__( UpperCamelCase__ : str , UpperCamelCase__ : str )->str:
A__ = len(UpperCamelCase__ )
A__ = len(UpperCamelCase__ )
A__ = (
first_str_length if first_str_length > second_str_length else second_str_length
)
A__ = []
for char_count in range(UpperCamelCase__ ):
if char_count < first_str_length:
output_list.append(first_str[char_count] )
if char_count < second_str_length:
output_list.append(second_str[char_count] )
return "".join(UpperCamelCase__ )
if __name__ == "__main__":
print(alternative_string_arrange('AB', 'XYZ'), end=' ')
| 212 |
import argparse
import logging
import pickle
import random
import time
import numpy as np
from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO
)
a__: Union[str, Any] = logging.getLogger(__name__)
def UpperCamelCase__( )->List[Any]:
A__ = argparse.ArgumentParser(
description='''Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).''' )
parser.add_argument('''--file_path''' , type=UpperCamelCase__ , default='''data/dump.txt''' , help='''The path to the data.''' )
parser.add_argument('''--tokenizer_type''' , type=UpperCamelCase__ , default='''bert''' , choices=['''bert''', '''roberta''', '''gpt2'''] )
parser.add_argument('''--tokenizer_name''' , type=UpperCamelCase__ , default='''bert-base-uncased''' , help='''The tokenizer to use.''' )
parser.add_argument('''--dump_file''' , type=UpperCamelCase__ , default='''data/dump''' , help='''The dump file prefix.''' )
A__ = parser.parse_args()
logger.info(f"Loading Tokenizer ({args.tokenizer_name})" )
if args.tokenizer_type == "bert":
A__ = BertTokenizer.from_pretrained(args.tokenizer_name )
A__ = tokenizer.special_tokens_map['''cls_token'''] # `[CLS]`
A__ = tokenizer.special_tokens_map['''sep_token'''] # `[SEP]`
elif args.tokenizer_type == "roberta":
A__ = RobertaTokenizer.from_pretrained(args.tokenizer_name )
A__ = tokenizer.special_tokens_map['''cls_token'''] # `<s>`
A__ = tokenizer.special_tokens_map['''sep_token'''] # `</s>`
elif args.tokenizer_type == "gpt2":
A__ = GPTaTokenizer.from_pretrained(args.tokenizer_name )
A__ = tokenizer.special_tokens_map['''bos_token'''] # `<|endoftext|>`
A__ = tokenizer.special_tokens_map['''eos_token'''] # `<|endoftext|>`
logger.info(f"Loading text from {args.file_path}" )
with open(args.file_path , '''r''' , encoding='''utf8''' ) as fp:
A__ = fp.readlines()
logger.info('''Start encoding''' )
logger.info(f"{len(UpperCamelCase__ )} examples to process." )
A__ = []
A__ = 0
A__ = 1_00_00
A__ = time.time()
for text in data:
A__ = f"{bos} {text.strip()} {sep}"
A__ = tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ )
rslt.append(UpperCamelCase__ )
iter += 1
if iter % interval == 0:
A__ = time.time()
logger.info(f"{iter} examples processed. - {(end-start):.2f}s/{interval}expl" )
A__ = time.time()
logger.info('''Finished binarization''' )
logger.info(f"{len(UpperCamelCase__ )} examples processed." )
A__ = f"{args.dump_file}.{args.tokenizer_name}.pickle"
A__ = tokenizer.vocab_size
if vocab_size < (1 << 16):
A__ = [np.uintaa(UpperCamelCase__ ) for d in rslt]
else:
A__ = [np.intaa(UpperCamelCase__ ) for d in rslt]
random.shuffle(rslt_ )
logger.info(f"Dump to {dp_file}" )
with open(UpperCamelCase__ , '''wb''' ) as handle:
pickle.dump(rslt_ , UpperCamelCase__ , protocol=pickle.HIGHEST_PROTOCOL )
if __name__ == "__main__":
main()
| 212 | 1 |
import unittest
import numpy as np
def UpperCamelCase ( lowercase_ , lowercase_ , lowercase_ , lowercase_ = None , ) -> np.ndarray:
'''simple docstring'''
lowercase__ : Tuple = np.shape(lowercase_ )
lowercase__ : Tuple = np.shape(lowercase_ )
lowercase__ : Optional[int] = np.shape(lowercase_ )
if shape_a[0] != shape_b[0]:
lowercase__ : List[Any] = (
"""Expected the same number of rows for A and B. """
F'Instead found A of size {shape_a} and B of size {shape_b}'
)
raise ValueError(lowercase_ )
if shape_b[1] != shape_c[1]:
lowercase__ : Any = (
"""Expected the same number of columns for B and C. """
F'Instead found B of size {shape_b} and C of size {shape_c}'
)
raise ValueError(lowercase_ )
lowercase__ : List[str] = pseudo_inv
if a_inv is None:
try:
lowercase__ : List[str] = np.linalg.inv(lowercase_ )
except np.linalg.LinAlgError:
raise ValueError(
"""Input matrix A is not invertible. Cannot compute Schur complement.""" )
return mat_c - mat_b.T @ a_inv @ mat_b
class _snake_case ( unittest.TestCase ):
def lowercase__ ( self):
'''simple docstring'''
lowercase__ : List[str] = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]])
lowercase__ : List[str] = np.array([[0, 3], [3, 0], [2, 3]])
lowercase__ : Tuple = np.array([[2, 1], [6, 3]])
lowercase__ : List[Any] = schur_complement(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_)
lowercase__ : Any = np.block([[a, b], [b.T, c]])
lowercase__ : List[Any] = np.linalg.det(SCREAMING_SNAKE_CASE_)
lowercase__ : List[Any] = np.linalg.det(SCREAMING_SNAKE_CASE_)
lowercase__ : int = np.linalg.det(SCREAMING_SNAKE_CASE_)
self.assertAlmostEqual(SCREAMING_SNAKE_CASE_ , det_a * det_s)
def lowercase__ ( self):
'''simple docstring'''
lowercase__ : Optional[Any] = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]])
lowercase__ : Dict = np.array([[0, 3], [3, 0], [2, 3]])
lowercase__ : int = np.array([[2, 1], [6, 3]])
with self.assertRaises(SCREAMING_SNAKE_CASE_):
schur_complement(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_)
def lowercase__ ( self):
'''simple docstring'''
lowercase__ : Tuple = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]])
lowercase__ : Union[str, Any] = np.array([[0, 3], [3, 0], [2, 3]])
lowercase__ : str = np.array([[2, 1, 3], [6, 3, 5]])
with self.assertRaises(SCREAMING_SNAKE_CASE_):
schur_complement(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_)
if __name__ == "__main__":
import doctest
doctest.testmod()
unittest.main()
| 12 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
A : Union[str, Any] = {
"configuration_timesformer": ["TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TimesformerConfig"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A : Optional[int] = [
"TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
"TimesformerModel",
"TimesformerForVideoClassification",
"TimesformerPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_timesformer import (
TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TimesformerForVideoClassification,
TimesformerModel,
TimesformerPreTrainedModel,
)
else:
import sys
A : List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 636 | 0 |
'''simple docstring'''
def __A ( _SCREAMING_SNAKE_CASE : int = 3 , _SCREAMING_SNAKE_CASE : int = 7 , _SCREAMING_SNAKE_CASE : int = 1_0_0_0_0_0_0 ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Optional[Any] = 0
__SCREAMING_SNAKE_CASE : Tuple = 1
for current_denominator in range(1 , limit + 1 ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = current_denominator * numerator // denominator
if current_denominator % denominator == 0:
current_numerator -= 1
if current_numerator * max_denominator > current_denominator * max_numerator:
__SCREAMING_SNAKE_CASE : int = current_numerator
__SCREAMING_SNAKE_CASE : Tuple = current_denominator
return max_numerator
if __name__ == "__main__":
print(solution(numerator=3, denominator=7, limit=100_0000))
| 564 |
'''simple docstring'''
import os
from datetime import datetime as dt
from github import Github
lowercase = [
'''good first issue''',
'''feature request''',
'''wip''',
]
def __A ( ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Union[str, Any] = Github(os.environ["GITHUB_TOKEN"] )
__SCREAMING_SNAKE_CASE : Tuple = g.get_repo("huggingface/accelerate" )
__SCREAMING_SNAKE_CASE : str = repo.get_issues(state="open" )
for issue in open_issues:
__SCREAMING_SNAKE_CASE : List[str] = sorted([comment for comment in issue.get_comments()] , key=lambda _SCREAMING_SNAKE_CASE : i.created_at , reverse=_SCREAMING_SNAKE_CASE )
__SCREAMING_SNAKE_CASE : Any = comments[0] if len(_SCREAMING_SNAKE_CASE ) > 0 else None
__SCREAMING_SNAKE_CASE : int = dt.utcnow()
__SCREAMING_SNAKE_CASE : Tuple = (current_time - issue.updated_at).days
__SCREAMING_SNAKE_CASE : Optional[Any] = (current_time - issue.created_at).days
if (
last_comment is not None
and last_comment.user.login == "github-actions[bot]"
and days_since_updated > 7
and days_since_creation >= 3_0
and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
):
# Close issue since it has been 7 days of inactivity since bot mention.
issue.edit(state="closed" )
elif (
days_since_updated > 2_3
and days_since_creation >= 3_0
and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
):
# Add stale comment
issue.create_comment(
"This issue has been automatically marked as stale because it has not had "
"recent activity. If you think this still needs to be addressed "
"please comment on this thread.\n\nPlease note that issues that do not follow the "
"[contributing guidelines](https://github.com/huggingface/accelerate/blob/main/CONTRIBUTING.md) "
"are likely to be ignored." )
if __name__ == "__main__":
main()
| 564 | 1 |
'''simple docstring'''
from __future__ import annotations
def a_ ( __UpperCAmelCase ) -> str:
"""simple docstring"""
snake_case: Dict =len(__UpperCAmelCase )
# We need to create solution object to save path.
snake_case: Tuple =[[0 for _ in range(__UpperCAmelCase )] for _ in range(__UpperCAmelCase )]
snake_case: int =run_maze(__UpperCAmelCase , 0 , 0 , __UpperCAmelCase )
if solved:
print('\n'.join(str(__UpperCAmelCase ) for row in solutions ) )
else:
print('No solution exists!' )
return solved
def a_ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Optional[int]:
"""simple docstring"""
snake_case: Any =len(__UpperCAmelCase )
# Final check point.
if i == j == (size - 1):
snake_case: Union[str, Any] =1
return True
snake_case: int =(not i < 0) and (not j < 0) # Check lower bounds
snake_case: int =(i < size) and (j < size) # Check upper bounds
if lower_flag and upper_flag:
# check for already visited and block points.
snake_case: Any =(not solutions[i][j]) and (not maze[i][j])
if block_flag:
# check visited
snake_case: Tuple =1
# check for directions
if (
run_maze(__UpperCAmelCase , i + 1 , __UpperCAmelCase , __UpperCAmelCase )
or run_maze(__UpperCAmelCase , __UpperCAmelCase , j + 1 , __UpperCAmelCase )
or run_maze(__UpperCAmelCase , i - 1 , __UpperCAmelCase , __UpperCAmelCase )
or run_maze(__UpperCAmelCase , __UpperCAmelCase , j - 1 , __UpperCAmelCase )
):
return True
snake_case: Tuple =0
return False
return False
if __name__ == "__main__":
import doctest
doctest.testmod()
| 350 |
'''simple docstring'''
from __future__ import annotations
import numpy as np
def UpperCamelCase__ ( lowerCAmelCase ):
"""simple docstring"""
_lowerCAmelCase , _lowerCAmelCase = np.shape(lowerCAmelCase )
if rows != columns:
_lowerCAmelCase = (
"""'table' has to be of square shaped array but got a """
f"{rows}x{columns} array:\n{table}"
)
raise ValueError(lowerCAmelCase )
_lowerCAmelCase = np.zeros((rows, columns) )
_lowerCAmelCase = np.zeros((rows, columns) )
for i in range(lowerCAmelCase ):
for j in range(lowerCAmelCase ):
_lowerCAmelCase = sum(lower[i][k] * upper[k][j] for k in range(lowerCAmelCase ) )
if upper[j][j] == 0:
raise ArithmeticError("""No LU decomposition exists""" )
_lowerCAmelCase = (table[i][j] - total) / upper[j][j]
_lowerCAmelCase = 1
for j in range(lowerCAmelCase , lowerCAmelCase ):
_lowerCAmelCase = sum(lower[i][k] * upper[k][j] for k in range(lowerCAmelCase ) )
_lowerCAmelCase = table[i][j] - total
return lower, upper
if __name__ == "__main__":
import doctest
doctest.testmod()
| 207 | 0 |
from __future__ import annotations
class lowerCamelCase__ :
def __init__( self : List[Any] , __a : int ):
'''simple docstring'''
lowerCamelCase__: List[str] = order
# a_{0} ... a_{k}
lowerCamelCase__: Optional[Any] = [1.0] + [0.0] * order
# b_{0} ... b_{k}
lowerCamelCase__: List[str] = [1.0] + [0.0] * order
# x[n-1] ... x[n-k]
lowerCamelCase__: int = [0.0] * self.order
# y[n-1] ... y[n-k]
lowerCamelCase__: Optional[Any] = [0.0] * self.order
def lowerCamelCase_ ( self : Union[str, Any] , __a : list[float] , __a : list[float] ):
'''simple docstring'''
if len(__a ) < self.order:
lowerCamelCase__: List[str] = [1.0, *a_coeffs]
if len(__a ) != self.order + 1:
lowerCamelCase__: Dict = (
f"""Expected a_coeffs to have {self.order + 1} elements """
f"""for {self.order}-order filter, got {len(__a )}"""
)
raise ValueError(__a )
if len(__a ) != self.order + 1:
lowerCamelCase__: str = (
f"""Expected b_coeffs to have {self.order + 1} elements """
f"""for {self.order}-order filter, got {len(__a )}"""
)
raise ValueError(__a )
lowerCamelCase__: Tuple = a_coeffs
lowerCamelCase__: int = b_coeffs
def lowerCamelCase_ ( self : int , __a : float ):
'''simple docstring'''
lowerCamelCase__: Union[str, Any] = 0.0
# Start at index 1 and do index 0 at the end.
for i in range(1 , self.order + 1 ):
result += (
self.b_coeffs[i] * self.input_history[i - 1]
- self.a_coeffs[i] * self.output_history[i - 1]
)
lowerCamelCase__: Union[str, Any] = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0]
lowerCamelCase__: str = self.input_history[:-1]
lowerCamelCase__: Optional[int] = self.output_history[:-1]
lowerCamelCase__: Union[str, Any] = sample
lowerCamelCase__: str = result
return result
| 242 |
import json
import os
import shutil
import tempfile
import unittest
import numpy as np
import pytest
from transformers import BertTokenizer, BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available
if is_vision_available():
from PIL import Image
from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor
@require_vision
class lowerCamelCase__ ( unittest.TestCase ):
def lowerCamelCase_ ( self : Union[str, Any] ):
'''simple docstring'''
lowerCamelCase__: int = tempfile.mkdtemp()
lowerCamelCase__: Tuple = [
"""[UNK]""",
"""[CLS]""",
"""[SEP]""",
"""[PAD]""",
"""[MASK]""",
"""的""",
"""价""",
"""格""",
"""是""",
"""15""",
"""便""",
"""alex""",
"""##andra""",
""",""",
"""。""",
"""-""",
"""t""",
"""shirt""",
]
lowerCamelCase__: Optional[int] = 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] ) )
lowerCamelCase__: Optional[int] = {
"""do_resize""": True,
"""size""": {"""height""": 224, """width""": 224},
"""do_center_crop""": True,
"""crop_size""": {"""height""": 18, """width""": 18},
"""do_normalize""": True,
"""image_mean""": [0.48_145_466, 0.4_578_275, 0.40_821_073],
"""image_std""": [0.26_862_954, 0.26_130_258, 0.27_577_711],
"""do_convert_rgb""": True,
}
lowerCamelCase__: List[str] = os.path.join(self.tmpdirname , __a )
with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp:
json.dump(__a , __a )
def lowerCamelCase_ ( self : List[Any] , **__a : List[str] ):
'''simple docstring'''
return BertTokenizer.from_pretrained(self.tmpdirname , **__a )
def lowerCamelCase_ ( self : int , **__a : str ):
'''simple docstring'''
return BertTokenizerFast.from_pretrained(self.tmpdirname , **__a )
def lowerCamelCase_ ( self : str , **__a : Tuple ):
'''simple docstring'''
return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **__a )
def lowerCamelCase_ ( self : Dict ):
'''simple docstring'''
shutil.rmtree(self.tmpdirname )
def lowerCamelCase_ ( self : Any ):
'''simple docstring'''
lowerCamelCase__: Dict = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )]
lowerCamelCase__: Dict = [Image.fromarray(np.moveaxis(__a , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def lowerCamelCase_ ( self : int ):
'''simple docstring'''
lowerCamelCase__: Optional[int] = self.get_tokenizer()
lowerCamelCase__: List[Any] = self.get_rust_tokenizer()
lowerCamelCase__: Dict = self.get_image_processor()
lowerCamelCase__: int = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a )
processor_slow.save_pretrained(self.tmpdirname )
lowerCamelCase__: Any = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__a )
lowerCamelCase__: str = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a )
processor_fast.save_pretrained(self.tmpdirname )
lowerCamelCase__: Tuple = ChineseCLIPProcessor.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 , __a )
self.assertIsInstance(processor_fast.tokenizer , __a )
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 , __a )
self.assertIsInstance(processor_fast.image_processor , __a )
def lowerCamelCase_ ( self : Dict ):
'''simple docstring'''
lowerCamelCase__: str = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
lowerCamelCase__: List[str] = self.get_tokenizer(cls_token="""(CLS)""" , sep_token="""(SEP)""" )
lowerCamelCase__: str = self.get_image_processor(do_normalize=__a )
lowerCamelCase__: List[Any] = ChineseCLIPProcessor.from_pretrained(
self.tmpdirname , cls_token="""(CLS)""" , sep_token="""(SEP)""" , do_normalize=__a )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer , __a )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , __a )
def lowerCamelCase_ ( self : int ):
'''simple docstring'''
lowerCamelCase__: str = self.get_image_processor()
lowerCamelCase__: Union[str, Any] = self.get_tokenizer()
lowerCamelCase__: List[str] = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a )
lowerCamelCase__: int = self.prepare_image_inputs()
lowerCamelCase__: List[str] = image_processor(__a , return_tensors="""np""" )
lowerCamelCase__: Optional[Any] = processor(images=__a , return_tensors="""np""" )
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 )
def lowerCamelCase_ ( self : Union[str, Any] ):
'''simple docstring'''
lowerCamelCase__: Tuple = self.get_image_processor()
lowerCamelCase__: Dict = self.get_tokenizer()
lowerCamelCase__: Optional[int] = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a )
lowerCamelCase__: List[str] = """Alexandra,T-shirt的价格是15便士。"""
lowerCamelCase__: Optional[Any] = processor(text=__a )
lowerCamelCase__: Tuple = tokenizer(__a )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def lowerCamelCase_ ( self : Dict ):
'''simple docstring'''
lowerCamelCase__: int = self.get_image_processor()
lowerCamelCase__: Any = self.get_tokenizer()
lowerCamelCase__: Tuple = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a )
lowerCamelCase__: Dict = """Alexandra,T-shirt的价格是15便士。"""
lowerCamelCase__: int = self.prepare_image_inputs()
lowerCamelCase__: Union[str, Any] = processor(text=__a , images=__a )
self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """token_type_ids""", """attention_mask""", """pixel_values"""] )
# test if it raises when no input is passed
with pytest.raises(__a ):
processor()
def lowerCamelCase_ ( self : Dict ):
'''simple docstring'''
lowerCamelCase__: Optional[Any] = self.get_image_processor()
lowerCamelCase__: List[Any] = self.get_tokenizer()
lowerCamelCase__: Optional[int] = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a )
lowerCamelCase__: Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
lowerCamelCase__: Union[str, Any] = processor.batch_decode(__a )
lowerCamelCase__: Union[str, Any] = tokenizer.batch_decode(__a )
self.assertListEqual(__a , __a )
def lowerCamelCase_ ( self : Optional[Any] ):
'''simple docstring'''
lowerCamelCase__: str = self.get_image_processor()
lowerCamelCase__: Tuple = self.get_tokenizer()
lowerCamelCase__: Union[str, Any] = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a )
lowerCamelCase__: Optional[int] = """Alexandra,T-shirt的价格是15便士。"""
lowerCamelCase__: Tuple = self.prepare_image_inputs()
lowerCamelCase__: Optional[int] = processor(text=__a , images=__a )
self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
| 242 | 1 |
"""simple docstring"""
from dataclasses import dataclass
from typing import Dict, Optional, Union
import torch
import torch.nn.functional as F
from torch import nn
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .attention import BasicTransformerBlock
from .attention_processor import AttentionProcessor, AttnProcessor
from .embeddings import TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
@dataclass
class lowerCamelCase__ ( A ):
"""simple docstring"""
__a = 42
class lowerCamelCase__ ( A , A ):
"""simple docstring"""
@register_to_config
def __init__( self : str , UpperCamelCase : int = 32 , UpperCamelCase : int = 64 , UpperCamelCase : int = 20 , UpperCamelCase : int = 768 , UpperCamelCase : Any=77 , UpperCamelCase : Optional[Any]=4 , UpperCamelCase : float = 0.0 , UpperCamelCase : str = "silu" , UpperCamelCase : Optional[str] = None , UpperCamelCase : Optional[str] = None , UpperCamelCase : Optional[str] = "linear" , UpperCamelCase : Optional[str] = "prd" , UpperCamelCase : Optional[int] = None , UpperCamelCase : Optional[int] = None , UpperCamelCase : Optional[int] = None , ):
'''simple docstring'''
super().__init__()
__UpperCAmelCase : Tuple = num_attention_heads
__UpperCAmelCase : Dict = attention_head_dim
__UpperCAmelCase : Tuple = num_attention_heads * attention_head_dim
__UpperCAmelCase : Dict = additional_embeddings
__UpperCAmelCase : int = time_embed_dim or inner_dim
__UpperCAmelCase : List[Any] = embedding_proj_dim or embedding_dim
__UpperCAmelCase : List[str] = clip_embed_dim or embedding_dim
__UpperCAmelCase : Union[str, Any] = Timesteps(UpperCamelCase , UpperCamelCase , 0 )
__UpperCAmelCase : Any = TimestepEmbedding(UpperCamelCase , UpperCamelCase , out_dim=UpperCamelCase , act_fn=UpperCamelCase )
__UpperCAmelCase : Any = nn.Linear(UpperCamelCase , UpperCamelCase )
if embedding_proj_norm_type is None:
__UpperCAmelCase : List[str] = None
elif embedding_proj_norm_type == "layer":
__UpperCAmelCase : int = nn.LayerNorm(UpperCamelCase )
else:
raise ValueError(f'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}''' )
__UpperCAmelCase : List[Any] = nn.Linear(UpperCamelCase , UpperCamelCase )
if encoder_hid_proj_type is None:
__UpperCAmelCase : List[Any] = None
elif encoder_hid_proj_type == "linear":
__UpperCAmelCase : List[Any] = nn.Linear(UpperCamelCase , UpperCamelCase )
else:
raise ValueError(f'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}''' )
__UpperCAmelCase : Union[str, Any] = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , UpperCamelCase ) )
if added_emb_type == "prd":
__UpperCAmelCase : Dict = nn.Parameter(torch.zeros(1 , 1 , UpperCamelCase ) )
elif added_emb_type is None:
__UpperCAmelCase : Dict = None
else:
raise ValueError(
f'''`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.''' )
__UpperCAmelCase : List[str] = nn.ModuleList(
[
BasicTransformerBlock(
UpperCamelCase , UpperCamelCase , UpperCamelCase , dropout=UpperCamelCase , activation_fn="""gelu""" , attention_bias=UpperCamelCase , )
for d in range(UpperCamelCase )
] )
if norm_in_type == "layer":
__UpperCAmelCase : int = nn.LayerNorm(UpperCamelCase )
elif norm_in_type is None:
__UpperCAmelCase : Dict = None
else:
raise ValueError(f'''Unsupported norm_in_type: {norm_in_type}.''' )
__UpperCAmelCase : List[str] = nn.LayerNorm(UpperCamelCase )
__UpperCAmelCase : Any = nn.Linear(UpperCamelCase , UpperCamelCase )
__UpperCAmelCase : int = torch.full(
[num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -10000.0 )
causal_attention_mask.triu_(1 )
__UpperCAmelCase : Optional[int] = causal_attention_mask[None, ...]
self.register_buffer("""causal_attention_mask""" , UpperCamelCase , persistent=UpperCamelCase )
__UpperCAmelCase : Union[str, Any] = nn.Parameter(torch.zeros(1 , UpperCamelCase ) )
__UpperCAmelCase : List[Any] = nn.Parameter(torch.zeros(1 , UpperCamelCase ) )
@property
# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
def lowerCamelCase__ ( self : Dict ):
'''simple docstring'''
__UpperCAmelCase : str = {}
def fn_recursive_add_processors(UpperCamelCase : str , UpperCamelCase : torch.nn.Module , UpperCamelCase : Dict[str, AttentionProcessor] ):
if hasattr(UpperCamelCase , """set_processor""" ):
__UpperCAmelCase : Union[str, Any] = module.processor
for sub_name, child in module.named_children():
fn_recursive_add_processors(f'''{name}.{sub_name}''' , UpperCamelCase , UpperCamelCase )
return processors
for name, module in self.named_children():
fn_recursive_add_processors(UpperCamelCase , UpperCamelCase , UpperCamelCase )
return processors
def lowerCamelCase__ ( self : Any , UpperCamelCase : Union[AttentionProcessor, Dict[str, AttentionProcessor]] ):
'''simple docstring'''
__UpperCAmelCase : str = len(self.attn_processors.keys() )
if isinstance(UpperCamelCase , UpperCamelCase ) and len(UpperCamelCase ) != count:
raise ValueError(
f'''A dict of processors was passed, but the number of processors {len(UpperCamelCase )} does not match the'''
f''' number of attention layers: {count}. Please make sure to pass {count} processor classes.''' )
def fn_recursive_attn_processor(UpperCamelCase : str , UpperCamelCase : torch.nn.Module , UpperCamelCase : Tuple ):
if hasattr(UpperCamelCase , """set_processor""" ):
if not isinstance(UpperCamelCase , UpperCamelCase ):
module.set_processor(UpperCamelCase )
else:
module.set_processor(processor.pop(f'''{name}.processor''' ) )
for sub_name, child in module.named_children():
fn_recursive_attn_processor(f'''{name}.{sub_name}''' , UpperCamelCase , UpperCamelCase )
for name, module in self.named_children():
fn_recursive_attn_processor(UpperCamelCase , UpperCamelCase , UpperCamelCase )
def lowerCamelCase__ ( self : Optional[int] ):
'''simple docstring'''
self.set_attn_processor(AttnProcessor() )
def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase : Dict , UpperCamelCase : Union[torch.Tensor, float, int] , UpperCamelCase : torch.FloatTensor , UpperCamelCase : Optional[torch.FloatTensor] = None , UpperCamelCase : Optional[torch.BoolTensor] = None , UpperCamelCase : bool = True , ):
'''simple docstring'''
__UpperCAmelCase : List[str] = hidden_states.shape[0]
__UpperCAmelCase : List[Any] = timestep
if not torch.is_tensor(UpperCamelCase ):
__UpperCAmelCase : Optional[int] = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device )
elif torch.is_tensor(UpperCamelCase ) and len(timesteps.shape ) == 0:
__UpperCAmelCase : Tuple = timesteps[None].to(hidden_states.device )
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
__UpperCAmelCase : Any = timesteps * torch.ones(UpperCamelCase , dtype=timesteps.dtype , device=timesteps.device )
__UpperCAmelCase : Tuple = self.time_proj(UpperCamelCase )
# timesteps does not contain any weights and will always return f32 tensors
# but time_embedding might be fp16, so we need to cast here.
__UpperCAmelCase : Any = timesteps_projected.to(dtype=self.dtype )
__UpperCAmelCase : Dict = self.time_embedding(UpperCamelCase )
if self.embedding_proj_norm is not None:
__UpperCAmelCase : List[str] = self.embedding_proj_norm(UpperCamelCase )
__UpperCAmelCase : int = self.embedding_proj(UpperCamelCase )
if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
__UpperCAmelCase : Any = self.encoder_hidden_states_proj(UpperCamelCase )
elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None:
raise ValueError("""`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set""" )
__UpperCAmelCase : str = self.proj_in(UpperCamelCase )
__UpperCAmelCase : Dict = self.positional_embedding.to(hidden_states.dtype )
__UpperCAmelCase : Optional[int] = []
__UpperCAmelCase : List[str] = 0
if encoder_hidden_states is not None:
additional_embeds.append(UpperCamelCase )
additional_embeddings_len += encoder_hidden_states.shape[1]
if len(proj_embeddings.shape ) == 2:
__UpperCAmelCase : Tuple = proj_embeddings[:, None, :]
if len(hidden_states.shape ) == 2:
__UpperCAmelCase : Any = hidden_states[:, None, :]
__UpperCAmelCase : List[Any] = additional_embeds + [
proj_embeddings,
time_embeddings[:, None, :],
hidden_states,
]
if self.prd_embedding is not None:
__UpperCAmelCase : Union[str, Any] = self.prd_embedding.to(hidden_states.dtype ).expand(UpperCamelCase , -1 , -1 )
additional_embeds.append(UpperCamelCase )
__UpperCAmelCase : str = torch.cat(
UpperCamelCase , dim=1 , )
# Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens
__UpperCAmelCase : Union[str, Any] = additional_embeddings_len + proj_embeddings.shape[1] + 1
if positional_embeddings.shape[1] < hidden_states.shape[1]:
__UpperCAmelCase : List[Any] = F.pad(
UpperCamelCase , (
0,
0,
additional_embeddings_len,
self.prd_embedding.shape[1] if self.prd_embedding is not None else 0,
) , value=0.0 , )
__UpperCAmelCase : str = hidden_states + positional_embeddings
if attention_mask is not None:
__UpperCAmelCase : List[Any] = (1 - attention_mask.to(hidden_states.dtype )) * -10000.0
__UpperCAmelCase : Optional[int] = F.pad(UpperCamelCase , (0, self.additional_embeddings) , value=0.0 )
__UpperCAmelCase : str = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype )
__UpperCAmelCase : int = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0 )
if self.norm_in is not None:
__UpperCAmelCase : Dict = self.norm_in(UpperCamelCase )
for block in self.transformer_blocks:
__UpperCAmelCase : Optional[int] = block(UpperCamelCase , attention_mask=UpperCamelCase )
__UpperCAmelCase : str = self.norm_out(UpperCamelCase )
if self.prd_embedding is not None:
__UpperCAmelCase : Optional[int] = hidden_states[:, -1]
else:
__UpperCAmelCase : str = hidden_states[:, additional_embeddings_len:]
__UpperCAmelCase : Union[str, Any] = self.proj_to_clip_embeddings(UpperCamelCase )
if not return_dict:
return (predicted_image_embedding,)
return PriorTransformerOutput(predicted_image_embedding=UpperCamelCase )
def lowerCamelCase__ ( self : Any , UpperCamelCase : List[Any] ):
'''simple docstring'''
__UpperCAmelCase : Dict = (prior_latents * self.clip_std) + self.clip_mean
return prior_latents
| 139 |
"""simple docstring"""
import baseaa
def lowerCamelCase ( _UpperCamelCase : str ) -> bytes:
'''simple docstring'''
return baseaa.baaencode(string.encode("""utf-8""" ) )
def lowerCamelCase ( _UpperCamelCase : bytes ) -> str:
'''simple docstring'''
return baseaa.baadecode(_UpperCamelCase ).decode("""utf-8""" )
if __name__ == "__main__":
UpperCAmelCase : Optional[int] = 'Hello World!'
UpperCAmelCase : Tuple = baseaa_encode(test)
print(encoded)
UpperCAmelCase : Any = baseaa_decode(encoded)
print(decoded)
| 139 | 1 |
"""simple docstring"""
import unittest
from transformers import MobileBertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
MODEL_FOR_PRETRAINING_MAPPING,
MobileBertForMaskedLM,
MobileBertForMultipleChoice,
MobileBertForNextSentencePrediction,
MobileBertForPreTraining,
MobileBertForQuestionAnswering,
MobileBertForSequenceClassification,
MobileBertForTokenClassification,
MobileBertModel,
)
class a :
def __init__( self : Union[str, Any] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Dict=13 , __lowerCAmelCase : int=7 , __lowerCAmelCase : Optional[int]=True , __lowerCAmelCase : str=True , __lowerCAmelCase : List[str]=True , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : Any=99 , __lowerCAmelCase : int=64 , __lowerCAmelCase : Dict=32 , __lowerCAmelCase : List[str]=5 , __lowerCAmelCase : str=4 , __lowerCAmelCase : str=37 , __lowerCAmelCase : Any="gelu" , __lowerCAmelCase : Dict=0.1 , __lowerCAmelCase : Any=0.1 , __lowerCAmelCase : int=512 , __lowerCAmelCase : Tuple=16 , __lowerCAmelCase : Dict=2 , __lowerCAmelCase : str=0.02 , __lowerCAmelCase : Tuple=3 , __lowerCAmelCase : Any=4 , __lowerCAmelCase : Optional[int]=None , ):
_UpperCAmelCase = parent
_UpperCAmelCase = batch_size
_UpperCAmelCase = seq_length
_UpperCAmelCase = is_training
_UpperCAmelCase = use_input_mask
_UpperCAmelCase = use_token_type_ids
_UpperCAmelCase = use_labels
_UpperCAmelCase = vocab_size
_UpperCAmelCase = hidden_size
_UpperCAmelCase = embedding_size
_UpperCAmelCase = num_hidden_layers
_UpperCAmelCase = num_attention_heads
_UpperCAmelCase = intermediate_size
_UpperCAmelCase = hidden_act
_UpperCAmelCase = hidden_dropout_prob
_UpperCAmelCase = attention_probs_dropout_prob
_UpperCAmelCase = max_position_embeddings
_UpperCAmelCase = type_vocab_size
_UpperCAmelCase = type_sequence_label_size
_UpperCAmelCase = initializer_range
_UpperCAmelCase = num_labels
_UpperCAmelCase = num_choices
_UpperCAmelCase = scope
def lowerCAmelCase_ ( self : Union[str, Any] ):
_UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
_UpperCAmelCase = None
if self.use_input_mask:
_UpperCAmelCase = random_attention_mask([self.batch_size, self.seq_length] )
_UpperCAmelCase = None
if self.use_token_type_ids:
_UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
_UpperCAmelCase = None
_UpperCAmelCase = None
_UpperCAmelCase = None
if self.use_labels:
_UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size )
_UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
_UpperCAmelCase = ids_tensor([self.batch_size] , self.num_choices )
_UpperCAmelCase = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def lowerCAmelCase_ ( self : List[Any] ):
return MobileBertConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , embedding_size=self.embedding_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__lowerCAmelCase , initializer_range=self.initializer_range , )
def lowerCAmelCase_ ( self : str , __lowerCAmelCase : Any , __lowerCAmelCase : Any , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[int] ):
_UpperCAmelCase = MobileBertModel(config=__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
_UpperCAmelCase = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase )
_UpperCAmelCase = model(__lowerCAmelCase , token_type_ids=__lowerCAmelCase )
_UpperCAmelCase = model(__lowerCAmelCase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) )
def lowerCAmelCase_ ( self : Optional[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : int , __lowerCAmelCase : Any , __lowerCAmelCase : List[Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Any ):
_UpperCAmelCase = MobileBertForMaskedLM(config=__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
_UpperCAmelCase = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def lowerCAmelCase_ ( self : Dict , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Tuple , __lowerCAmelCase : int ):
_UpperCAmelCase = MobileBertForNextSentencePrediction(config=__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
_UpperCAmelCase = model(
__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) )
def lowerCAmelCase_ ( self : Dict , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : Dict , __lowerCAmelCase : Tuple ):
_UpperCAmelCase = MobileBertForPreTraining(config=__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
_UpperCAmelCase = model(
__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase , next_sentence_label=__lowerCAmelCase , )
self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) )
def lowerCAmelCase_ ( self : Union[str, Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] , __lowerCAmelCase : int , __lowerCAmelCase : Dict , __lowerCAmelCase : str , __lowerCAmelCase : Any , __lowerCAmelCase : str ):
_UpperCAmelCase = MobileBertForQuestionAnswering(config=__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
_UpperCAmelCase = model(
__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , start_positions=__lowerCAmelCase , end_positions=__lowerCAmelCase , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def lowerCAmelCase_ ( self : Tuple , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : str , __lowerCAmelCase : int , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Tuple , __lowerCAmelCase : str ):
_UpperCAmelCase = self.num_labels
_UpperCAmelCase = MobileBertForSequenceClassification(__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
_UpperCAmelCase = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def lowerCAmelCase_ ( self : int , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[Any] ):
_UpperCAmelCase = self.num_labels
_UpperCAmelCase = MobileBertForTokenClassification(config=__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
_UpperCAmelCase = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def lowerCAmelCase_ ( self : List[str] , __lowerCAmelCase : Any , __lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Tuple , __lowerCAmelCase : str , __lowerCAmelCase : Tuple ):
_UpperCAmelCase = self.num_choices
_UpperCAmelCase = MobileBertForMultipleChoice(config=__lowerCAmelCase )
model.to(__lowerCAmelCase )
model.eval()
_UpperCAmelCase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
_UpperCAmelCase = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
_UpperCAmelCase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
_UpperCAmelCase = model(
__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def lowerCAmelCase_ ( self : int ):
_UpperCAmelCase = self.prepare_config_and_inputs()
(
(
_UpperCAmelCase
) , (
_UpperCAmelCase
) , (
_UpperCAmelCase
) , (
_UpperCAmelCase
) , (
_UpperCAmelCase
) , (
_UpperCAmelCase
) , (
_UpperCAmelCase
) ,
) = config_and_inputs
_UpperCAmelCase = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
return config, inputs_dict
@require_torch
class a ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ):
_snake_case : Optional[int] = (
(
MobileBertModel,
MobileBertForMaskedLM,
MobileBertForMultipleChoice,
MobileBertForNextSentencePrediction,
MobileBertForPreTraining,
MobileBertForQuestionAnswering,
MobileBertForSequenceClassification,
MobileBertForTokenClassification,
)
if is_torch_available()
else ()
)
_snake_case : List[str] = (
{
'feature-extraction': MobileBertModel,
'fill-mask': MobileBertForMaskedLM,
'question-answering': MobileBertForQuestionAnswering,
'text-classification': MobileBertForSequenceClassification,
'token-classification': MobileBertForTokenClassification,
'zero-shot': MobileBertForSequenceClassification,
}
if is_torch_available()
else {}
)
_snake_case : Tuple = True
def lowerCAmelCase_ ( self : List[Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : List[str]=False ):
_UpperCAmelCase = super()._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase , return_labels=__lowerCAmelCase )
if return_labels:
if model_class in get_values(__lowerCAmelCase ):
_UpperCAmelCase = torch.zeros(
(self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=__lowerCAmelCase )
_UpperCAmelCase = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=__lowerCAmelCase )
return inputs_dict
def lowerCAmelCase_ ( self : Dict ):
_UpperCAmelCase = MobileBertModelTester(self )
_UpperCAmelCase = ConfigTester(self , config_class=__lowerCAmelCase , hidden_size=37 )
def lowerCAmelCase_ ( self : Optional[Any] ):
self.config_tester.run_common_tests()
def lowerCAmelCase_ ( self : Optional[Any] ):
_UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_model(*__lowerCAmelCase )
def lowerCAmelCase_ ( self : Tuple ):
_UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_masked_lm(*__lowerCAmelCase )
def lowerCAmelCase_ ( self : Tuple ):
_UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_multiple_choice(*__lowerCAmelCase )
def lowerCAmelCase_ ( self : Optional[Any] ):
_UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*__lowerCAmelCase )
def lowerCAmelCase_ ( self : Optional[Any] ):
_UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_pretraining(*__lowerCAmelCase )
def lowerCAmelCase_ ( self : Tuple ):
_UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_question_answering(*__lowerCAmelCase )
def lowerCAmelCase_ ( self : Tuple ):
_UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_sequence_classification(*__lowerCAmelCase )
def lowerCAmelCase_ ( self : List[Any] ):
_UpperCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_token_classification(*__lowerCAmelCase )
def __UpperCAmelCase ( lowercase ):
"""simple docstring"""
return torch.tensor(
lowercase ,dtype=torch.long ,device=lowercase ,)
UpperCAmelCase__ = 1E-3
@require_torch
@require_sentencepiece
@require_tokenizers
class a ( unittest.TestCase ):
@slow
def lowerCAmelCase_ ( self : Dict ):
_UpperCAmelCase = MobileBertModel.from_pretrained("""google/mobilebert-uncased""" ).to(__lowerCAmelCase )
_UpperCAmelCase = _long_tensor([[101, 7110, 1005, 1056, 2023, 1_1333, 1_7413, 1029, 102]] )
with torch.no_grad():
_UpperCAmelCase = model(__lowerCAmelCase )[0]
_UpperCAmelCase = torch.Size((1, 9, 512) )
self.assertEqual(output.shape , __lowerCAmelCase )
_UpperCAmelCase = torch.tensor(
[
[
[-2.4_7_3_6_5_2_6e0_7, 8.2_6_9_1_6_5_6e0_4, 1.6_5_2_1_8_3_8e0_5],
[-5.7_5_4_1_7_0_4e-0_1, 3.9_0_5_6_0_2_2e0_0, 4.4_0_1_1_5_0_7e0_0],
[2.6_0_4_7_3_5_9e0_0, 1.5_6_7_7_6_5_2e0_0, -1.7_3_2_4_1_8_8e-0_1],
]
] , device=__lowerCAmelCase , )
# MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a
# ~1 difference, it's therefore not a good idea to measure using addition.
# Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the
# result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE
_UpperCAmelCase = torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE )
_UpperCAmelCase = torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE )
self.assertTrue(lower_bound and upper_bound )
| 721 | """simple docstring"""
from argparse import ArgumentParser, Namespace
from typing import Any, List, Optional
from ..pipelines import Pipeline, get_supported_tasks, pipeline
from ..utils import logging
from . import BaseTransformersCLICommand
try:
from fastapi import Body, FastAPI, HTTPException
from fastapi.routing import APIRoute
from pydantic import BaseModel
from starlette.responses import JSONResponse
from uvicorn import run
UpperCAmelCase__ = True
except (ImportError, AttributeError):
UpperCAmelCase__ = object
def __UpperCAmelCase ( *lowercase ,**lowercase ):
"""simple docstring"""
pass
UpperCAmelCase__ = False
UpperCAmelCase__ = logging.get_logger("""transformers-cli/serving""")
def __UpperCAmelCase ( lowercase ):
"""simple docstring"""
_UpperCAmelCase = pipeline(
task=args.task ,model=args.model if args.model else None ,config=args.config ,tokenizer=args.tokenizer ,device=args.device ,)
return ServeCommand(lowercase ,args.host ,args.port ,args.workers )
class a ( lowerCAmelCase_ ):
_snake_case : dict
class a ( lowerCAmelCase_ ):
_snake_case : List[str]
_snake_case : Optional[List[int]]
class a ( lowerCAmelCase_ ):
_snake_case : str
class a ( lowerCAmelCase_ ):
_snake_case : Any
class a ( lowerCAmelCase_ ):
@staticmethod
def lowerCAmelCase_ ( __lowerCAmelCase : ArgumentParser ):
_UpperCAmelCase = parser.add_parser(
"""serve""" , help="""CLI tool to run inference requests through REST and GraphQL endpoints.""" )
serve_parser.add_argument(
"""--task""" , type=__lowerCAmelCase , choices=get_supported_tasks() , help="""The task to run the pipeline on""" , )
serve_parser.add_argument("""--host""" , type=__lowerCAmelCase , default="""localhost""" , help="""Interface the server will listen on.""" )
serve_parser.add_argument("""--port""" , type=__lowerCAmelCase , default=8888 , help="""Port the serving will listen to.""" )
serve_parser.add_argument("""--workers""" , type=__lowerCAmelCase , default=1 , help="""Number of http workers""" )
serve_parser.add_argument("""--model""" , type=__lowerCAmelCase , help="""Model's name or path to stored model.""" )
serve_parser.add_argument("""--config""" , type=__lowerCAmelCase , help="""Model's config name or path to stored model.""" )
serve_parser.add_argument("""--tokenizer""" , type=__lowerCAmelCase , help="""Tokenizer name to use.""" )
serve_parser.add_argument(
"""--device""" , type=__lowerCAmelCase , default=-1 , help="""Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)""" , )
serve_parser.set_defaults(func=__lowerCAmelCase )
def __init__( self : Tuple , __lowerCAmelCase : Pipeline , __lowerCAmelCase : str , __lowerCAmelCase : int , __lowerCAmelCase : int ):
_UpperCAmelCase = pipeline
_UpperCAmelCase = host
_UpperCAmelCase = port
_UpperCAmelCase = workers
if not _serve_dependencies_installed:
raise RuntimeError(
"""Using serve command requires FastAPI and uvicorn. """
"""Please install transformers with [serving]: pip install \"transformers[serving]\"."""
"""Or install FastAPI and uvicorn separately.""" )
else:
logger.info(f'''Serving model over {host}:{port}''' )
_UpperCAmelCase = FastAPI(
routes=[
APIRoute(
"""/""" , self.model_info , response_model=__lowerCAmelCase , response_class=__lowerCAmelCase , methods=["""GET"""] , ),
APIRoute(
"""/tokenize""" , self.tokenize , response_model=__lowerCAmelCase , response_class=__lowerCAmelCase , methods=["""POST"""] , ),
APIRoute(
"""/detokenize""" , self.detokenize , response_model=__lowerCAmelCase , response_class=__lowerCAmelCase , methods=["""POST"""] , ),
APIRoute(
"""/forward""" , self.forward , response_model=__lowerCAmelCase , response_class=__lowerCAmelCase , methods=["""POST"""] , ),
] , timeout=600 , )
def lowerCAmelCase_ ( self : Optional[int] ):
run(self._app , host=self.host , port=self.port , workers=self.workers )
def lowerCAmelCase_ ( self : str ):
return ServeModelInfoResult(infos=vars(self._pipeline.model.config ) )
def lowerCAmelCase_ ( self : Tuple , __lowerCAmelCase : str = Body(__lowerCAmelCase , embed=__lowerCAmelCase ) , __lowerCAmelCase : bool = Body(__lowerCAmelCase , embed=__lowerCAmelCase ) ):
try:
_UpperCAmelCase = self._pipeline.tokenizer.tokenize(__lowerCAmelCase )
if return_ids:
_UpperCAmelCase = self._pipeline.tokenizer.convert_tokens_to_ids(__lowerCAmelCase )
return ServeTokenizeResult(tokens=__lowerCAmelCase , tokens_ids=__lowerCAmelCase )
else:
return ServeTokenizeResult(tokens=__lowerCAmelCase )
except Exception as e:
raise HTTPException(status_code=500 , detail={"""model""": """""", """error""": str(__lowerCAmelCase )} )
def lowerCAmelCase_ ( self : int , __lowerCAmelCase : List[int] = Body(__lowerCAmelCase , embed=__lowerCAmelCase ) , __lowerCAmelCase : bool = Body(__lowerCAmelCase , embed=__lowerCAmelCase ) , __lowerCAmelCase : bool = Body(__lowerCAmelCase , embed=__lowerCAmelCase ) , ):
try:
_UpperCAmelCase = self._pipeline.tokenizer.decode(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
return ServeDeTokenizeResult(model="""""" , text=__lowerCAmelCase )
except Exception as e:
raise HTTPException(status_code=500 , detail={"""model""": """""", """error""": str(__lowerCAmelCase )} )
async def lowerCAmelCase_ ( self : str , __lowerCAmelCase : List[Any]=Body(__lowerCAmelCase , embed=__lowerCAmelCase ) ):
# Check we don't have empty string
if len(__lowerCAmelCase ) == 0:
return ServeForwardResult(output=[] , attention=[] )
try:
# Forward through the model
_UpperCAmelCase = self._pipeline(__lowerCAmelCase )
return ServeForwardResult(output=__lowerCAmelCase )
except Exception as e:
raise HTTPException(500 , {"""error""": str(__lowerCAmelCase )} )
| 275 | 0 |
import argparse
import os
import torch
from transformers import FlavaConfig, FlavaForPreTraining
from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint
def __lowerCAmelCase ( __lowerCamelCase : Tuple ) -> Dict:
# encoder.embeddings are double copied in original FLAVA
return sum(param.float().sum() if """encoder.embeddings""" not in key else 0 for key, param in state_dict.items() )
def __lowerCAmelCase ( __lowerCamelCase : Any , __lowerCamelCase : Union[str, Any] ) -> List[str]:
__lowerCAmelCase ={}
for key, value in state_dict.items():
if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key:
continue
__lowerCAmelCase =key.replace("""heads.cmd.mim_head.cls.predictions""" , """mmm_image_head""" )
__lowerCAmelCase =key.replace("""heads.cmd.mlm_head.cls.predictions""" , """mmm_text_head""" )
__lowerCAmelCase =key.replace("""heads.cmd.itm_head.cls""" , """itm_head""" )
__lowerCAmelCase =key.replace("""heads.cmd.itm_head.pooler""" , """itm_head.pooler""" )
__lowerCAmelCase =key.replace("""heads.cmd.clip_head.logit_scale""" , """flava.logit_scale""" )
__lowerCAmelCase =key.replace("""heads.fairseq_mlm.cls.predictions""" , """mlm_head""" )
__lowerCAmelCase =key.replace("""heads.imagenet.mim_head.cls.predictions""" , """mim_head""" )
__lowerCAmelCase =key.replace("""mm_text_projection""" , """flava.text_to_mm_projection""" )
__lowerCAmelCase =key.replace("""mm_image_projection""" , """flava.image_to_mm_projection""" )
__lowerCAmelCase =key.replace("""image_encoder.module""" , """flava.image_model""" )
__lowerCAmelCase =key.replace("""text_encoder.module""" , """flava.text_model""" )
__lowerCAmelCase =key.replace("""mm_encoder.module.encoder.cls_token""" , """flava.multimodal_model.cls_token""" )
__lowerCAmelCase =key.replace("""mm_encoder.module""" , """flava.multimodal_model""" )
__lowerCAmelCase =key.replace("""text_projection""" , """flava.text_projection""" )
__lowerCAmelCase =key.replace("""image_projection""" , """flava.image_projection""" )
__lowerCAmelCase =value.float()
for key, value in codebook_state_dict.items():
__lowerCAmelCase =value
return upgrade
@torch.no_grad()
def __lowerCAmelCase ( __lowerCamelCase : Tuple , __lowerCamelCase : Any , __lowerCamelCase : List[str] , __lowerCamelCase : int=None ) -> int:
if config_path is not None:
__lowerCAmelCase =FlavaConfig.from_pretrained(__lowerCamelCase )
else:
__lowerCAmelCase =FlavaConfig()
__lowerCAmelCase =FlavaForPreTraining(__lowerCamelCase ).eval()
__lowerCAmelCase =convert_dalle_checkpoint(__lowerCamelCase , __lowerCamelCase , save_checkpoint=__lowerCamelCase )
if os.path.exists(__lowerCamelCase ):
__lowerCAmelCase =torch.load(__lowerCamelCase , map_location="""cpu""" )
else:
__lowerCAmelCase =torch.hub.load_state_dict_from_url(__lowerCamelCase , map_location="""cpu""" )
__lowerCAmelCase =upgrade_state_dict(__lowerCamelCase , __lowerCamelCase )
hf_model.load_state_dict(__lowerCamelCase )
__lowerCAmelCase =hf_model.state_dict()
__lowerCAmelCase =count_parameters(__lowerCamelCase )
__lowerCAmelCase =count_parameters(__lowerCamelCase ) + count_parameters(__lowerCamelCase )
assert torch.allclose(__lowerCamelCase , __lowerCamelCase , atol=1E-3 )
hf_model.save_pretrained(__lowerCamelCase )
if __name__ == "__main__":
lowercase_ = argparse.ArgumentParser()
parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to flava checkpoint''')
parser.add_argument('''--codebook_path''', default=None, type=str, help='''Path to flava codebook checkpoint''')
parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''')
lowercase_ = parser.parse_args()
convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
| 354 |
from __future__ import annotations
class __a :
def __init__( self : Optional[int] , snake_case_ : int = 0)-> List[str]:
__lowerCAmelCase =key
def UpperCamelCase ( self : Any , snake_case_ : str , snake_case_ : int)-> list[str]:
assert isinstance(snake_case_ , snake_case_) and isinstance(snake_case_ , snake_case_)
__lowerCAmelCase =key or self.__key or 1
# make sure key is an appropriate size
key %= 2_55
return [chr(ord(snake_case_) ^ key) for ch in content]
def UpperCamelCase ( self : Tuple , snake_case_ : str , snake_case_ : int)-> list[str]:
assert isinstance(snake_case_ , snake_case_) and isinstance(snake_case_ , snake_case_)
__lowerCAmelCase =key or self.__key or 1
# make sure key is an appropriate size
key %= 2_55
return [chr(ord(snake_case_) ^ key) for ch in content]
def UpperCamelCase ( self : str , snake_case_ : str , snake_case_ : int = 0)-> str:
assert isinstance(snake_case_ , snake_case_) and isinstance(snake_case_ , snake_case_)
__lowerCAmelCase =key or self.__key or 1
# make sure key can be any size
while key > 2_55:
key -= 2_55
# This will be returned
__lowerCAmelCase =""""""
for ch in content:
ans += chr(ord(snake_case_) ^ key)
return ans
def UpperCamelCase ( self : Tuple , snake_case_ : str , snake_case_ : int = 0)-> str:
assert isinstance(snake_case_ , snake_case_) and isinstance(snake_case_ , snake_case_)
__lowerCAmelCase =key or self.__key or 1
# make sure key can be any size
while key > 2_55:
key -= 2_55
# This will be returned
__lowerCAmelCase =""""""
for ch in content:
ans += chr(ord(snake_case_) ^ key)
return ans
def UpperCamelCase ( self : int , snake_case_ : str , snake_case_ : int = 0)-> bool:
assert isinstance(snake_case_ , snake_case_) and isinstance(snake_case_ , snake_case_)
try:
with open(snake_case_) as fin, open("""encrypt.out""" , """w+""") as fout:
# actual encrypt-process
for line in fin:
fout.write(self.encrypt_string(snake_case_ , snake_case_))
except OSError:
return False
return True
def UpperCamelCase ( self : Tuple , snake_case_ : str , snake_case_ : int)-> bool:
assert isinstance(snake_case_ , snake_case_) and isinstance(snake_case_ , snake_case_)
try:
with open(snake_case_) as fin, open("""decrypt.out""" , """w+""") as fout:
# actual encrypt-process
for line in fin:
fout.write(self.decrypt_string(snake_case_ , snake_case_))
except OSError:
return False
return True
# Tests
# crypt = XORCipher()
# key = 67
# # test encrypt
# print(crypt.encrypt("hallo welt",key))
# # test decrypt
# print(crypt.decrypt(crypt.encrypt("hallo welt",key), key))
# # test encrypt_string
# print(crypt.encrypt_string("hallo welt",key))
# # test decrypt_string
# print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key))
# if (crypt.encrypt_file("test.txt",key)):
# print("encrypt successful")
# else:
# print("encrypt unsuccessful")
# if (crypt.decrypt_file("encrypt.out",key)):
# print("decrypt successful")
# else:
# print("decrypt unsuccessful")
| 354 | 1 |
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
| 332 |
from ...configuration_utils import PretrainedConfig
_UpperCamelCase : Tuple ={
'google/tapas-base-finetuned-sqa': (
'https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json'
),
'google/tapas-base-finetuned-wtq': (
'https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json'
),
'google/tapas-base-finetuned-wikisql-supervised': (
'https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json'
),
'google/tapas-base-finetuned-tabfact': (
'https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json'
),
}
class UpperCAmelCase__ ( __snake_case ):
__snake_case : List[Any] = "tapas"
def __init__( self ,A__=30522 ,A__=768 ,A__=12 ,A__=12 ,A__=3072 ,A__="gelu" ,A__=0.1 ,A__=0.1 ,A__=1024 ,A__=[3, 256, 256, 2, 256, 256, 10] ,A__=0.02 ,A__=1E-12 ,A__=0 ,A__=10.0 ,A__=0 ,A__=1.0 ,A__=None ,A__=1.0 ,A__=False ,A__=None ,A__=1.0 ,A__=1.0 ,A__=False ,A__=False ,A__="ratio" ,A__=None ,A__=None ,A__=64 ,A__=32 ,A__=False ,A__=True ,A__=False ,A__=False ,A__=True ,A__=False ,A__=None ,A__=None ,**A__ ,):
super().__init__(pad_token_id=A__ ,**A__ )
# BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes)
_A : int = vocab_size
_A : Dict = hidden_size
_A : List[str] = num_hidden_layers
_A : Tuple = num_attention_heads
_A : Any = hidden_act
_A : str = intermediate_size
_A : List[str] = hidden_dropout_prob
_A : List[Any] = attention_probs_dropout_prob
_A : Tuple = max_position_embeddings
_A : Optional[Any] = type_vocab_sizes
_A : List[Any] = initializer_range
_A : Optional[Any] = layer_norm_eps
# Fine-tuning task hyperparameters
_A : Optional[Any] = positive_label_weight
_A : List[Any] = num_aggregation_labels
_A : Union[str, Any] = aggregation_loss_weight
_A : Optional[int] = use_answer_as_supervision
_A : Tuple = answer_loss_importance
_A : Dict = use_normalized_answer_loss
_A : Union[str, Any] = huber_loss_delta
_A : Union[str, Any] = temperature
_A : Optional[Any] = aggregation_temperature
_A : Optional[int] = use_gumbel_for_cells
_A : List[str] = use_gumbel_for_aggregation
_A : int = average_approximation_function
_A : Union[str, Any] = cell_selection_preference
_A : List[str] = answer_loss_cutoff
_A : List[Any] = max_num_rows
_A : List[str] = max_num_columns
_A : Union[str, Any] = average_logits_per_cell
_A : Optional[Any] = select_one_column
_A : List[str] = allow_empty_column_selection
_A : int = init_cell_selection_weights_to_zero
_A : Dict = reset_position_index_per_cell
_A : Dict = disable_per_token_loss
# Aggregation hyperparameters
_A : Tuple = aggregation_labels
_A : Dict = no_aggregation_label_index
if isinstance(self.aggregation_labels ,A__ ):
_A : Dict = {int(A__ ): v for k, v in aggregation_labels.items()}
| 332 | 1 |
import argparse
import json
import os
from pathlib import Path
import requests
import torch
from transformers import JukeboxConfig, JukeboxModel
from transformers.utils import logging
logging.set_verbosity_info()
_UpperCAmelCase : Optional[Any] = logging.get_logger(__name__)
_UpperCAmelCase : str = """https://openaipublic.azureedge.net/jukebox/models/"""
_UpperCAmelCase : Union[str, Any] = {
"""jukebox-1b-lyrics""": [
"""5b/vqvae.pth.tar""",
"""5b/prior_level_0.pth.tar""",
"""5b/prior_level_1.pth.tar""",
"""1b_lyrics/prior_level_2.pth.tar""",
],
"""jukebox-5b-lyrics""": [
"""5b/vqvae.pth.tar""",
"""5b/prior_level_0.pth.tar""",
"""5b/prior_level_1.pth.tar""",
"""5b_lyrics/prior_level_2.pth.tar""",
],
}
def __lowerCamelCase ( UpperCamelCase__ ):
'''simple docstring'''
if key.endswith('.model.1.bias' ) and len(key.split('.' ) ) > 10:
snake_case_ = key.replace('.model.1.bias' , '.conv1d_1.bias' )
elif key.endswith('.model.1.weight' ) and len(key.split('.' ) ) > 10:
snake_case_ = key.replace('.model.1.weight' , '.conv1d_1.weight' )
elif key.endswith('.model.3.bias' ) and len(key.split('.' ) ) > 10:
snake_case_ = key.replace('.model.3.bias' , '.conv1d_2.bias' )
elif key.endswith('.model.3.weight' ) and len(key.split('.' ) ) > 10:
snake_case_ = key.replace('.model.3.weight' , '.conv1d_2.weight' )
if "conditioner_blocks.0." in key:
snake_case_ = key.replace('conditioner_blocks.0' , 'conditioner_blocks' )
if "prime_prior" in key:
snake_case_ = key.replace('prime_prior' , 'encoder' )
if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key:
snake_case_ = key.replace('.emb.' , '.' )
if key.endswith('k' ): # replace vqvae.X.k with vqvae.X.codebook
return key.replace('.k' , '.codebook' )
if "y_emb." in key:
return key.replace('y_emb.' , 'metadata_embedding.' )
if "x_emb.emb." in key:
snake_case_ = key.replace('0.x_emb.emb' , 'embed_tokens' )
if "prime_state_ln" in key:
return key.replace('prime_state_ln' , 'encoder.final_layer_norm' )
if ".ln" in key:
return key.replace('.ln' , '.layer_norm' )
if "_ln" in key:
return key.replace('_ln' , '_layer_norm' )
if "prime_state_proj" in key:
return key.replace('prime_state_proj' , 'encoder.proj_in' )
if "prime_x_out" in key:
return key.replace('prime_x_out' , 'encoder.lm_head' )
if "prior.x_out" in key:
return key.replace('x_out' , 'fc_proj_out' )
if "x_emb" in key:
return key.replace('x_emb' , 'embed_tokens' )
return key
def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ):
'''simple docstring'''
snake_case_ = {}
import re
snake_case_ = re.compile(r'encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)' )
snake_case_ = re.compile(
r'encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)' )
snake_case_ = re.compile(r'encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)' )
snake_case_ = re.compile(r'decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)' )
snake_case_ = re.compile(
r'decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)' )
snake_case_ = re.compile(r'decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)' )
snake_case_ = re.compile(r'conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)' )
snake_case_ = re.compile(
r'conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)' )
snake_case_ = re.compile(r'conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)' )
for original_key, value in state_dict.items():
# rename vqvae.encoder keys
if re_encoder_block_conv_in.fullmatch(UpperCamelCase__ ):
snake_case_ = re_encoder_block_conv_in.match(UpperCamelCase__ )
snake_case_ = regex_match.groups()
snake_case_ = int(groups[2] ) * 2 + int(groups[3] )
snake_case_ = F'''encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}'''
snake_case_ = re_encoder_block_conv_in.sub(UpperCamelCase__ , UpperCamelCase__ )
elif re_encoder_block_resnet.fullmatch(UpperCamelCase__ ):
snake_case_ = re_encoder_block_resnet.match(UpperCamelCase__ )
snake_case_ = regex_match.groups()
snake_case_ = int(groups[2] ) * 2 + int(groups[3] )
snake_case_ = {'1': 1, '3': 2}[groups[-2]]
snake_case_ = F'''encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.'''
snake_case_ = F'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}'''
snake_case_ = prefix + resnet_block
snake_case_ = re_encoder_block_resnet.sub(UpperCamelCase__ , UpperCamelCase__ )
elif re_encoder_block_proj_out.fullmatch(UpperCamelCase__ ):
snake_case_ = re_encoder_block_proj_out.match(UpperCamelCase__ )
snake_case_ = regex_match.groups()
snake_case_ = F'''encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}'''
snake_case_ = re_encoder_block_proj_out.sub(UpperCamelCase__ , UpperCamelCase__ )
# rename vqvae.decoder keys
elif re_decoder_block_conv_out.fullmatch(UpperCamelCase__ ):
snake_case_ = re_decoder_block_conv_out.match(UpperCamelCase__ )
snake_case_ = regex_match.groups()
snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2
snake_case_ = F'''decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}'''
snake_case_ = re_decoder_block_conv_out.sub(UpperCamelCase__ , UpperCamelCase__ )
elif re_decoder_block_resnet.fullmatch(UpperCamelCase__ ):
snake_case_ = re_decoder_block_resnet.match(UpperCamelCase__ )
snake_case_ = regex_match.groups()
snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2
snake_case_ = {'1': 1, '3': 2}[groups[-2]]
snake_case_ = F'''decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.'''
snake_case_ = F'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}'''
snake_case_ = prefix + resnet_block
snake_case_ = re_decoder_block_resnet.sub(UpperCamelCase__ , UpperCamelCase__ )
elif re_decoder_block_proj_in.fullmatch(UpperCamelCase__ ):
snake_case_ = re_decoder_block_proj_in.match(UpperCamelCase__ )
snake_case_ = regex_match.groups()
snake_case_ = F'''decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}'''
snake_case_ = re_decoder_block_proj_in.sub(UpperCamelCase__ , UpperCamelCase__ )
# rename prior cond.model to upsampler.upsample_block and resnet
elif re_prior_cond_conv_out.fullmatch(UpperCamelCase__ ):
snake_case_ = re_prior_cond_conv_out.match(UpperCamelCase__ )
snake_case_ = regex_match.groups()
snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2
snake_case_ = F'''conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}'''
snake_case_ = re_prior_cond_conv_out.sub(UpperCamelCase__ , UpperCamelCase__ )
elif re_prior_cond_resnet.fullmatch(UpperCamelCase__ ):
snake_case_ = re_prior_cond_resnet.match(UpperCamelCase__ )
snake_case_ = regex_match.groups()
snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2
snake_case_ = {'1': 1, '3': 2}[groups[-2]]
snake_case_ = F'''conditioner_blocks.upsampler.upsample_block.{block_index}.'''
snake_case_ = F'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}'''
snake_case_ = prefix + resnet_block
snake_case_ = re_prior_cond_resnet.sub(UpperCamelCase__ , UpperCamelCase__ )
elif re_prior_cond_proj_in.fullmatch(UpperCamelCase__ ):
snake_case_ = re_prior_cond_proj_in.match(UpperCamelCase__ )
snake_case_ = regex_match.groups()
snake_case_ = F'''conditioner_blocks.upsampler.proj_in.{groups[-1]}'''
snake_case_ = re_prior_cond_proj_in.sub(UpperCamelCase__ , UpperCamelCase__ )
# keep original key
else:
snake_case_ = original_key
snake_case_ = replace_key(UpperCamelCase__ )
if F'''{key_prefix}.{key}''' not in model_state_dict or key is None:
print(F'''failed converting {original_key} to {key}, does not match''' )
# handle missmatched shape
elif value.shape != model_state_dict[F'''{key_prefix}.{key}'''].shape:
snake_case_ = model_state_dict[F'''{key_prefix}.{key}''']
print(F'''{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match''' )
snake_case_ = original_key
snake_case_ = original_key
snake_case_ = value
return new_dict
@torch.no_grad()
def __lowerCamelCase ( UpperCamelCase__=None , UpperCamelCase__=None ):
'''simple docstring'''
for file in MODEL_MAPPING[model_name]:
if not os.path.isfile(F'''{pytorch_dump_folder_path}/{file.split("/" )[-1]}''' ):
snake_case_ = requests.get(F'''{PREFIX}{file}''' , allow_redirects=UpperCamelCase__ )
os.makedirs(F'''{pytorch_dump_folder_path}/''' , exist_ok=UpperCamelCase__ )
open(F'''{pytorch_dump_folder_path}/{file.split("/" )[-1]}''' , 'wb' ).write(r.content )
snake_case_ = MODEL_MAPPING[model_name.split('/' )[-1]]
snake_case_ = JukeboxConfig.from_pretrained(UpperCamelCase__ )
snake_case_ = JukeboxModel(UpperCamelCase__ )
snake_case_ = []
snake_case_ = {}
for i, dict_name in enumerate(UpperCamelCase__ ):
snake_case_ = torch.load(F'''{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}''' )['model']
snake_case_ = {}
for k in old_dic.keys():
if k.endswith('.b' ):
snake_case_ = old_dic[k]
elif k.endswith('.w' ):
snake_case_ = old_dic[k]
elif "level_2" not in dict_name and "cond.model." in k:
snake_case_ = old_dic[k]
else:
snake_case_ = old_dic[k]
snake_case_ = 'vqvae' if i == 0 else F'''priors.{3 - i}'''
snake_case_ = fix_jukebox_keys(UpperCamelCase__ , model.state_dict() , UpperCamelCase__ , UpperCamelCase__ )
weight_dict.append(UpperCamelCase__ )
snake_case_ = weight_dict.pop(0 )
model.vqvae.load_state_dict(UpperCamelCase__ )
for i in range(len(UpperCamelCase__ ) ):
model.priors[i].load_state_dict(weight_dict[2 - i] )
Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ )
with open(F'''{pytorch_dump_folder_path}/mapping.json''' , 'w' ) as txtfile:
json.dump(UpperCamelCase__ , UpperCamelCase__ )
print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(UpperCamelCase__ )
return weight_dict
if __name__ == "__main__":
_UpperCAmelCase : Optional[int] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--model_name""",
default="""jukebox-5b-lyrics""",
type=str,
help="""Name of the model you'd like to convert.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""",
default="""jukebox-5b-lyrics-converted""",
type=str,
help="""Path to the output PyTorch model directory.""",
)
_UpperCAmelCase : Optional[Any] = parser.parse_args()
convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
| 362 |
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 ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ):
'''simple docstring'''
snake_case_ = BertConfig.from_json_file(UpperCamelCase__ )
print(F'''Building PyTorch model from configuration: {config}''' )
snake_case_ = BertForPreTraining(UpperCamelCase__ )
# Load weights from tf checkpoint
load_tf_weights_in_bert(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )
# Save pytorch-model
print(F'''Save PyTorch model to {pytorch_dump_path}''' )
torch.save(model.state_dict() , UpperCamelCase__ )
if __name__ == "__main__":
_UpperCAmelCase : Union[str, Any] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path."""
)
parser.add_argument(
"""--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."""
)
_UpperCAmelCase : Any = parser.parse_args()
convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
| 362 | 1 |
def A_ ( a ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : int = len(a )
SCREAMING_SNAKE_CASE_ : int = sum(a )
SCREAMING_SNAKE_CASE_ : Dict = [[False for x in range(s + 1 )] for y in range(n + 1 )]
for i in range(1 , n + 1 ):
SCREAMING_SNAKE_CASE_ : List[Any] = True
for i in range(1 , s + 1 ):
SCREAMING_SNAKE_CASE_ : Tuple = False
for i in range(1 , n + 1 ):
for j in range(1 , s + 1 ):
SCREAMING_SNAKE_CASE_ : Optional[int] = dp[i][j - 1]
if arr[i - 1] <= j:
SCREAMING_SNAKE_CASE_ : Any = dp[i][j] or dp[i - 1][j - arr[i - 1]]
for j in range(int(s / 2 ) , -1 , -1 ):
if dp[n][j] is True:
SCREAMING_SNAKE_CASE_ : str = s - 2 * j
break
return diff
| 353 |
def A_ ( a , a , a ):
"""simple docstring"""
if len(a ) != len(a ):
raise ValueError('The length of profit and weight must be same.' )
if max_weight <= 0:
raise ValueError('max_weight must greater than zero.' )
if any(p < 0 for p in profit ):
raise ValueError('Profit can not be negative.' )
if any(w < 0 for w in weight ):
raise ValueError('Weight can not be negative.' )
# List created to store profit gained for the 1kg in case of each weight
# respectively. Calculate and append profit/weight for each element.
SCREAMING_SNAKE_CASE_ : Tuple = [p / w for p, w in zip(a , a )]
# Creating a copy of the list and sorting profit/weight in ascending order
SCREAMING_SNAKE_CASE_ : List[Any] = sorted(a )
# declaring useful variables
SCREAMING_SNAKE_CASE_ : List[Any] = len(a )
SCREAMING_SNAKE_CASE_ : str = 0
SCREAMING_SNAKE_CASE_ : List[str] = 0
SCREAMING_SNAKE_CASE_ : Any = 0
# loop till the total weight do not reach max limit e.g. 15 kg and till i<length
while limit <= max_weight and i < length:
# flag value for encountered greatest element in sorted_profit_by_weight
SCREAMING_SNAKE_CASE_ : Optional[Any] = sorted_profit_by_weight[length - i - 1]
SCREAMING_SNAKE_CASE_ : Union[str, Any] = profit_by_weight.index(a )
SCREAMING_SNAKE_CASE_ : Dict = -1
# check if the weight encountered is less than the total weight
# encountered before.
if max_weight - limit >= weight[index]:
limit += weight[index]
# Adding profit gained for the given weight 1 ===
# weight[index]/weight[index]
gain += 1 * profit[index]
else:
# Since the weight encountered is greater than limit, therefore take the
# required number of remaining kgs and calculate profit for it.
# weight remaining / weight[index]
gain += (max_weight - limit) / weight[index] * profit[index]
break
i += 1
return gain
if __name__ == "__main__":
print(
'Input profits, weights, and then max_weight (all positive ints) separated by '
'spaces.'
)
lowerCAmelCase : Tuple = [int(x) for x in input('Input profits separated by spaces: ').split()]
lowerCAmelCase : Union[str, Any] = [int(x) for x in input('Input weights separated by spaces: ').split()]
lowerCAmelCase : Dict = int(input('Max weight allowed: '))
# Function Call
calc_profit(profit, weight, max_weight)
| 353 | 1 |
import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss
from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.models.bert.modeling_bert import (
BERT_INPUTS_DOCSTRING,
BERT_START_DOCSTRING,
BertEmbeddings,
BertLayer,
BertPooler,
BertPreTrainedModel,
)
def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ ) -> Dict:
'''simple docstring'''
UpperCAmelCase = torch.exp(UpperCamelCase__ )
UpperCAmelCase = torch.sum(UpperCamelCase__ , dim=1 ) # sum of exp(x_i)
UpperCAmelCase = torch.sum(x * exp_x , dim=1 ) # sum of x_i * exp(x_i)
return torch.log(UpperCamelCase__ ) - B / A
class A_ (nn.Module ):
def __init__( self , _A ):
'''simple docstring'''
super().__init__()
UpperCAmelCase = config.output_attentions
UpperCAmelCase = config.output_hidden_states
UpperCAmelCase = nn.ModuleList([BertLayer(_A ) for _ in range(config.num_hidden_layers )] )
UpperCAmelCase = nn.ModuleList([BertHighway(_A ) for _ in range(config.num_hidden_layers )] )
UpperCAmelCase = [-1 for _ in range(config.num_hidden_layers )]
def _lowercase ( self , _A ):
'''simple docstring'''
if (type(_A ) is float) or (type(_A ) is int):
for i in range(len(self.early_exit_entropy ) ):
UpperCAmelCase = x
else:
UpperCAmelCase = x
def _lowercase ( self , _A ):
'''simple docstring'''
UpperCAmelCase = pooler.state_dict()
for highway in self.highway:
for name, param in highway.pooler.state_dict().items():
param.copy_(loaded_model[name] )
def _lowercase ( self , _A , _A=None , _A=None , _A=None , _A=None , ):
'''simple docstring'''
UpperCAmelCase = ()
UpperCAmelCase = ()
UpperCAmelCase = ()
for i, layer_module in enumerate(self.layer ):
if self.output_hidden_states:
UpperCAmelCase = all_hidden_states + (hidden_states,)
UpperCAmelCase = layer_module(
_A , _A , head_mask[i] , _A , _A )
UpperCAmelCase = layer_outputs[0]
if self.output_attentions:
UpperCAmelCase = all_attentions + (layer_outputs[1],)
UpperCAmelCase = (hidden_states,)
if self.output_hidden_states:
UpperCAmelCase = current_outputs + (all_hidden_states,)
if self.output_attentions:
UpperCAmelCase = current_outputs + (all_attentions,)
UpperCAmelCase = self.highway[i](_A )
# logits, pooled_output
if not self.training:
UpperCAmelCase = highway_exit[0]
UpperCAmelCase = entropy(_A )
UpperCAmelCase = highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy
UpperCAmelCase = all_highway_exits + (highway_exit,)
if highway_entropy < self.early_exit_entropy[i]:
UpperCAmelCase = (highway_logits,) + current_outputs[1:] + (all_highway_exits,)
raise HighwayException(_A , i + 1 )
else:
UpperCAmelCase = all_highway_exits + (highway_exit,)
# Add last layer
if self.output_hidden_states:
UpperCAmelCase = all_hidden_states + (hidden_states,)
UpperCAmelCase = (hidden_states,)
if self.output_hidden_states:
UpperCAmelCase = outputs + (all_hidden_states,)
if self.output_attentions:
UpperCAmelCase = outputs + (all_attentions,)
UpperCAmelCase = outputs + (all_highway_exits,)
return outputs # last-layer hidden state, (all hidden states), (all attentions), all highway exits
@add_start_docstrings(
'''The Bert Model transformer with early exiting (DeeBERT). ''' , a_ , )
class A_ (a_ ):
def __init__( self , _A ):
'''simple docstring'''
super().__init__(_A )
UpperCAmelCase = config
UpperCAmelCase = BertEmbeddings(_A )
UpperCAmelCase = DeeBertEncoder(_A )
UpperCAmelCase = BertPooler(_A )
self.init_weights()
def _lowercase ( self ):
'''simple docstring'''
self.encoder.init_highway_pooler(self.pooler )
def _lowercase ( self ):
'''simple docstring'''
return self.embeddings.word_embeddings
def _lowercase ( self , _A ):
'''simple docstring'''
UpperCAmelCase = value
def _lowercase ( self , _A ):
'''simple docstring'''
for layer, heads in heads_to_prune.items():
self.encoder.layer[layer].attention.prune_heads(_A )
@add_start_docstrings_to_model_forward(_A )
def _lowercase ( self , _A=None , _A=None , _A=None , _A=None , _A=None , _A=None , _A=None , _A=None , ):
'''simple docstring'''
if input_ids is not None and inputs_embeds is not None:
raise ValueError('''You cannot specify both input_ids and inputs_embeds at the same time''' )
elif input_ids is not None:
UpperCAmelCase = input_ids.size()
elif inputs_embeds is not None:
UpperCAmelCase = inputs_embeds.size()[:-1]
else:
raise ValueError('''You have to specify either input_ids or inputs_embeds''' )
UpperCAmelCase = input_ids.device if input_ids is not None else inputs_embeds.device
if attention_mask is None:
UpperCAmelCase = torch.ones(_A , device=_A )
if encoder_attention_mask is None:
UpperCAmelCase = torch.ones(_A , device=_A )
if token_type_ids is None:
UpperCAmelCase = torch.zeros(_A , dtype=torch.long , device=_A )
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
# ourselves in which case we just need to make it broadcastable to all heads.
UpperCAmelCase = self.get_extended_attention_mask(_A , _A , _A )
# If a 2D ou 3D attention mask is provided for the cross-attention
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
if encoder_attention_mask.dim() == 3:
UpperCAmelCase = encoder_attention_mask[:, None, :, :]
if encoder_attention_mask.dim() == 2:
UpperCAmelCase = encoder_attention_mask[:, None, None, :]
UpperCAmelCase = encoder_extended_attention_mask.to(
dtype=next(self.parameters() ).dtype ) # fp16 compatibility
UpperCAmelCase = (1.0 - encoder_extended_attention_mask) * -1_00_00.0
# Prepare head mask if needed
# 1.0 in head_mask indicate we keep the head
# attention_probs has shape bsz x n_heads x N x N
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
UpperCAmelCase = self.get_head_mask(_A , self.config.num_hidden_layers )
UpperCAmelCase = self.embeddings(
input_ids=_A , position_ids=_A , token_type_ids=_A , inputs_embeds=_A )
UpperCAmelCase = self.encoder(
_A , attention_mask=_A , head_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , )
UpperCAmelCase = encoder_outputs[0]
UpperCAmelCase = self.pooler(_A )
UpperCAmelCase = (
sequence_output,
pooled_output,
) + encoder_outputs[
1:
] # add hidden_states and attentions if they are here
return outputs # sequence_output, pooled_output, (hidden_states), (attentions), highway exits
class A_ (a_ ):
def __init__( self , _A , _A ):
'''simple docstring'''
UpperCAmelCase = message
UpperCAmelCase = exit_layer # start from 1!
class A_ (nn.Module ):
def __init__( self , _A ):
'''simple docstring'''
super().__init__()
UpperCAmelCase = BertPooler(_A )
UpperCAmelCase = nn.Dropout(config.hidden_dropout_prob )
UpperCAmelCase = nn.Linear(config.hidden_size , config.num_labels )
def _lowercase ( self , _A ):
'''simple docstring'''
UpperCAmelCase = encoder_outputs[0]
UpperCAmelCase = self.pooler(_A )
# "return" pooler_output
# BertModel
UpperCAmelCase = (pooler_input, pooler_output) + encoder_outputs[1:]
# "return" bmodel_output
# Dropout and classification
UpperCAmelCase = bmodel_output[1]
UpperCAmelCase = self.dropout(_A )
UpperCAmelCase = self.classifier(_A )
return logits, pooled_output
@add_start_docstrings(
'''Bert Model (with early exiting - DeeBERT) with a classifier on top,
also takes care of multi-layer training. ''' , a_ , )
class A_ (a_ ):
def __init__( self , _A ):
'''simple docstring'''
super().__init__(_A )
UpperCAmelCase = config.num_labels
UpperCAmelCase = config.num_hidden_layers
UpperCAmelCase = DeeBertModel(_A )
UpperCAmelCase = nn.Dropout(config.hidden_dropout_prob )
UpperCAmelCase = nn.Linear(config.hidden_size , self.config.num_labels )
self.init_weights()
@add_start_docstrings_to_model_forward(_A )
def _lowercase ( self , _A=None , _A=None , _A=None , _A=None , _A=None , _A=None , _A=None , _A=-1 , _A=False , ):
'''simple docstring'''
UpperCAmelCase = self.num_layers
try:
UpperCAmelCase = self.bert(
_A , attention_mask=_A , token_type_ids=_A , position_ids=_A , head_mask=_A , inputs_embeds=_A , )
# sequence_output, pooled_output, (hidden_states), (attentions), highway exits
UpperCAmelCase = outputs[1]
UpperCAmelCase = self.dropout(_A )
UpperCAmelCase = self.classifier(_A )
UpperCAmelCase = (logits,) + outputs[2:] # add hidden states and attention if they are here
except HighwayException as e:
UpperCAmelCase = e.message
UpperCAmelCase = e.exit_layer
UpperCAmelCase = outputs[0]
if not self.training:
UpperCAmelCase = entropy(_A )
UpperCAmelCase = []
UpperCAmelCase = []
if labels is not None:
if self.num_labels == 1:
# We are doing regression
UpperCAmelCase = MSELoss()
UpperCAmelCase = loss_fct(logits.view(-1 ) , labels.view(-1 ) )
else:
UpperCAmelCase = CrossEntropyLoss()
UpperCAmelCase = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) )
# work with highway exits
UpperCAmelCase = []
for highway_exit in outputs[-1]:
UpperCAmelCase = highway_exit[0]
if not self.training:
highway_logits_all.append(_A )
highway_entropy.append(highway_exit[2] )
if self.num_labels == 1:
# We are doing regression
UpperCAmelCase = MSELoss()
UpperCAmelCase = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) )
else:
UpperCAmelCase = CrossEntropyLoss()
UpperCAmelCase = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) )
highway_losses.append(_A )
if train_highway:
UpperCAmelCase = (sum(highway_losses[:-1] ),) + outputs
# exclude the final highway, of course
else:
UpperCAmelCase = (loss,) + outputs
if not self.training:
UpperCAmelCase = outputs + ((original_entropy, highway_entropy), exit_layer)
if output_layer >= 0:
UpperCAmelCase = (
(outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:]
) # use the highway of the last layer
return outputs # (loss), logits, (hidden_states), (attentions), (highway_exits)
| 130 |
from __future__ import annotations
from collections.abc import Sequence
from typing import Literal
def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ ) -> str | Literal[False]:
'''simple docstring'''
UpperCAmelCase = list(UpperCamelCase__ )
UpperCAmelCase = list(UpperCamelCase__ )
UpperCAmelCase = 0
for i in range(len(UpperCamelCase__ ) ):
if lista[i] != lista[i]:
count += 1
UpperCAmelCase = '''_'''
if count > 1:
return False
else:
return "".join(UpperCamelCase__ )
def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ ) -> list[str]:
'''simple docstring'''
UpperCAmelCase = []
while True:
UpperCAmelCase = ['''$'''] * len(UpperCamelCase__ )
UpperCAmelCase = []
for i in range(len(UpperCamelCase__ ) ):
for j in range(i + 1 , len(UpperCamelCase__ ) ):
UpperCAmelCase = compare_string(binary[i] , binary[j] )
if k is False:
UpperCAmelCase = '''*'''
UpperCAmelCase = '''*'''
temp.append('''X''' )
for i in range(len(UpperCamelCase__ ) ):
if checka[i] == "$":
pi.append(binary[i] )
if len(UpperCamelCase__ ) == 0:
return pi
UpperCAmelCase = list(set(UpperCamelCase__ ) )
def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ ) -> list[str]:
'''simple docstring'''
UpperCAmelCase = []
for minterm in minterms:
UpperCAmelCase = ''''''
for _ in range(UpperCamelCase__ ):
UpperCAmelCase = str(minterm % 2 ) + string
minterm //= 2
temp.append(UpperCamelCase__ )
return temp
def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> bool:
'''simple docstring'''
UpperCAmelCase = list(UpperCamelCase__ )
UpperCAmelCase = list(UpperCamelCase__ )
UpperCAmelCase = 0
for i in range(len(UpperCamelCase__ ) ):
if lista[i] != lista[i]:
count_n += 1
return count_n == count
def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ ) -> list[str]:
'''simple docstring'''
UpperCAmelCase = []
UpperCAmelCase = [0] * len(UpperCamelCase__ )
for i in range(len(chart[0] ) ):
UpperCAmelCase = 0
UpperCAmelCase = -1
for j in range(len(UpperCamelCase__ ) ):
if chart[j][i] == 1:
count += 1
UpperCAmelCase = j
if count == 1:
UpperCAmelCase = 1
for i in range(len(UpperCamelCase__ ) ):
if select[i] == 1:
for j in range(len(chart[0] ) ):
if chart[i][j] == 1:
for k in range(len(UpperCamelCase__ ) ):
UpperCAmelCase = 0
temp.append(prime_implicants[i] )
while True:
UpperCAmelCase = 0
UpperCAmelCase = -1
UpperCAmelCase = 0
for i in range(len(UpperCamelCase__ ) ):
UpperCAmelCase = chart[i].count(1 )
if count_n > max_n:
UpperCAmelCase = count_n
UpperCAmelCase = i
if max_n == 0:
return temp
temp.append(prime_implicants[rem] )
for i in range(len(chart[0] ) ):
if chart[rem][i] == 1:
for j in range(len(UpperCamelCase__ ) ):
UpperCAmelCase = 0
def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ ) -> list[list[int]]:
'''simple docstring'''
UpperCAmelCase = [[0 for x in range(len(UpperCamelCase__ ) )] for x in range(len(UpperCamelCase__ ) )]
for i in range(len(UpperCamelCase__ ) ):
UpperCAmelCase = prime_implicants[i].count('''_''' )
for j in range(len(UpperCamelCase__ ) ):
if is_for_table(prime_implicants[i] , binary[j] , UpperCamelCase__ ):
UpperCAmelCase = 1
return chart
def __SCREAMING_SNAKE_CASE ( ) -> None:
'''simple docstring'''
UpperCAmelCase = int(input('''Enter the no. of variables\n''' ) )
UpperCAmelCase = [
float(UpperCamelCase__ )
for x in input(
'''Enter the decimal representation of Minterms \'Spaces Separated\'\n''' ).split()
]
UpperCAmelCase = decimal_to_binary(UpperCamelCase__ , UpperCamelCase__ )
UpperCAmelCase = check(UpperCamelCase__ )
print('''Prime Implicants are:''' )
print(UpperCamelCase__ )
UpperCAmelCase = prime_implicant_chart(UpperCamelCase__ , UpperCamelCase__ )
UpperCAmelCase = selection(UpperCamelCase__ , UpperCamelCase__ )
print('''Essential Prime Implicants are:''' )
print(UpperCamelCase__ )
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 130 | 1 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase_ : List[str] = logging.get_logger(__name__)
UpperCamelCase_ : Tuple = {
"""bigcode/gpt_bigcode-santacoder""": """https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json""",
}
class lowerCamelCase__ ( __lowerCamelCase ):
"""simple docstring"""
UpperCamelCase__ = '''gpt_bigcode'''
UpperCamelCase__ = ['''past_key_values''']
UpperCamelCase__ = {
'''hidden_size''': '''n_embd''',
'''max_position_embeddings''': '''n_positions''',
'''num_attention_heads''': '''n_head''',
'''num_hidden_layers''': '''n_layer''',
}
def __init__( self : Union[str, Any] ,a__ : Tuple=5_02_57 ,a__ : List[Any]=10_24 ,a__ : Dict=7_68 ,a__ : List[str]=12 ,a__ : List[str]=12 ,a__ : int=None ,a__ : int="gelu_pytorch_tanh" ,a__ : Optional[int]=0.1 ,a__ : List[Any]=0.1 ,a__ : Union[str, Any]=0.1 ,a__ : Optional[Any]=1e-5 ,a__ : List[str]=0.02 ,a__ : Union[str, Any]=True ,a__ : Optional[int]=True ,a__ : int=5_02_56 ,a__ : Optional[int]=5_02_56 ,a__ : str=True ,a__ : Union[str, Any]=True ,a__ : Optional[int]=True ,**a__ : Union[str, Any] ,):
a__ = vocab_size
a__ = n_positions
a__ = n_embd
a__ = n_layer
a__ = n_head
a__ = n_inner
a__ = activation_function
a__ = resid_pdrop
a__ = embd_pdrop
a__ = attn_pdrop
a__ = layer_norm_epsilon
a__ = initializer_range
a__ = scale_attn_weights
a__ = use_cache
a__ = attention_softmax_in_fpaa
a__ = scale_attention_softmax_in_fpaa
a__ = multi_query
a__ = bos_token_id
a__ = eos_token_id
super().__init__(bos_token_id=a__ ,eos_token_id=a__ ,**a__ )
| 394 |
'''simple docstring'''
import importlib
import math
import os
from dataclasses import dataclass
from enum import Enum
from typing import Any, Dict, Optional, Tuple, Union
import flax
import jax.numpy as jnp
from ..utils import BaseOutput
UpperCamelCase_ : str = """scheduler_config.json"""
class lowerCamelCase__ ( __lowerCamelCase ):
"""simple docstring"""
UpperCamelCase__ = 1
UpperCamelCase__ = 2
UpperCamelCase__ = 3
UpperCamelCase__ = 4
UpperCamelCase__ = 5
@dataclass
class lowerCamelCase__ ( __lowerCamelCase ):
"""simple docstring"""
UpperCamelCase__ = 42
class lowerCamelCase__ :
"""simple docstring"""
UpperCamelCase__ = SCHEDULER_CONFIG_NAME
UpperCamelCase__ = ['''dtype''']
UpperCamelCase__ = []
UpperCamelCase__ = True
@classmethod
def lowerCAmelCase_ ( cls : Optional[Any] ,a__ : Dict[str, Any] = None ,a__ : Optional[str] = None ,a__ : Union[str, Any]=False ,**a__ : Tuple ,):
a__ , a__ = cls.load_config(
pretrained_model_name_or_path=a__ ,subfolder=a__ ,return_unused_kwargs=a__ ,**a__ ,)
a__ , a__ = cls.from_config(a__ ,return_unused_kwargs=a__ ,**a__ )
if hasattr(a__ ,"create_state" ) and getattr(a__ ,"has_state" ,a__ ):
a__ = scheduler.create_state()
if return_unused_kwargs:
return scheduler, state, unused_kwargs
return scheduler, state
def lowerCAmelCase_ ( self : Any ,a__ : Union[str, os.PathLike] ,a__ : bool = False ,**a__ : Optional[int] ):
self.save_config(save_directory=a__ ,push_to_hub=a__ ,**a__ )
@property
def lowerCAmelCase_ ( self : List[str] ):
return self._get_compatibles()
@classmethod
def lowerCAmelCase_ ( cls : str ):
a__ = list(set([cls.__name__] + cls._compatibles ) )
a__ = importlib.import_module(__name__.split("." )[0] )
a__ = [
getattr(a__ ,a__ ) for c in compatible_classes_str if hasattr(a__ ,a__ )
]
return compatible_classes
def _lowerCAmelCase (_lowercase , _lowercase ):
"""simple docstring"""
assert len(_lowercase ) >= x.ndim
return jnp.broadcast_to(x.reshape(x.shape + (1,) * (len(_lowercase ) - x.ndim) ) , _lowercase )
def _lowerCAmelCase (_lowercase , _lowercase=0.999 , _lowercase=jnp.floataa ):
"""simple docstring"""
def alpha_bar(_lowercase ):
return math.cos((time_step + 0.008) / 1.008 * math.pi / 2 ) ** 2
a__ = []
for i in range(_lowercase ):
a__ = i / num_diffusion_timesteps
a__ = (i + 1) / num_diffusion_timesteps
betas.append(min(1 - alpha_bar(_lowercase ) / alpha_bar(_lowercase ) , _lowercase ) )
return jnp.array(_lowercase , dtype=_lowercase )
@flax.struct.dataclass
class lowerCamelCase__ :
"""simple docstring"""
UpperCamelCase__ = 42
UpperCamelCase__ = 42
UpperCamelCase__ = 42
@classmethod
def lowerCAmelCase_ ( cls : Tuple ,a__ : List[Any] ):
a__ = scheduler.config
if config.trained_betas is not None:
a__ = jnp.asarray(config.trained_betas ,dtype=scheduler.dtype )
elif config.beta_schedule == "linear":
a__ = jnp.linspace(config.beta_start ,config.beta_end ,config.num_train_timesteps ,dtype=scheduler.dtype )
elif config.beta_schedule == "scaled_linear":
# this schedule is very specific to the latent diffusion model.
a__ = (
jnp.linspace(
config.beta_start**0.5 ,config.beta_end**0.5 ,config.num_train_timesteps ,dtype=scheduler.dtype )
** 2
)
elif config.beta_schedule == "squaredcos_cap_v2":
# Glide cosine schedule
a__ = betas_for_alpha_bar(config.num_train_timesteps ,dtype=scheduler.dtype )
else:
raise NotImplementedError(
f'beta_schedule {config.beta_schedule} is not implemented for scheduler {scheduler.__class__.__name__}' )
a__ = 1.0 - betas
a__ = jnp.cumprod(a__ ,axis=0 )
return cls(
alphas=a__ ,betas=a__ ,alphas_cumprod=a__ ,)
def _lowerCAmelCase (_lowercase , _lowercase , _lowercase , _lowercase ):
"""simple docstring"""
a__ = state.alphas_cumprod
a__ = alphas_cumprod[timesteps] ** 0.5
a__ = sqrt_alpha_prod.flatten()
a__ = broadcast_to_shape_from_left(_lowercase , original_samples.shape )
a__ = (1 - alphas_cumprod[timesteps]) ** 0.5
a__ = sqrt_one_minus_alpha_prod.flatten()
a__ = broadcast_to_shape_from_left(_lowercase , original_samples.shape )
return sqrt_alpha_prod, sqrt_one_minus_alpha_prod
def _lowerCAmelCase (_lowercase , _lowercase , _lowercase , _lowercase ):
"""simple docstring"""
a__ , a__ = get_sqrt_alpha_prod(_lowercase , _lowercase , _lowercase , _lowercase )
a__ = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
return noisy_samples
def _lowerCAmelCase (_lowercase , _lowercase , _lowercase , _lowercase ):
"""simple docstring"""
a__ , a__ = get_sqrt_alpha_prod(_lowercase , _lowercase , _lowercase , _lowercase )
a__ = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample
return velocity
| 394 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.